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
TeamCohen/SEAL
src/com/rcwang/seal/expand/WrapperSaver.java
[ "public class XMLUtil {\r\n static public Exception exception = null;\r\n static private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n static private DocumentBuilder parser = null;\r\n \r\n /**\r\n * XSL transform (identity) to create text from Document.\r\n */\r\n static private Transformer identityTransformer;\r\n \r\n private Document document;\r\n \r\n static {\r\n // XML initialization\r\n try {\r\n dbf = DocumentBuilderFactory.newInstance();\r\n parser = dbf.newDocumentBuilder();\r\n } catch (ParserConfigurationException x) {\r\n x.printStackTrace();\r\n }\r\n }\r\n\r\n static {\r\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\r\n try {\r\n identityTransformer = transformerFactory.newTransformer();\r\n } catch (TransformerConfigurationException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n static public Document cloneDocument(Document document) {\r\n if (document == null) return null;\r\n Document result = newDocument();\r\n try {\r\n identityTransformer.transform(new DOMSource( document), new DOMResult( result));\r\n } catch (TransformerException e) {\r\n e.printStackTrace();\r\n }\r\n return result;\r\n }\r\n\r\n static public String document2String(Node document) {\r\n if (document == null) return null;\r\n\r\n StringWriter stringWriter = new StringWriter();\r\n try {\r\n identityTransformer.transform(new DOMSource( document), new StreamResult( stringWriter));\r\n } catch (TransformerException e) {\r\n e.printStackTrace();\r\n }\r\n return stringWriter.toString();\r\n }\r\n\r\n /**\r\n * Escapes special HTML entities\r\n * @param text\r\n * @return text with HTML entities escaped\r\n */\r\n public static String escapeXMLEntities(String text) {\r\n if (text == null)\r\n return null;\r\n text = text.replace(\"&\", \"&amp;\");\r\n text = text.replace(\"\\\"\", \"&quot;\");\r\n text = text.replace(\"<\", \"&lt;\");\r\n text = text.replace(\">\", \"&gt;\");\r\n text = text.replace(\"'\", \"&#039;\");\r\n return text;\r\n }\r\n \r\n /**\r\n * Returns first node at the bottom of path from node.\r\n * If element begins with '@', indicates an attribute, eg \"@id\"\r\n * The '#text' element indicates that the node has a single text child.\r\n * @param node Node to apply path to\r\n * @param path Path to apply\r\n * @return Node at bottom of path, or null\r\n */\r\n static public Node extractNode(Node node, String path) {\r\n if (node == null) return null;\r\n NodeList list = node.getChildNodes();\r\n if (path.equals(\"#text\"))\r\n return node.getFirstChild();\r\n else if (path.charAt(0) == '@')\r\n return node.getAttributes().getNamedItem( path.substring(1));\r\n else for (int j = 0; j < list.getLength(); j++)\r\n if (list.item(j).getNodeType() == Node.ELEMENT_NODE &&\r\n list.item(j).getNodeName().equals( path))\r\n return list.item(j);\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns all nodes at the bottom of path from node.\r\n * If element begins with '@', indicates an attribute, eg \"@id\"\r\n * The '#text' element indicates that the node has a single text child.\r\n * @param node Node to apply path to\r\n * @param path Path to apply\r\n * @return All Nodes at bottom of path. List may be empty, but not null.\r\n */\r\n static public List<Node> extractNodes(Node node, String path) {\r\n if (node == null) return new ArrayList<Node>();\r\n List<Node> result = new ArrayList<Node>();\r\n NodeList list = node.getChildNodes();\r\n if (path.equals(\"#text\"))\r\n result.add( node.getFirstChild());\r\n else if (path.charAt(0) == '@')\r\n result.add(node.getAttributes().getNamedItem( path.substring(1)));\r\n else for (int j = 0; j < list.getLength(); j++)\r\n if (list.item(j).getNodeType() == Node.ELEMENT_NODE &&\r\n list.item(j).getNodeName().equals( path))\r\n result.add( list.item(j));\r\n return result;\r\n }\r\n \r\n /**\r\n * Returns first node at the bottom of path from node.\r\n * If element begins with '@', indicates an attribute, eg \"@id\"\r\n * The '#text' element indicates that the node has a single text child.\r\n * @param node Node to apply path to\r\n * @param path Path to apply\r\n * @return Node at bottom of path, or null\r\n */\r\n static public Node extractPath(Node node, String[] path) {\r\n for (int i = 0; i < path.length; i++)\r\n node = extractNode( node, path[i]);\r\n return node;\r\n }\r\n\r\n /**\r\n * Returns all nodes at the bottom of path from node.\r\n * If element begins with '@', indicates an attribute, eg \"@id\"\r\n * The '#text' element indicates that the node has a single text child.\r\n * @param node Node to apply path to\r\n * @param path Path to apply\r\n * @return All nodes at bottom of path. List may be empty but not null.\r\n */\r\n static public List<Node> extractPaths(Node node, String[] path) {\r\n List<Node> result = new ArrayList<Node>();\r\n result.add( node);\r\n for (int i = 0; i < path.length; i++) {\r\n List<Node> children = new ArrayList<Node>();\r\n for (int j = 0; j < result.size(); j++)\r\n children.addAll( extractNodes((Node) result.get(j), path[i]));\r\n result = children;\r\n }\r\n return result;\r\n }\r\n\r\n static public Document newDocument() {\r\n return parser.newDocument();\r\n }\r\n\r\n static public Document parse(String text) {\r\n Document document = null;\r\n exception = null;\r\n try {\r\n document = riskyParse( text);\r\n } catch (Exception e) {\r\n exception = e;\r\n }\r\n return document;\r\n }\r\n\r\n public static String removeXMLTags(String in) {\r\n return in.replaceAll(\"<[^<>]+>\", \"\");\r\n }\r\n\r\n public static synchronized Document riskyParse(String text) throws Exception {\r\n InputSource is = new InputSource(new StringReader( text));\r\n return parser.parse(is);\r\n }\r\n\r\n /**\r\n * Unescapes special HTML entities\r\n * @param s\r\n * @return text with HTML entities escaped\r\n */\r\n public static String unescapeXMLEntities(String s) {\r\n if (s == null) return null;\r\n // handles common HTML entities\r\n s = s.replaceAll(\"(?i)&amp;\", \"&\");\r\n s = s.replaceAll(\"(?i)&gt;\", \">\");\r\n s = s.replaceAll(\"(?i)&lt;\", \"<\");\r\n s = s.replaceAll(\"(?i)&quot;\", \"\\\"\");\r\n s = s.replaceAll(\"(?i)&nbsp;\", \" \");\r\n s = s.replaceAll(\"(?i)&apos;\", \"'\");\r\n s = s.replaceAll(\"(?i)&middot;\", \"·\");\r\n\r\n // handles characters represented by (hexa)decimals\r\n StringBuffer sb = new StringBuffer();\r\n Matcher m = Pattern.compile(\"(?i)&#x?(\\\\d+);\").matcher(s);\r\n while(m.find()) {\r\n int radix = m.group(0).toLowerCase().contains(\"x\") ? 16 : 10;\r\n char c = (char)Integer.valueOf(m.group(1), radix).intValue();\r\n String rep = Character.toString(c);\r\n switch(c) {\r\n case '\\\\': rep = \"\\\\\\\\\"; break;\r\n case '$': rep = \"\\\\$\"; break;\r\n }\r\n m.appendReplacement(sb, rep);\r\n }\r\n m.appendTail(sb);\r\n return sb.toString();\r\n }\r\n\r\n public XMLUtil() {\r\n this(null);\r\n }\r\n \r\n public XMLUtil(Document document) {\r\n this.document = (document == null) ? newDocument() : document;\r\n }\r\n \r\n public Attr[] createAttrsFor(Element element, Object[] keyValuePairs) {\r\n int numAttrs = keyValuePairs.length / 2;\r\n Attr[] attrs = new Attr[numAttrs];\r\n for (int i = 0; i < numAttrs; i++) {\r\n Object keyObj = keyValuePairs[i*2];\r\n Object valueObj = keyValuePairs[i*2+1];\r\n if (keyObj == null || valueObj == null)\r\n continue;\r\n attrs[i] = document.createAttribute(keyObj.toString());\r\n attrs[i].setNodeValue(valueObj.toString());\r\n }\r\n for (Attr attr : attrs)\r\n if (attr != null)\r\n element.setAttributeNode(attr);\r\n return attrs;\r\n }\r\n\r\n /**\r\n * Creates a new element with given text: <element>text</element>\r\n * @param element Name of new element tag\r\n * @param text Text that element tag should contain\r\n * @return new element node. (not actually added to document yet)\r\n */\r\n public Element createElement(String element, String text) {\r\n Element node = document.createElement( element);\r\n if (text != null) {\r\n Node textNode = document.createTextNode( text);\r\n node.insertBefore( textNode, null);\r\n }\r\n return node;\r\n }\r\n \r\n public Element createElementBelow(Element parentNode, String element, String text) {\r\n Element childNode = createElement(element, text);\r\n parentNode.insertBefore(childNode, null);\r\n return childNode;\r\n }\r\n\r\n /**\r\n * Creates a new element path with given text: <element1><element2>text</element2></element1>\r\n * @param path Path of new element tags\r\n * @param text Text that element tag should contain\r\n * @return Array of new element nodes. First node is top node, last is text node.\r\n */\r\n public Element[] createPath(String[] path, String text) {\r\n Element[] elements = new Element[ path.length];\r\n for (int i = 0; i < path.length; i++)\r\n elements[i] = document.createElement( path[i]);\r\n Node textNode = document.createTextNode( text);\r\n for (int i = 0; i < path.length - 1; i++)\r\n elements[i].insertBefore( elements[i+1], null);\r\n elements[ path.length - 1].insertBefore( textNode, null);\r\n return elements;\r\n }\r\n \r\n public Document getDocument() {\r\n return document;\r\n }\r\n}\r", "public class Helper {\r\n \r\n public static Logger log = Logger.getLogger(Helper.class);\r\n \r\n public static final String UNICODE = \"UTF-8\";\r\n public static final String COMMON_ENCODING = \"ISO-8859-1\";\r\n public static final String DATE_FORMAT = \"yyyy-MM-dd\"; // must match below\r\n public static final String DATE_PATTERN = \"\\\\d+{4}-\\\\d+{2}-\\\\d+{2}\"; // must match above\r\n public static final String TIME_FORMAT = \"h:mm:ss aa\";\r\n public static final String DATE_TIME_FORMAT = DATE_FORMAT + \" \" + TIME_FORMAT;\r\n public static final NumberFormat NUM_FORMAT = NumberFormat.getInstance();\r\n \r\n public static String repeat(char c, int n) {\r\n StringBuffer buf = new StringBuffer();\r\n for (; n > 0; n--)\r\n buf.append(c);\r\n return buf.toString();\r\n }\r\n \r\n public static String center(String s, char filler, int width) {\r\n if (s.length() >= width) return s;\r\n int numFillers = (width - s.length()) / 2;\r\n return repeat(filler, numFillers) + s + repeat(filler, numFillers);\r\n }\r\n \r\n public static String addQuote(String s) {\r\n s = s.trim();\r\n if (!s.startsWith(\"\\\"\"))\r\n s = \"\\\"\" + s;\r\n if (!s.endsWith(\"\\\"\"))\r\n s += \"\\\"\";\r\n return s;\r\n }\r\n \r\n public static double getPDF(double x, double avg, double std) {\r\n double diff = x - avg;\r\n double exp = Math.exp(-0.5 * Math.pow(diff / std, 2));\r\n return exp / (std * Math.sqrt(2 * Math.PI));\r\n }\r\n \r\n public static String addQuote(String[] ss) {\r\n StringBuffer buf = new StringBuffer();\r\n for (String s : ss)\r\n buf.append(buf.length() > 0 ? \" \" : \"\").append(addQuote(s));\r\n return buf.toString();\r\n }\r\n \r\n public static File createDir(File dir) {\r\n if (dir != null && !dir.isDirectory()) {\r\n log.info(\"Creating directory: \" + dir.getAbsolutePath());\r\n if (!dir.mkdirs())\r\n log.error(\"Could not create requested directories for \"+dir.getAbsolutePath());\r\n }\r\n return dir;\r\n }\r\n \r\n public static File createTempFile (String content) {\r\n File temp = null;\r\n try {\r\n temp = File.createTempFile(\"tmp\", null);\r\n } catch (IOException ioe) {\r\n log.error(\"Error creating temp file: \" + ioe);\r\n return null;\r\n }\r\n temp.deleteOnExit();\r\n writeToFile(temp, content, \"UTF-8\", false);\r\n return temp;\r\n }\r\n \r\n public static String decodeURLString(String s) {\r\n if (s == null) return null;\r\n try {\r\n return URLDecoder.decode(s, UNICODE);\r\n } catch (UnsupportedEncodingException e) {\r\n log.error(e.toString());\r\n return null;\r\n }\r\n }\r\n \r\n public static void die(String s) {\r\n System.err.println(\"[FATAL] \" + s);\r\n System.exit(1);\r\n }\r\n \r\n public static boolean empty(EntityList entityList) {\r\n return entityList == null || entityList.isEmpty();\r\n }\r\n \r\n public static boolean empty(String s) {\r\n return s == null || s.trim().length() == 0;\r\n }\r\n \r\n // encode the query and formulate the query URL\r\n public static String encodeURLString(String s) {\r\n if (s == null) return null;\r\n try {\r\n return URLEncoder.encode(s, UNICODE);\r\n } catch (UnsupportedEncodingException e) {\r\n log.error(e.toString());\r\n return null;\r\n }\r\n }\r\n \r\n /**\r\n * Returns the String bounded by \"left\" and \"after\" in String s\r\n * @param s\r\n * @param left\r\n * @param right\r\n * @return the bounded String\r\n */\r\n public static String extract(String s, String left, String right) {\r\n int leftOffset, rightOffset;\r\n if (left == null) {\r\n leftOffset = 0;\r\n left = \"\";\r\n } else {\r\n leftOffset = s.indexOf(left);\r\n if (leftOffset == -1)\r\n return null;\r\n }\r\n if (right == null) {\r\n rightOffset = s.length();\r\n } else {\r\n rightOffset = s.indexOf(right, leftOffset + left.length());\r\n if (rightOffset == -1)\r\n return null;\r\n }\r\n return s.substring(leftOffset + left.length(), rightOffset);\r\n }\r\n\r\n public static String formatNumber(double number, int decimal) {\r\n NUM_FORMAT.setMaximumFractionDigits(decimal);\r\n NUM_FORMAT.setMinimumFractionDigits(decimal);\r\n return NUM_FORMAT.format(number).replace(\",\", \"\");\r\n }\r\n \r\n public static int getStringSize(String s) {\r\n int docSize = -1;\r\n try {\r\n docSize = s.getBytes(\"US-ASCII\").length;\r\n } catch (UnsupportedEncodingException e) {\r\n e.printStackTrace();\r\n }\r\n return docSize;\r\n }\r\n \r\n /***\r\n * Creates a unique ID based on the current date and time\r\n * @return a unique ID\r\n */\r\n public static String getUniqueID () {\r\n Calendar cal = Calendar.getInstance(TimeZone.getDefault());\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"MMdd-HHmmss\");\r\n sdf.setTimeZone(TimeZone.getDefault());\r\n return sdf.format(cal.getTime());\r\n }\r\n \r\n public static Properties loadPropertiesFile(File propFile) {\r\n if (propFile == null)\r\n return null;\r\n Properties props = new Properties();\r\n InputStream in;\r\n try {\r\n in = readFileToStream(propFile);\r\n if (in != null) {\r\n props.load(in);\r\n in.close();\r\n }\r\n } catch (FileNotFoundException e) {\r\n log.error(\"Properties file not found: \" + e);\r\n return null;\r\n } catch (IOException e) {\r\n log.error(\"Read properties file error: \" + e);\r\n return null;\r\n }\r\n return props;\r\n }\r\n \r\n public static <T> T loadSerialized(File file, Class<? extends T> c) {\r\n log.info(\"Loading serialized object from: \" + file);\r\n FileInputStream fis = null;\r\n ObjectInputStream in = null;\r\n T object = null;\r\n try {\r\n fis = new FileInputStream(file);\r\n in = new ObjectInputStream(fis);\r\n object = c.cast(in.readObject());\r\n in.close();\r\n } catch(IOException ex) {\r\n ex.printStackTrace();\r\n } catch(ClassNotFoundException ex) {\r\n ex.printStackTrace();\r\n }\r\n return object;\r\n }\r\n\r\n public static double log2(double d) {\r\n return Math.log(d) / Math.log(2);\r\n }\r\n \r\n public static String merge(String[] strList, String delimiter) {\r\n StringBuffer buf = new StringBuffer();\r\n for (String s : strList) {\r\n if (buf.length() > 0)\r\n buf.append(delimiter);\r\n buf.append(s);\r\n }\r\n return buf.toString();\r\n }\r\n \r\n public static void printElapsedTime(long startTime) {\r\n log.info(\"Elapsed time: \" + (System.currentTimeMillis() - startTime) / 1000.0 + \" seconds\");\r\n }\r\n \r\n public static void printDebugInfo() {\r\n log.info(\"Originator Size: \" + Originator.size() + \" (\" + Originator.getNumStrings() + \")\");\r\n log.info(\"String Size: \" + StringFactory.getStrSize());\r\n log.info(\"String ID Size: \" + StringFactory.getIDSize());\r\n Helper.printMemoryUsed();\r\n }\r\n \r\n public static void printMemoryUsed() {\r\n for (int i = 0; i < 3; i++) System.gc();\r\n long memSize = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\r\n String memSizeStr = Helper.formatNumber((double) memSize / 1024 / 1024, 2);\r\n log.info(\" Memory used: \" + memSizeStr + \"MB\");\r\n }\r\n \r\n public static String readFile(File f) {\r\n return readFile(f, \"UTF-8\", false);\r\n }\r\n\r\n /**\r\n * Reads in a file, if not found, search on the class path\r\n * @param file the input file\r\n * @param charset the character set\r\n * @param binary is the file binary or text (non-binary)?\r\n * @return the content of the file\r\n */\r\n public static String readFile(File file, String charset, boolean binary) {\r\n if (file == null || charset == null)\r\n return null;\r\n InputStream in = readFileToStream(file);\r\n if (in == null)\r\n return null;\r\n StringBuffer buf = new StringBuffer();\r\n try {\r\n BufferedReader bReader = new BufferedReader(new InputStreamReader(in, charset));\r\n if (!binary) {\r\n String line;\r\n while ((line = bReader.readLine()) != null)\r\n buf.append(line).append(\"\\n\");\r\n } else {\r\n char[] c = new char[(int) file.length()];\r\n bReader.read(c);\r\n buf.append(c);\r\n }\r\n bReader.close();\r\n } catch (Exception e) {\r\n log.error(\"Could not read \\\"\" + file + \"\\\": \" + e);\r\n return null;\r\n }\r\n String result = buf.toString();\r\n // get rid of BOM (byte order marker) from UTF-8 file\r\n if (result.length() > 0 && result.charAt(0) == 65279)\r\n result = result.substring(1);\r\n return result;\r\n }\r\n \r\n public static InputStream readFileToStream(File in) {\r\n if (in == null) return null;\r\n InputStream s = null;\r\n try {\r\n if (in.exists()) // if file exist locally\r\n s = new FileInputStream(in);\r\n if (s == null) // if file exist somewhere on the class path\r\n s = ClassLoader.getSystemResourceAsStream(in.getPath());\r\n if (s == null) { // if file still could not be found\r\n log.error(\"Could not find \\\"\" + in + \"\\\" locally (\"+in.getAbsolutePath()+\") or on classpath\");\r\n return null;\r\n }\r\n } catch (Exception e) {\r\n log.error(\"Could not read \\\"\" + in + \"\\\": \" + e);\r\n return null;\r\n }\r\n return s;\r\n }\r\n \r\n public static void recursivelyRemove(File f) {\r\n if (f == null || !f.exists()) return;\r\n if (f.isDirectory()) {\r\n File[] files = f.listFiles();\r\n for (File file : files)\r\n recursivelyRemove(file);\r\n }\r\n String type = f.isDirectory() ? \"directory\" : \"file\";\r\n boolean deleted = f.delete();\r\n if (!deleted)\r\n log.error(\"Cannot delete the \" + type + \": \" + f);\r\n else log.debug(\"Successfully deleted the \" + type + \": \" + f);\r\n }\r\n \r\n public static String removeQuote(String s) {\r\n if (s == null) return null;\r\n s = s.trim();\r\n if (s.startsWith(\"\\\"\") && s.endsWith(\"\\\"\"))\r\n s = s.substring(1, s.length()-1);\r\n return s;\r\n }\r\n \r\n public static void saveSerialized(Object object, File file, boolean overwrite) {\r\n if (!overwrite && file.exists()) {\r\n log.info(\"Serialized file \" + file + \" already exists! Skip saving...\");\r\n return;\r\n }\r\n log.info(\"Saving serialized object to: \" + file);\r\n if (file.getParentFile() != null)\r\n Helper.createDir(file.getParentFile());\r\n FileOutputStream fos = null;\r\n ObjectOutputStream out = null;\r\n try {\r\n fos = new FileOutputStream(file);\r\n out = new ObjectOutputStream(fos);\r\n out.writeObject(object);\r\n out.close();\r\n } catch(IOException ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n public static void sortByLength(List<String> list, final boolean ascending) {\r\n Comparator<String> c = new Comparator<String>() {\r\n public int compare(String e1, String e2) {\r\n int length1 = e1.length();\r\n int length2 = e2.length();\r\n if (ascending)\r\n return Double.compare(length1, length2);\r\n else return Double.compare(length2, length1);\r\n }\r\n };\r\n Collections.sort(list, c);\r\n }\r\n \r\n /**\r\n * Converts an integer to a binary array with a specified max size\r\n * input: 11, output: [1011]\r\n * @param integer\r\n * @param size\r\n * @return\r\n */\r\n public static boolean[] toBinaryArray(int integer, int size) {\r\n boolean[] b = new boolean[size];\r\n String s = Integer.toBinaryString(integer);\r\n if (s.length() > b.length)\r\n s = s.substring(s.length()-b.length);\r\n // algorithm bug fixed kmr jan 2012\r\n // the 1s place is at the end of the string, so start there\r\n for (int i = s.length()-1; i >=0; i--)\r\n // the 1s element is at b[0] so start there\r\n b[s.length()-1-i] = (s.charAt(i) == '1');\r\n return b;\r\n }\r\n\r\n public static String toFileName(String s) {\r\n return s.replaceAll(\"[\\\\/:\\\\*?\\\"<>|\\\\s]+\", \"_\");\r\n }\r\n\r\n public static File toFileOrDie(String filename) {\r\n if (filename == null)\r\n die(\"Could not find the file: \" + filename);\r\n File file = new File(filename);\r\n if (!file.exists())\r\n die(\"Could not find the file: \" + filename);\r\n return file;\r\n }\r\n\r\n public static String toReadableString(Collection<String> list) {\r\n Set<String> seeds = new TreeSet<String>();\r\n if (list != null)\r\n seeds.addAll(list);\r\n StringBuffer buf = new StringBuffer();\r\n buf.append(\"{\");\r\n for (String seed : seeds) {\r\n if (buf.length() > 1)\r\n buf.append(\", \");\r\n buf.append(seed);\r\n }\r\n buf.append(\"}\");\r\n return buf.toString();\r\n }\r\n\r\n public static String toReadableDouble(Collection<Double> doubles) {\r\n StringBuffer buf = new StringBuffer();\r\n buf.append(\"{\");\r\n for (Double d : doubles) {\r\n if (buf.length() > 1)\r\n buf.append(\", \");\r\n buf.append(Helper.formatNumber(d, 5));\r\n }\r\n buf.append(\"}\");\r\n return buf.toString();\r\n }\r\n \r\n public static String toReadableTime(Long timestamp, String format) {\r\n SimpleDateFormat sdf = new SimpleDateFormat(format);\r\n sdf.setTimeZone(TimeZone.getDefault());\r\n if (timestamp == null)\r\n timestamp = System.currentTimeMillis();\r\n return sdf.format(new Date(timestamp));\r\n }\r\n\r\n public static String toSeedsFileName(Collection<String> seedList) {\r\n Set<String> seeds = new TreeSet<String>();\r\n if (seedList != null)\r\n seeds.addAll(seedList);\r\n StringBuffer buf = new StringBuffer();\r\n for (String seed : seeds) {\r\n if (buf.length() > 0)\r\n buf.append(\"+\");\r\n buf.append(seed);\r\n }\r\n return toFileName(buf.toString());\r\n }\r\n \r\n /**\r\n * Converts a String array to a Collection of Unicode\r\n * @param strs\r\n * @return\r\n */\r\n public static Set<String> toUnicode(Collection<String> strs) {\r\n Set<String> set = new HashSet<String>();\r\n if (strs == null) return set;\r\n for (String s : strs) {\r\n s = toUnicode(s);\r\n if (!empty(s))\r\n set.add(s.toLowerCase()); // added 04/21/2008\r\n }\r\n return set;\r\n }\r\n\r\n /**\r\n * Converts a string to unicode\r\n * @param s\r\n * @return\r\n */\r\n public static String toUnicode(String s) {\r\n if (s == null) return null;\r\n try {\r\n s = new String(s.getBytes(COMMON_ENCODING), UNICODE);\r\n } catch (UnsupportedEncodingException e) {\r\n log.error(e);\r\n }\r\n return s.trim();\r\n }\r\n\r\n public static URL toURL(String s) {\r\n try {\r\n return new URL(s);\r\n } catch (MalformedURLException e) {\r\n return null;\r\n }\r\n }\r\n\r\n public static void writeToFile(File out, String content) {\r\n writeToFile(out, content, UNICODE, false);\r\n }\r\n\r\n public static void writeToFile(File out, String content, boolean append) {\r\n writeToFile(out, content, UNICODE, append);\r\n }\r\n \r\n public static void writeToFile(File out, String content, String charset, boolean append) {\r\n if (out == null || content == null) return;\r\n try {\r\n BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out, append), charset));\r\n bWriter.write(content);\r\n bWriter.close();\r\n } catch (IOException e) {\r\n log.error(\"Writing to \" + out + \": \" + e);\r\n }\r\n }\r\n\r\npublic static Object toReadableString(Set<EntityLiteral> contents) {\r\n Set<EntityLiteral> seeds = new TreeSet<EntityLiteral>();\r\n if (contents != null)\r\n seeds.addAll(contents);\r\n StringBuffer buf = new StringBuffer();\r\n buf.append(\"{\");\r\n for (EntityLiteral seed : seeds) {\r\n if (buf.length() > 1)\r\n buf.append(\", \");\r\n buf.append(seed.toString());\r\n }\r\n buf.append(\"}\");\r\n return buf.toString();\r\n }\r\n}\r", "public class StringFactory {\r\n\r\n public static class SID implements Iterable<String> {\r\n \r\n String[] array;\r\n \r\n public SID(List<String> strs) {\r\n array = strs.toArray(new String[strs.size()]);\r\n }\r\n\r\n public SID(SID id) {\r\n this(id.array);\r\n }\r\n\r\n public SID(String[] array) {\r\n this.array = array.clone();\r\n }\r\n \r\n public void append(SID sid) {\r\n append(sid.array);\r\n }\r\n \r\n public void append(String s) {\r\n append(StringFactory.toID(s));\r\n }\r\n \r\n public void append(String[] array) {\r\n String[] array2 = new String[this.array.length+array.length];\r\n System.arraycopy(this.array, 0, array2, 0, this.array.length);\r\n System.arraycopy(array, 0, array2, this.array.length, array.length);\r\n this.array = array2;\r\n }\r\n \r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) return true;\r\n if (obj == null) return false;\r\n if (getClass() != obj.getClass()) return false;\r\n final SID other = (SID) obj;\r\n if (!Arrays.equals(array, other.array))\r\n return false;\r\n return true;\r\n }\r\n \r\n @Override\r\n public int hashCode() {\r\n return 31 + Arrays.hashCode(array);\r\n }\r\n \r\n public Iterator<String> iterator() {\r\n return Arrays.asList(array).iterator();\r\n }\r\n \r\n public int length() {\r\n int length = 0;\r\n for (String s : this)\r\n length += s.length();\r\n return length;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return StringFactory.toName(this);\r\n }\r\n \r\n public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }\r\n \r\n public SID toLower() {\r\n \treturn StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));\r\n }\r\n }\r\n public static class RSID extends SID {\r\n int boundary;\r\n\r\n public RSID(List<String> strs) { super(strs); }\r\n public RSID(SID id) { super(id); }\r\n public RSID(String[] array) { super(array); }\r\n \r\n public RSID(SID a1, SID a2) {\r\n super(a1); \r\n boundary = a1.array.length;\r\n super.append(a2);\r\n }\r\n \r\n public EntityLiteral toLiteral() {\r\n return new EntityLiteral(\r\n StringFactory.toName(Arrays.copyOfRange(this.array, 0, boundary)),\r\n StringFactory.toName(Arrays.copyOfRange(this.array, boundary, this.array.length))\r\n );\r\n }\r\n }\r\n \r\n /*public static class SID extends ArrayList<String> {\r\n private static final long serialVersionUID = -746676179936368932L;\r\n \r\n public SID() {\r\n super();\r\n }\r\n \r\n public SID(SID id) {\r\n this();\r\n this.addAll(id);\r\n }\r\n \r\n public void append(SID id) {\r\n this.addAll(id);\r\n }\r\n \r\n public int length() {\r\n int length = 0;\r\n for (String s : this)\r\n length += s.length();\r\n return length;\r\n }\r\n \r\n @Override\r\n public String toString() {\r\n return StringFactory.toName(this);\r\n }\r\n }*/\r\n \r\n public static final boolean DISABLE_CACHE = false; // reduces memory for small runs\r\n private static Map<String, String> strMap = new Cache<String, String>();\r\n private static Map<SID, SID> sidMap = new Cache<SID, SID>();\r\n private static StringBuffer buf = new StringBuffer();\r\n private static String delimiter = \" \"; // space\r\n \r\n public static void clear() {\r\n strMap.clear();\r\n sidMap.clear();\r\n }\r\n \r\n public static SID get(SID sid) {\r\n if (DISABLE_CACHE) return sid;\r\n SID sid2 = sidMap.get(sid);\r\n if (sid2 == null) {\r\n sidMap.put(sid, sid);\r\n return sid;\r\n } else return sid2;\r\n }\r\n \r\n public static String get(String s) {\r\n if (DISABLE_CACHE) return s;\r\n String s2 = strMap.get(s);\r\n if (s2 == null) {\r\n strMap.put(s, s);\r\n return s;\r\n } else return s2;\r\n }\r\n \r\n public static String getDelimiter() {\r\n return delimiter;\r\n }\r\n \r\n public static int getIDSize() {\r\n return sidMap.size();\r\n }\r\n \r\n public static int getStrSize() {\r\n return strMap.size();\r\n }\r\n \r\n public static void main(String args[]) {\r\n String[] tests = new String[] {\r\n \"\",\r\n \" \",\r\n \" \",\r\n \".\",\r\n \". \",\r\n \" .\",\r\n \"..\",\r\n };\r\n \r\n boolean failed = false;\r\n for (String test : tests) {\r\n SID id = StringFactory.toID(test);\r\n String s = StringFactory.toName(id);\r\n if (!test.equals(s)) {\r\n failed = true;\r\n break;\r\n }\r\n }\r\n \r\n if (failed)\r\n System.out.println(\"FAILURE!!!\");\r\n else System.out.println(\"SUCCESS!!!\");\r\n }\r\n \r\n public static void setDelimiter(String delimiter) {\r\n StringFactory.delimiter = delimiter;\r\n }\r\n \r\n /**\r\n * Sort by alphabetical order\r\n * @param idSet\r\n * @return\r\n */\r\n public static List<SID> sortIDs(Set<SID> idSet) {\r\n Map<String, SID> strIDMap = new HashMap<String, SID>();\r\n for (SID id : idSet)\r\n strIDMap.put(toName(id), id);\r\n List<String> strList = new ArrayList<String>(strIDMap.keySet());\r\n Collections.sort(strList);\r\n List<SID> resultList = new ArrayList<SID>();\r\n for (String str : strList)\r\n resultList.add(get(strIDMap.get(str)));\r\n return resultList;\r\n }\r\n \r\n /**\r\n * Splits a String\r\n * @param name\r\n * @return a new List\r\n */\r\n public static SID toID(String name) {\r\n if (name == null) return null;\r\n List<String> ids = new ArrayList<String>();\r\n int index = 0, prevIndex = 0;\r\n if (name.length() > 0) {\r\n while ((index = name.indexOf(delimiter, prevIndex)) != -1) {\r\n ids.add(get(name.substring(prevIndex, index)));\r\n prevIndex = index + delimiter.length();\r\n if (prevIndex == name.length())\r\n break;\r\n }\r\n }\r\n if (prevIndex > name.length())\r\n System.err.println(\"Something is wrong!!!\");\r\n else if (prevIndex == name.length())\r\n ids.add(get(\"\"));\r\n else if (index == -1)\r\n ids.add(get(name.substring(prevIndex)));\r\n return get(new SID(ids));\r\n }\r\n \r\n public static SID toID(EntityLiteral name) {\r\n if (name == null) return null;\r\n if (name.arg2 == null) return toID(name.arg1);\r\n SID id1 = toID(name.arg1);\r\n SID id2 = toID(name.arg2);\r\n return new RSID(id1,id2);\r\n }\r\n \r\n \r\n public static String toName(SID id) {\r\n if (id == null) return null;\r\n return toName(id.array);\r\n }\r\n /**\r\n * Combines a list of Strings\r\n * @param id\r\n * @return a new String\r\n */\r\n public static String toName(String ... id) {\r\n if (id == null) return null;\r\n buf.setLength(0);\r\n for (Object o : id) {\r\n if (buf.length() > 0)\r\n buf.append(delimiter);\r\n buf.append(o);\r\n }\r\n return buf.toString();\r\n }\r\n\r\n public static Set<String> toNames(Set<SID> idSet) {\r\n Set<String> names = new HashSet<String>();\r\n for (SID id : idSet)\r\n names.add(toName(id));\r\n return names;\r\n }\r\n}\r", "public static class EntityLiteral implements Comparable<EntityLiteral> {\r\n public String arg1;\r\n public String arg2;\r\n public EntityLiteral(String arg1) { this.arg1=StringFactory.get(arg1); }\r\n public EntityLiteral(String arg1, String arg2) { this(arg1); this.arg2 = StringFactory.get(arg2); }\r\n public EntityLiteral(String ... names) {\r\n if (names.length > 0) this.arg1=StringFactory.get(names[0]);\r\n if (names.length > 1) this.arg2 = StringFactory.get(names[1]);\r\n if (names.length > 2) log.warn(\"Attempt to create entity literal with more than two strings:\" + names);\r\n }\r\n public String toString() { \r\n StringBuilder sb = new StringBuilder(arg1);\r\n if (arg2!= null) sb.append(Entity.RELATION_SEPARATOR).append(arg2);\r\n return sb.toString();\r\n }\r\n final public boolean equals(Object o) {\r\n if (! (o instanceof EntityLiteral)) return false;\r\n EntityLiteral e = (EntityLiteral) o;\r\n return arg1 == e.arg1 && arg2 == e.arg2; \r\n }\r\n final public int hashCode() { \r\n int a1 = arg1.hashCode();\r\n if (arg2!=null) return a1 ^ arg2.hashCode();\r\n return a1;\r\n }\r\n final public int compareTo(EntityLiteral e) {\r\n return this.toString().compareTo(e.toString());\r\n }\r\n}\r", "public class DocumentSet implements Iterable<Document>, Serializable {\r\n \r\n public static final double DELTA = 1e-10;\r\n public static final int DEFAULT_MAX_DOCS_IN_XML = 5;\r\n \r\n private static final long serialVersionUID = 7211782411429869181L;\r\n private Map<Document, Document> docMap;\r\n private List<Document> docList;\r\n private Set<EntityLiteral> extractions;\r\n private Set<Wrapper> wrappers;\r\n private Feature scoredByFeature;\r\n private int maxDocsInXML;\r\n \r\n public DocumentSet() {\r\n setMaxDocsInXML(DEFAULT_MAX_DOCS_IN_XML);\r\n docMap = new HashMap<Document, Document>();\r\n docList = new ArrayList<Document>();\r\n extractions = new HashSet<EntityLiteral>();\r\n wrappers = new HashSet<Wrapper>();\r\n }\r\n \r\n public DocumentSet(DocumentSet documents) {\r\n this();\r\n addAll(documents);\r\n }\r\n \r\n public void add(Document document) {\r\n if (document == null) return;\r\n Document doc = docMap.get(document);\r\n if (doc == document) return;\r\n if (doc == null) {\r\n docMap.put(document, document);\r\n docList.add(document);\r\n } else {\r\n doc.merge(document);\r\n }\r\n wrappers.addAll(document.getWrappers());\r\n extractions.addAll(document.getExtractions());\r\n }\r\n \r\n public void addAll(DocumentSet documents) {\r\n if (documents == null) return;\r\n for (Document document : documents)\r\n add(document);\r\n }\r\n \r\n public void assignScore(Feature feature) {\r\n scoredByFeature = feature;\r\n if (docList.size() == 0) return;\r\n sort();\r\n double maxScore = docList.get(0).getWeight() + DELTA;\r\n double minScore = docList.get(docList.size()-1).getWeight() - DELTA;\r\n for (Document document : docList) {\r\n double weight = (document.getWeight() - minScore) / (maxScore - minScore);\r\n document.setWeight(weight);\r\n }\r\n }\r\n \r\n public void clear() {\r\n docMap.clear();\r\n docList.clear();\r\n extractions.clear();\r\n wrappers.clear();\r\n }\r\n \r\n public void clearExtractions() {\r\n for (Document document : this)\r\n document.clearExtractions();\r\n extractions.clear();\r\n }\r\n \r\n public void clearStats() {\r\n clearWrappers();\r\n clearExtractions();\r\n }\r\n \r\n /*public double getConfidence() {\r\n double w = 0;\r\n for (Document document : this) {\r\n if (document.length() == 0) continue;\r\n int sum = 0;\r\n for (Wrapper wrapper : document.getWrappers())\r\n sum += wrapper.length() * wrapper.getNumCommonTypes();\r\n w += (double) sum / document.length();\r\n }\r\n w = w / this.size();\r\n return w;\r\n }*/\r\n \r\n public void clearWrappers() {\r\n for (Document document : this)\r\n document.clearWrappers();\r\n wrappers.clear();\r\n }\r\n \r\n public Document get(int i) {\r\n return docList.get(i);\r\n }\r\n \r\n public double getContentQuality() {\r\n int numWrappers = getNumWrappers();\r\n if (numWrappers == 0) return 0;\r\n return getSumWrapperLength() / numWrappers;\r\n }\r\n \r\n public Set<EntityLiteral> getExtractions() {\r\n return extractions;\r\n }\r\n \r\n public int getMaxDocsInXML() {\r\n return maxDocsInXML;\r\n }\r\n \r\n public int getNumExtractions() {\r\n return getExtractions().size();\r\n }\r\n \r\n public int getNumWrappers() {\r\n return getWrappers().size();\r\n }\r\n \r\n public int getSumDocLength() {\r\n int sum = 0;\r\n for (Document document : this)\r\n sum += document.length();\r\n return sum;\r\n }\r\n \r\n public double getSumWrapperLength() {\r\n double sum = 0;\r\n for (Document document : this)\r\n for (Wrapper wrapper : document.getWrappers())\r\n sum += Math.log(wrapper.getContextLength()) * wrapper.getNumCommonTypes();\r\n return sum;\r\n }\r\n \r\n public Set<Wrapper> getWrappers() {\r\n return wrappers;\r\n }\r\n\r\n public Iterator<Document> iterator() {\r\n return docList.iterator();\r\n }\r\n \r\n public void setMaxDocsInXML(int numTopDocsInXML) {\r\n this.maxDocsInXML = numTopDocsInXML;\r\n }\r\n \r\n public int size() {\r\n return docList.size();\r\n }\r\n \r\n public void sort() {\r\n Collections.sort(docList);\r\n }\r\n \r\n public DocumentSet subList(int fromIndex, int toIndex) {\r\n DocumentSet docSet = new DocumentSet();\r\n docSet.docList = docList.subList(fromIndex, toIndex);\r\n for (Document document : docList)\r\n docSet.docMap.put(document, document);\r\n return docSet;\r\n }\r\n\r\n public String toXML() {\r\n return XMLUtil.document2String(toXMLElement(null));\r\n }\r\n\r\n public Element toXMLElement(org.w3c.dom.Document document) {\r\n XMLUtil xml = new XMLUtil(document);\r\n Element documentsNode = xml.createElement(\"documents\", null);\r\n xml.createAttrsFor(documentsNode, new Object[]{\r\n \"numDocuments\", docList.size(),\r\n \"scoredBy\", scoredByFeature,\r\n });\r\n\r\n for (int i = 0; i < Math.min(docList.size(), maxDocsInXML); i++) {\r\n Document doc = docList.get(i);\r\n if (doc.getWeight() == 0) continue;\r\n Element documentNode = xml.createElementBelow(documentsNode, \"document\", null);\r\n xml.createAttrsFor(documentNode, new Object[]{\r\n \"rank\", i+1,\r\n \"weight\", doc.getWeight(),\r\n });\r\n String title = doc.getSnippet().getTitle().toString();\r\n String urlStr = doc.getSnippet().getPageURL().toString();\r\n xml.createElementBelow(documentNode, \"title\", title);\r\n xml.createElementBelow(documentNode, \"url\", urlStr);\r\n }\r\n return documentsNode;\r\n }\r\n\r\n protected Feature getScoredByFeature() {\r\n return scoredByFeature;\r\n }\r\n}", "public class Document implements Comparable<Document>, Serializable {\r\n public static Logger log = Logger.getLogger(Document.class);\r\n private static final long serialVersionUID = -1407914809895275301L;\r\n \r\n private Set<Wrapper> wrappers;\r\n private Set<EntityLiteral> extractions;\r\n private Snippet snippet;\r\n private String text;\r\n private URL url;\r\n private double weight = 0;\r\n \r\n public Document(String text, URL url) {\r\n setText(text);\r\n setURL(url);\r\n wrappers = new HashSet<Wrapper>();\r\n extractions = new HashSet<EntityLiteral>();\r\n }\r\n \r\n public void addWrapper(Wrapper wrapper) {\r\n if (wrapper == null || wrapper.getContents().isEmpty()) return;\r\n wrapper.setURL(url);\r\n wrappers.add(wrapper);\r\n extractions.addAll(wrapper.getContents());\r\n }\r\n \r\n public void addWrappers(Set<Wrapper> wrappers) {\r\n for (Wrapper wrapper : wrappers)\r\n addWrapper(wrapper);\r\n }\r\n \r\n public void clearExtractions() {\r\n extractions.clear();\r\n }\r\n \r\n public void clearWrappers() {\r\n wrappers.clear();\r\n }\r\n \r\n public int compareTo(Document doc2) {\r\n return Double.compare(doc2.weight, weight);\r\n }\r\n \r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) return true;\r\n if (obj == null) return false;\r\n if (getClass() != obj.getClass()) return false;\r\n final Document other = (Document) obj;\r\n if (url == null) {\r\n if (other.url != null) return false;\r\n } else if (!url.toString().equals(other.url.toString()))\r\n return false;\r\n return true;\r\n }\r\n \r\n public Set<EntityLiteral> getExtractions() {\r\n return extractions;\r\n }\r\n\r\n public Snippet getSnippet() {\r\n return snippet;\r\n }\r\n\r\n public String getText() {\r\n return text;\r\n }\r\n\r\n public URL getURL() {\r\n return url;\r\n }\r\n\r\n public double getWeight() {\r\n return weight;\r\n }\r\n \r\n public Set<Wrapper> getWrappers() {\r\n return wrappers;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return 31 + (url == null ? 0 : url.toString().hashCode()); // added 01/27/2009\r\n }\r\n\r\n public boolean isEmpty() {\r\n return text == null || text.trim().length() == 0;\r\n }\r\n\r\n public int length() {\r\n return getText().length();\r\n }\r\n\r\n protected void merge(Document document) {\r\n if (document == null) return;\r\n if (!this.equals(document)) {\r\n log.warn(\"Documents cannot be merged since they are not equal!\");\r\n return;\r\n }\r\n addWrappers(document.getWrappers());\r\n setSnippet(document.getSnippet());\r\n setURL(document.getURL());\r\n }\r\n\r\n public void setSnippet(Snippet snippet) {\r\n if (this.snippet == null)\r\n this.snippet = snippet;\r\n else if (snippet != null)\r\n this.snippet.merge(snippet);\r\n }\r\n \r\n public void setText(String text) {\r\n this.text = text;\r\n }\r\n\r\n public void setURL(URL url) {\r\n if (url == null) return;\r\n \r\n if (this.url == null) {\r\n this.url = url;\r\n } else if (this.url.toString().length() > url.toString().length()) {\r\n // prefer shorter URL\r\n this.url = url;\r\n }\r\n \r\n /*if (this.url == null || \r\n url != null && url.toString().length() < this.url.toString().length())\r\n this.url = url;*/\r\n }\r\n\r\n public void setWeight(double weight) {\r\n this.weight = weight;\r\n }\r\n}", "public class WebManager {\r\n\r\n public static Logger log = Logger.getLogger(WebManager.class);\r\n public static GlobalVar gv = GlobalVar.getGlobalVar();\r\n \r\n public static final String URL_VAR = \"%URL%\";\r\n public static final String CACHE_HEADER = \"<!-- Downloaded from: \" + URL_VAR + \" -->\\n\";\r\n public static final String CACHE_FILE_EXT = \".html\";\r\n public static final int NUM_CACHE_BINS = 1024;\r\n \r\n // the unix timestamp when www.google.com was last accessed\r\n private static long lastHitGoogle = 0;\r\n // true to enable downloading web documents; false otherwise\r\n private static boolean isFetchFromWeb = true;\r\n // true to enable reading from the cache; false otherwise\r\n private static boolean isReadFromCache = true;\r\n // true to enable writing to the cache; false otherwise\r\n private static boolean isWriteToCache = true;\r\n \r\n private File cacheDir;\r\n private int numUrlFromCache = 0;\r\n private int numUrlFromWeb = 0;\r\n private int timeOutInMS;\r\n private int maxDocSizeInKB;\r\n \r\n public static boolean isFetchFromWeb() {\r\n return isFetchFromWeb;\r\n }\r\n \r\n public static boolean isReadFromCache() {\r\n return isReadFromCache;\r\n }\r\n \r\n public static boolean isWriteToCache() {\r\n return isWriteToCache;\r\n }\r\n \r\n /**\r\n * Read cache from the input URL\r\n * @param url\r\n * @return cached document\r\n */\r\n public static String readFromCache(URL url, File cacheDir) {\r\n if (url == null || !isReadFromCache())\r\n return null;\r\n String document = null;\r\n File cacheFile = loadCachedFile(url, cacheDir, false);\r\n if (cacheFile != null && cacheFile.isFile()) {\r\n document = Helper.readFile(cacheFile);\r\n // no permission to read the document?\r\n if (document == null) return null;\r\n // remove empty cache file\r\n if (document.length() == 0) {\r\n cacheFile.delete();\r\n return null;\r\n }\r\n // remove error Yahoo! page\r\n if (document.contains(\"service temporarily unavailable [C:28]\")) {\r\n cacheFile.delete();\r\n return null;\r\n }\r\n log.debug(\"Found Cache: \" + cacheFile);\r\n // get rid of \"page source\" on the top of every cached document\r\n document = removeCacheHeader(document);\r\n }\r\n return document;\r\n }\r\n \r\n public static void setFetchFromWeb(boolean isFetchFromWeb) {\r\n WebManager.isFetchFromWeb = isFetchFromWeb;\r\n log.info(\"isFetchFromWeb set to \" + WebManager.isFetchFromWeb);\r\n }\r\n \r\n public static void setReadFromCache(boolean isReadFromCache) {\r\n WebManager.isReadFromCache = isReadFromCache;\r\n }\r\n\r\n public static void setWriteToCache(boolean isWriteToCache) {\r\n WebManager.isWriteToCache = isWriteToCache;\r\n }\r\n \r\n public static void writeToCache(URL url, String document, File cacheDir) {\r\n if (document == null || url == null || !isWriteToCache())\r\n return;\r\n File cacheFile = loadCachedFile(url, cacheDir, true);\r\n if (cacheFile == null)\r\n return;\r\n long documentSize = Math.round(Helper.getStringSize(document) / 1024.0);\r\n log.debug(\"To Cache: \" + cacheFile + \" (\" + documentSize + \"KB)\");\r\n // add a \"page source\" on the top of every cached document\r\n document = CACHE_HEADER.replace(URL_VAR, url.toString()) + document;\r\n Helper.writeToFile(cacheFile, document);\r\n }\r\n \r\n /**\r\n * Finds the corresponding cached file for the input \"url\".\r\n * @param url\r\n * @param makeDir True to create cache dir if it does not exist\r\n * @return cached file\r\n */\r\n private static File loadCachedFile(URL url, File cacheDir, boolean makeDir) {\r\n if (url == null || cacheDir == null)\r\n return null;\r\n int urlHash = Math.abs(url.toString().hashCode());\r\n String cacheDirName = String.valueOf(urlHash % NUM_CACHE_BINS);\r\n File newCacheDir = new File(cacheDir, cacheDirName);\r\n if (makeDir)\r\n Helper.createDir(newCacheDir);\r\n String urlFileName = cacheDirName + \".\" + urlHash + CACHE_FILE_EXT;\r\n return new File(newCacheDir, urlFileName);\r\n }\r\n \r\n /**\r\n * Tries to read \"urls\" from cache. If an URL is not found in cache, it will be inserted into \"uncachedURLs\". \r\n * @param urls List of URLs to retrieve from cache\r\n * @param uncachedURLs List of URLs not found in cache\r\n * @return corresponding cached documents of the input \"urls\"\r\n */\r\n private static List<String> readFromCache(List<URL> urls, List<URL> uncachedURLs, File cacheDir) {\r\n if (urls == null || uncachedURLs == null)\r\n return null;\r\n List<String> documents = new ArrayList<String>(urls.size());\r\n if (urls.size() == 0)\r\n return documents;\r\n// log.debug(\"Reading \" + urls.size() + \" URLs from cache...\");\r\n for (URL url : urls) {\r\n String document = readFromCache(url, cacheDir);\r\n /*final String userDirName0 = \"/usr0/\", userDirName1 = \"/usr1/\";\r\n if (document == null && cacheDir.toString().contains(userDirName0)) {\r\n File alterFile = new File(cacheDir.toString().replace(userDirName0, userDirName1));\r\n document = readFromCache(url, alterFile);\r\n }*/\r\n documents.add(document);\r\n if (document == null)\r\n uncachedURLs.add(url);\r\n }\r\n return documents;\r\n }\r\n\r\n // wwc: made public\r\n public static String removeCacheHeader(String document) {\r\n final String prefix = CACHE_HEADER.substring(0, CACHE_HEADER.indexOf(URL_VAR));\r\n if (document.startsWith(prefix)) {\r\n int endIndex = document.indexOf(\"\\n\");\r\n if (endIndex != -1)\r\n return document.substring(endIndex+1);\r\n }\r\n return document;\r\n }\r\n\r\n private static void sleep(List<URL> uncachedURLs) {\r\n if (!GoogleWebSearcher.containsGoogleURL(uncachedURLs))\r\n return;\r\n long elapsedTime;\r\n while ((elapsedTime = System.currentTimeMillis() - lastHitGoogle) < gv.getGoogleHitGapInMS()) {\r\n long sleepTime = gv.getGoogleHitGapInMS() - elapsedTime;\r\n String sleepTimeStr = Helper.formatNumber(sleepTime/1000.0, 2);\r\n log.info(\"Just hit Google, sleeping for \" + sleepTimeStr + \" seconds to prevent being blocked...\");\r\n try { Thread.sleep(sleepTime); }\r\n catch (InterruptedException e) {}\r\n }\r\n lastHitGoogle = System.currentTimeMillis();\r\n }\r\n\r\n private static void writeToCache(List<URL> urls, List<String> documents, File cacheDir) {\r\n if (urls == null || documents == null || !isWriteToCache())\r\n return;\r\n int size = Math.min(urls.size(), documents.size());\r\n if (size == 0)\r\n return;\r\n log.debug(\"Writing \" + size + \" URLs to cache...\");\r\n for (int i = 0; i < size; i++)\r\n writeToCache(urls.get(i), documents.get(i), cacheDir);\r\n }\r\n\r\n public WebManager() {\r\n setCacheDir(gv.getCacheDir());\r\n setTimeOutInMS(gv.getTimeOutInMS());\r\n setMaxDocSizeInKB(gv.getMaxDocSizeInKB());\r\n setFetchFromWeb(gv.getIsFetchFromWeb());\r\n }\r\n\r\n /**\r\n * Attempts to retrieve documents from the cache. If not found in cache, \r\n * it will download the document from the Internet.\r\n * @param urls\r\n * @return retrieved documents\r\n */\r\n public List<String> get(List<URL> urls) {\r\n if (urls == null) return null;\r\n List<URL> uncachedURLs = new ArrayList<URL>();\r\n List<String> documents = readFromCache(urls, uncachedURLs, cacheDir);\r\n numUrlFromCache = urls.size()-uncachedURLs.size();\r\n numUrlFromWeb = uncachedURLs.size();\r\n log.info(\"Fetching \" + numUrlFromCache + \" webpages from cache and up to \" + numUrlFromWeb + \" webpages from the Internet\");\r\n \r\n List<String> uncachedDocs;\r\n if (!isFetchFromWeb()) {\r\n log.warn(\"Not downloading from the Web: Fetching has been disabled!\");\r\n uncachedDocs = Arrays.asList(new String[uncachedURLs.size()]);\r\n } else {\r\n log.info(\"Downloading URLs from Web\");\r\n sleep(uncachedURLs); // prevent blocking by Google\r\n uncachedDocs = MultiThreadFetcher.fetch(uncachedURLs, timeOutInMS, maxDocSizeInKB);\r\n }\r\n \r\n // converts search engine's cached pages back to their original format \r\n for (int i = 0; i < uncachedDocs.size(); i++) {\r\n URL url = uncachedURLs.get(i);\r\n String doc = uncachedDocs.get(i);\r\n if (GoogleWebSearcher.isBlockedByGoogle(doc, url))\r\n System.exit(1);\r\n doc = CacheRecoverer.recover(url, doc);\r\n uncachedDocs.set(i, doc);\r\n }\r\n\r\n writeToCache(uncachedURLs, uncachedDocs, cacheDir);\r\n int j = 0;\r\n for (int i = 0; i < documents.size(); i++)\r\n if (documents.get(i) == null)\r\n documents.set(i, uncachedDocs.get(j++));\r\n return documents;\r\n }\r\n\r\n /**\r\n * Attempts to retrieve a document from the cache. If not found in cache, \r\n * it will download the document from the Internet.\r\n * @param url\r\n * @return retrieved documents\r\n */\r\n public String get(URL url) {\r\n if (url == null) return null;\r\n List<URL> urls = new ArrayList<URL>();\r\n urls.add(url);\r\n return get(urls).get(0);\r\n }\r\n\r\n public File getCacheDir() {\r\n return cacheDir;\r\n }\r\n\r\n public int getMaxDocSizeInKB() {\r\n return maxDocSizeInKB;\r\n }\r\n\r\n public int getNumUrlFromCache() {\r\n return numUrlFromCache;\r\n }\r\n\r\n public int getNumUrlFromWeb() {\r\n return numUrlFromWeb;\r\n }\r\n\r\n public int getTimeOutInMS() {\r\n return timeOutInMS;\r\n }\r\n\r\n public void setCacheDir(File cacheDir) {\r\n this.cacheDir = cacheDir;\r\n }\r\n\r\n public void setMaxDocSizeInKB(int maxDocSizeInKB) {\r\n this.maxDocSizeInKB = maxDocSizeInKB;\r\n }\r\n\r\n public void setTimeOutInMS(int timeOutInMS) {\r\n this.timeOutInMS = timeOutInMS;\r\n }\r\n}\r", "public class StringEncoder\n{\n private char escapeChar;\n private String illegalChars;\n\n public StringEncoder(char escapeChar,String illegalChars)\n {\n this.escapeChar = escapeChar;\n this.illegalChars = illegalChars;\n }\n\n public String encode(String s)\n {\n StringBuffer buf = new StringBuffer(\"\");\n for (int i=0; i<s.length(); i++) {\n char ch = s.charAt(i);\n if (ch==escapeChar) {\n buf.append(escapeChar);\n buf.append(escapeChar);\n } else if (isIllegal(ch)) {\n buf.append(escapeChar);\n int code = (int)ch;\n int hex1 = code/16;\n int hex2 = code%16;\n buf.append(Character.forDigit(hex1,16));\n buf.append(Character.forDigit(hex2,16));\n } else {\n buf.append(ch);\n }\n }\n return buf.toString();\n }\n public String decode(String s)\n {\n StringBuffer buf = new StringBuffer(\"\");\n int k=0;\n while (k<s.length()) {\n if (s.charAt(k)!=escapeChar) {\n buf.append(s.charAt(k));\n k+=1;\n } else if (s.charAt(k+1)==escapeChar) {\n buf.append(escapeChar);\n k+=2;\n } else {\n int hex1 = Character.digit(s.charAt(k+1),16);\n int hex2 = Character.digit(s.charAt(k+2),16);\n //\t\t\t\tint code = hex1*16+hex2;\n buf.append((char)(hex1*16+hex2));\n k+=3;\n }\n }\n return buf.toString();\n }\n\n private boolean isIllegal(char c) \n {\n for (int i=0; i<illegalChars.length(); i++) {\n if (illegalChars.charAt(i)==c) return true;\n }\n return false;\n }\n\n static public void main(String[] args)\n {\n StringEncoder e = new StringEncoder('%',\".= \\t\\r\");\n for (int i=0; i<args.length; i++) {\n System.out.println(\"'\"+args[i]+\"'\\t'\"+e.encode(args[i])+\"'\\t'\"+e.decode(e.encode(args[i]))+\"'\");\n }\n }\n}" ]
import java.io.File; import java.net.URL; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.List; import java.util.ArrayList; import org.apache.log4j.Logger; import org.w3c.dom.Element; import com.rcwang.seal.util.XMLUtil; import com.rcwang.seal.util.Helper; import com.rcwang.seal.util.StringFactory; import com.rcwang.seal.expand.Wrapper.EntityLiteral; import com.rcwang.seal.fetch.DocumentSet; import com.rcwang.seal.fetch.Document; import com.rcwang.seal.fetch.WebManager; import com.rcwang.seal.util.StringEncoder;
/************************************************************************** * Developed by Language Technologies Institute, Carnegie Mellon University * Written by Richard Wang (rcwang#cs,cmu,edu) * * ... and William Cohen (wcohen@cs.cmu.edu) **************************************************************************/ package com.rcwang.seal.expand; public class WrapperSaver { public static Logger log = Logger.getLogger(WrapperSaver.class);
private static StringEncoder encoder = new StringEncoder('%',"\"\t\n\r");
7
ptitfred/magrit
server/core/src/main/java/org/kercoin/magrit/core/build/QueueServiceImpl.java
[ "@Singleton\npublic class Context {\n\t\n\tprivate final Configuration configuration = new Configuration();\n\t\n\tprivate Injector injector;\n\t\n\tprivate final GitUtils gitUtils;\n\t\n\tprivate final ExecutorService commandRunnerPool;\n\n\tpublic Context() {\n\t\tgitUtils = null;\n\t\tcommandRunnerPool = null;\n\t}\n\t\n\tpublic Context(GitUtils gitUtils) {\n\t\tthis(gitUtils, null);\n\t}\n\t\n\t@Inject\n\tpublic Context(GitUtils gitUtils,\n\t\t\t@Named(\"commandRunnerPool\") ExecutorService commandRunnerPool) {\n\t\tthis.gitUtils = gitUtils;\n\t\tthis.commandRunnerPool = commandRunnerPool;\n\t}\n\n\tpublic Configuration configuration() {\n\t\treturn configuration;\n\t}\n\t\n\tpublic Injector getInjector() {\n\t\treturn injector;\n\t}\n\t\n\tpublic ExecutorService getCommandRunnerPool() {\n\t\treturn commandRunnerPool;\n\t}\n\t\n\tpublic void setInjector(Injector injector) {\n\t\tthis.injector = injector;\n\t}\n\t\n\tpublic GitUtils getGitUtils() {\n\t\treturn gitUtils;\n\t}\n\n}", "public class Pair<T, U> {\n\tprivate T t;\n\tprivate U u;\n\n\tpublic Pair(T t, U u) {\n\t\tsuper();\n\t\tthis.t = t;\n\t\tthis.u = u;\n\t}\n\t\n\tpublic T getT() {\n\t\treturn t;\n\t}\n\n\tpublic U getU() {\n\t\treturn u;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((t == null) ? 0 : t.hashCode());\n\t\tresult = prime * result + ((u == null) ? 0 : u.hashCode());\n\t\treturn result;\n\t}\n\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\t@SuppressWarnings(\"unchecked\")\n\t\tPair<T, U> other = (Pair<T, U>) obj;\n\t\tif (t == null) {\n\t\t\tif (other.t != null)\n\t\t\t\treturn false;\n\t\t} else if (!t.equals(other.t))\n\t\t\treturn false;\n\t\tif (u == null) {\n\t\t\tif (other.u != null)\n\t\t\t\treturn false;\n\t\t} else if (!u.equals(other.u))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}", "public interface Filter {\n\n\t/**\n\t * Allows the user refine the list of tasks he is looking for.\n\t * @param s\n\t * @param submissionDate\n\t * @return\n\t * @see Pipeline#list(Filter...)\n\t */\n\tboolean matches(boolean isRunning, Date submissionDate);\n}", "public final class Filters {\n\tprivate Filters() {}\n\t\n\tprivate static final Filter ANY = new Filter() {\n\t\t@Override\n\t\tpublic boolean matches(boolean isRunning, Date submissionDate) {\n\t\t\treturn true;\n\t\t}\n\t};\n\tprivate static final Filter PENDING = new Filter() {\n\t\tpublic boolean matches(boolean r, Date d) {\n\t\t\treturn !r;\n\t\t}\n\t};\n\tprivate static final Filter RUNNING = new Filter() {\n\t\tpublic boolean matches(boolean r, Date d) {\n\t\t\treturn r;\n\t\t}\n\t};\n\n\tpublic static Filter any() {\n\t\treturn Filters.ANY;\n\t}\n\n\tpublic static Filter pending() {\n\t\treturn Filters.PENDING;\n\t}\n\n\tpublic static Filter running() {\n\t\treturn Filters.RUNNING;\n\t}\n\n\tpublic static Filter since(final Date from) {\n\t\treturn between(from, null);\n\t}\n\n\tpublic static Filter until(final Date to) {\n\t\treturn between(null, to);\n\t}\n\n\tpublic static Filter between(final Date from, final Date to) {\n\t\tif (from == null && to == null) {\n\t\t\tthrow new IllegalArgumentException(\"Both dates can't be null.\");\n\t\t}\n\t\tif (from != null && to != null && from.after(to)) {\n\t\t\tthrow new IllegalArgumentException(\"from must be before to\");\n\t\t}\n\t\treturn new Filter() {\n\t\t\t@Override\n\t\t\tpublic boolean matches(boolean isRunning, Date submissionDate) {\n\t\t\t\treturn (from == null || submissionDate.after(from))\n\t\t\t\t\t\t&& (to == null || submissionDate.before(to));\n\t\t\t}\n\t\t};\n\t}\n\n}", "public interface Key extends Comparable<Key> {\n\t/**\n\t * An uniq id, doesn't have any sense for client of the pipeline.\n\t * @return\n\t */\n\tint uniqId();\n\t/**\n\t * Tells if the key is valid or not. A non valid task avoids the use of <code>null</code> magic value.\n\t * @return\n\t */\n\tboolean isValid();\n}", "public interface Listener {\n\tvoid onSubmit(Key k);\n\tvoid onStart(Key k);\n\tvoid onDone(Key k);\n}", "@ImplementedBy(PipelineImpl.class)\npublic interface Pipeline {\n\n\t/**\n\t * Submits tasks to the pipeline. If the tasks is accepted, the returned key will be valid.\n\t * @param task\n\t * @return\n\t */\n\tKey submit(Task<BuildResult> task);\n\n\tTask<BuildResult> get(Key taskId);\n\n\tvoid addListener(Listener listener);\n\tvoid removeListener(Listener listener);\n\n\tvoid waitFor(Key... k) throws InterruptedException;\n\tvoid waitFor(long time, TimeUnit unit, Key... k) throws InterruptedException;\n\n\t/**\n\t * @param taskId\n\t */\n\tvoid cancel(Key taskId);\n\n\tList<Key> list(Filter... filters);\n\n\t/**\n\t * Returns a replicated outputstream to the stdout of the task identified by the {@link Key}.\n\t * @param task\n\t * @return\n\t */\n\tInputStream cat(Key task);\n\n\tFuture<BuildResult> getFuture(Key k);\n}", "public interface Task<E> extends Callable<E> {\n\tKey getKey();\n\tvoid setKey(Key k);\n\tDate getSubmitDate();\n\tvoid setSubmitDate(Date d);\n\tCriticalResource getUnderlyingResource();\n\tInputStream openStdout();\n}", "public class UserIdentity {\n\tprivate final String email;\n\tprivate final String name;\n\tprivate final String toString;\n\n\tpublic UserIdentity(String email, String name) {\n\t\tsuper();\n\t\tthis.email = email;\n\t\tthis.name = name;\n\t\tthis.toString = String.format(\"\\\"%s\\\" <%s>\", name, email);\n\t}\n\t\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn toString;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result\n\t\t\t\t+ ((toString == null) ? 0 : toString.hashCode());\n\t\treturn result;\n\t}\n\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\tUserIdentity other = (UserIdentity) obj;\n\t\tif (toString == null) {\n\t\t\tif (other.toString != null)\n\t\t\t\treturn false;\n\t\t} else if (!toString.equals(other.toString))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t\n\t\n}" ]
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryBuilder; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Pair; import org.kercoin.magrit.core.build.pipeline.Filter; import org.kercoin.magrit.core.build.pipeline.Filters; import org.kercoin.magrit.core.build.pipeline.Key; import org.kercoin.magrit.core.build.pipeline.Listener; import org.kercoin.magrit.core.build.pipeline.Pipeline; import org.kercoin.magrit.core.build.pipeline.Task; import org.kercoin.magrit.core.user.UserIdentity; import com.google.inject.Inject; import com.google.inject.Singleton;
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit 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. Magrit 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 Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit.core.build; @Singleton public class QueueServiceImpl implements QueueService {
private final Context context;
0
smartmarmot/DBforBIX
src/com/smartmarmot/dbforbix/DBforBix.java
[ "public class Constants {\r\n\tprivate static final String VERSION = \"Version 3.2.0-beta\";\r\n\tpublic static final String BANNER = Constants.PROJECT_NAME + \" \" + VERSION;\r\n\tprivate static final String PROJECT_NAME = \"DBforBix\";\r\n}", "public class Config {\r\n\r\n\tinterface Validable {\r\n\r\n\t\tpublic boolean isValid();\r\n\t}\r\n\t\r\n\t/**\r\n\t * \r\n\t */\r\n\tprivate static final Logger\t\tLOG\t\t\t\t\t= Logger.getLogger(Config.class);\r\n\tprivate static final String\t\tGLOBAL_NAME\t\t\t= \"DBforBIX\";\r\n\tprivate static final String\t\tGLOBAL_POOL\t\t\t= \"Pool\";\r\n\tprivate static final String\t\tGLOBAL_ZBXSRV\t\t= \"ZabbixServer\";\r\n\tprivate static final String\t\tGLOBAL_DB\t\t\t= \"DB\";\r\n\tprivate static final String\t\tSET_UPDATECONFIG \t= GLOBAL_NAME + \".UpdateConfigTimeout\";\r\n\tprivate static final String\t\tSET_POOL_MAXACTIVE\t= GLOBAL_POOL + \".MaxActive\";\r\n\tprivate static final String\t\tSET_POOL_MAXIDLE\t= GLOBAL_POOL + \".MaxIdle\";\r\n\tprivate static final String \tSET_LOGIN_TIMEOUT \t= GLOBAL_POOL+ \".LoginTimeOut\";\r\n\tprivate static final String \tZBX_HEADER_PREFIX\t= \"ZBXD\\1\";\r\n\tprivate static final String\t\tSET_PERSISTENCETYPE\t= GLOBAL_NAME + \".PersistenceType\";\r\n\tprivate static final String\t\tSET_PERSISTENCEDIR \t= GLOBAL_NAME + \".PersistenceDir\";\r\n\t\r\n\t\r\n\t\r\n\t/**\r\n\t * singleton\r\n\t */\r\n\tprivate static Config\t\t\t\t\t\tinstance;\r\n\t\r\n\t\r\n\t/**\r\n\t * Config\r\n\t */\r\n\tprivate String\t\t\t\t\tbasedir;\t\r\n\tprivate String \t\t\t\t\tconfigFile\t\t\t\t\t\t= null;\r\n\t\r\n\t\r\n\t/**\r\n\t * \r\n\t */\r\n\tprivate String \t\t\t\t\tconfigFileHash\t\t\t\t\t= null; \r\n//\tprivate Level\t\t\t\t\tlogLevel\t\t\t\t\t\t= Level.WARN;\r\n//\tprivate String\t\t\t\t\tlogFile\t\t\t\t\t\t\t= \"./logs/DBforBix.log\";\r\n//\tprivate String\t\t\t\t\tsspDir\t\t \t\t\t\t\t= \"./temp/\";\r\n//\tprivate String\t\t\t\t\tlogFileSize\t\t\t\t\t\t= \"1MB\";\r\n\tprivate int\t\t\t\t\t\tmaxActive\t\t\t\t\t\t= 10;\t\r\n\tprivate int\t\t\t\t\t\tloginTimeout\t\t\t\t\t= 60;\t// default queryTimeout\r\n\tprivate int\t\t\t\t\t\tmaxIdle\t\t\t\t\t\t\t= 15;\t// pieces\r\n\tprivate int\t\t\t\t\t\tupdateConfigTimeout\t\t\t\t= 120; \t// seconds\r\n\tprivate String\t\t\t\t\tpersistenceType\t\t\t\t\t= \"DB\";\r\n\tprivate String\t\t\t\t\tpersistenceDir\t\t \t\t\t= \"./persistence/\";\r\n\t\r\n\t\r\n\t/**\r\n\t * \r\n\t * zbxServers:\r\n\t * 1. Config.readConfigZSRV: - Zabbix Server: \r\n\t * zbxServerHost=Address, zbxServerPort=Port, ProxyName, DBList=dbNames - \r\n\t * 2. main: zbxSender - \r\n\t * 3. Config.getItemConfigFromZabbix: - Zabbix Server,\r\n\t * 4. Config.getItemConfigFromZabbix: itemsJSON, hosts, items, hostmacro, itemConfigs\r\n\t * 5. \r\n\t * \r\n\t * databases:\r\n\t * 1. readConfigDB: \r\n\t * 2. loadItemConfigFromZabbix: configurationUID\r\n\t * 2. main: add db to dbmanager\r\n\t * 3. \r\n\t * \r\n\t * schedulers:\r\n\t * 1. buildServerElements: configurationUID, time, new Scheduler(time), scheduler.addItem(configurationUID, item)\r\n\t * 2. main: schedulers -> worktimers\r\n\t * 3. \r\n\t */\r\n\t\r\n\t//configurationUID -> ZServer\r\n\t//configurationUID:ZServer = N:1\r\n\tprivate Set<ZabbixServer>\t_zabbixServers;\r\n\t\r\n\t//configurationUID -> Database\r\n\t//configurationUID:Database = N:1\r\n\tprivate Set<Database>\tdatabases;\r\n\t\r\n\t//configurationUID->time->Scheduler\r\n\t//configurationUID:Scheduler = 1:N\r\n\tprivate Map<String, Map<Integer, Scheduler>> schedulers = new HashMap<String,Map<Integer, Scheduler>>();\r\n\t\r\n\t//configurationUID->Timer\r\n\t//configurationUID:workTimer = 1:1\r\n\tprivate static Map<String,Timer> workTimers = new HashMap<String, Timer>();\r\n\r\n\tpublic Map<Integer, Scheduler> getSchedulersByConfigurationUID(String configurationUID) {\r\n\t\tif(!schedulers.containsKey(configurationUID)) schedulers.put(configurationUID,new HashMap<Integer,Scheduler>());\r\n\t\treturn schedulers.get(configurationUID);\r\n\t}\r\n\r\n\tpublic void addScheduler(String configurationUID, HashMap<Integer, Scheduler> scheduler) {\r\n\t\tthis.schedulers.put(configurationUID,scheduler);\r\n\t}\r\n\t\r\n\tpublic void clearSchedulers(){\r\n\t\tfor(Entry<String, Map<Integer, Scheduler>> s:schedulers.entrySet()){\r\n\t\t\tfor(Scheduler sch:s.getValue().values()){\r\n\t\t\t\tsch.cancel();\t\t\t\t\r\n\t\t\t}\t\t\t\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tThread.sleep(100);\r\n\t\t} catch (InterruptedException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\tschedulers.clear();\r\n\t}\r\n\r\n\tprivate Config() {\r\n\t\t_zabbixServers = new HashSet<ZabbixServer>();\r\n\t\tdatabases = new HashSet<Database>();\r\n\t}\r\n\t\r\n\t/**\r\n\t * reset Config instance\r\n\t * @return new Config instance\r\n\t */\r\n\tpublic Config reset() {\r\n\t\tif (workTimers != null)\r\n\t\t\tfor(Entry<String, Timer> element:workTimers.entrySet())\telement.getValue().cancel();\r\n\t\ttry {\r\n\t\t\tThread.sleep(100);\r\n\t\t} catch (InterruptedException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\tworkTimers.clear();\r\n\t\tclearSchedulers();\r\n\t\tConfig newconfig=new Config();\r\n\t\tnewconfig.setBasedir(getBasedir());\r\n\t\tnewconfig.setConfigFile(getConfigFile());\r\n\t\tinstance=newconfig;\r\n\t\treturn instance;\r\n\t}\r\n\t\r\n\r\n\t/**\r\n\t * Get the system configuration\r\n\t */\r\n\tpublic static Config getInstance() {\r\n\t\tif (instance == null)\r\n\t\t\tinstance = new Config();\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t/**\r\n\t * calculates hash for config file\r\n\t * @throws NullPointerException - if hash is null\r\n\t */\r\n\tprivate void calculateFileConfigHash() throws NullPointerException {\r\n\t\tMessageDigest md = null;\r\n\t\tbyte[] b=new byte[2048];\r\n\t\ttry{\r\n\t\t\tmd = MessageDigest.getInstance(\"MD5\");\r\n\t\t}\r\n\t\tcatch(NoSuchAlgorithmException e){\r\n\t\t\tLOG.error(\"Wrong algorithm provided while getting instance of MessageDigest: \" + e.getMessage());\r\n\t\t}\r\n\t\t/**\r\n\t\t * try with resources. Autoclosing after exitting try block\r\n\t\t */\r\n\t\ttry (InputStream is = Files.newInputStream(Paths.get(getConfigFile())); DigestInputStream dis = new DigestInputStream(is, md)){\r\n\t\t while(dis.read(b)>=0);\r\n\t\t} catch (IOException e) {\r\n\t\t\tLOG.error(\"Something has happenned reading file: \" + e.getLocalizedMessage());\r\n\t\t}\r\n\t\ttry{\r\n\t\t\tsetFileConfigHash((new HexBinaryAdapter()).marshal(md.digest()));\r\n\t\t} catch(Exception e){\r\n\t\t\tLOG.error(\"Something has happenned converting md5 sum to string: \" + e.getLocalizedMessage());\r\n\t\t}\r\n\t\tif(null==getFileConfigHash()) throw new NullPointerException(\"Hash for config file is null!\");\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Reads the configuration from a properties file\r\n\t * \r\n\t * @throws IOException\r\n\t */\r\n\tpublic void readFileConfig() throws IOException,NullPointerException {\r\n\t\tLOG.debug(\"Parsing config file: \" + configFile);\r\n\t\tcalculateFileConfigHash();\r\n\t\ttry (FileReader reader = new FileReader(configFile)){\r\n\t \t\tPropertiesConfiguration pcfg = new PropertiesConfiguration();\t \t\t\r\n\t\t \tpcfg.read(reader);\r\n\t\t\tif (pcfg.containsKey(SET_PERSISTENCETYPE))\r\n\t\t\t\tpersistenceType = pcfg.getString(SET_PERSISTENCETYPE);\t\t\t\r\n\t\t\tif (pcfg.containsKey(SET_PERSISTENCEDIR))\r\n\t\t\t\tpersistenceDir = pcfg.getString(SET_PERSISTENCEDIR);\r\n\t\t\tif (pcfg.containsKey(SET_UPDATECONFIG))\r\n\t\t\t\tsetUpdateConfigTimeout(pcfg.getInt(SET_UPDATECONFIG));\r\n\t\t\tif (pcfg.containsKey(SET_POOL_MAXACTIVE))\r\n\t\t\t\tmaxActive = pcfg.getInt(SET_POOL_MAXACTIVE);\r\n\t\t\tif (pcfg.containsKey(SET_POOL_MAXIDLE))\r\n\t\t\t\tmaxIdle = pcfg.getInt(SET_POOL_MAXIDLE);\r\n\t\t\tif (pcfg.containsKey(SET_LOGIN_TIMEOUT))\r\n\t\t\t\tloginTimeout = Integer.parseInt(pcfg.getString(SET_LOGIN_TIMEOUT));\t\t\t\t\r\n\t\t\tIterator<?> it;\r\n\t\t\tit = pcfg.getKeys(GLOBAL_ZBXSRV);\r\n\t\t\twhile (it.hasNext()) {\r\n\t\t\t\tString key = it.next().toString();\r\n\t\t\t\tString[] keyparts = key.split(\"\\\\.\");\r\n\t\t\t\tif (keyparts.length == 3)\r\n\t\t\t\t\treadConfigZSRV(keyparts[0], keyparts[1], keyparts[2], pcfg.getString(key));\r\n\t\t\t}\r\n\t\t\tit = pcfg.getKeys(GLOBAL_DB);\r\n\t\t\twhile (it.hasNext()) {\r\n\t\t\t\tString key = it.next().toString();\r\n\t\t\t\tString[] keyparts = key.split(\"\\\\.\");\r\n\t\t\t\tif (keyparts.length == 3)\r\n\t\t\t\t\treadConfigDB(keyparts[0], keyparts[1], keyparts[2], pcfg.getString(key));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (ConfigurationException e) {\r\n\t\t\tthrow new IOException(\"Error in configuration: \" + e.getLocalizedMessage(), e);\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\t/**\r\n\t * Read configuration value as zabbix server config\r\n\t */\r\n\tprivate void readConfigZSRV(String group, String name, String key, String value) {\r\n\t\tZabbixServer zabbixServer = getZServerByNameFC(name);\r\n\t\tif (zabbixServer == null) {\r\n\t\t\tzabbixServer = new ZabbixServer();\r\n\t\t\tzabbixServer.setZbxServerNameFC(name);\r\n\t\t\t_zabbixServers.add(zabbixServer);\r\n\t\t}\r\n\t\tif (\"Address\".equalsIgnoreCase(key)) zabbixServer.zbxServerHost = value;\r\n\t\telse if (\"Port\".equalsIgnoreCase(key)) {\r\n\t\t\ttry {\r\n\t\t\t\tzabbixServer.zbxServerPort = Integer.parseInt(value);\r\n\t\t\t}\r\n\t\t\tcatch (NumberFormatException ex) {\r\n\t\t\t\tLOG.error(\"Could not parse zbxServerPort number\", ex);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(\"ProxyName\".equalsIgnoreCase(key)) zabbixServer.proxy=value;\r\n\t\telse if(\"ConfigSuffix\".equalsIgnoreCase(key)) zabbixServer.zabbixConfigurationItemSuffix=value;\r\n\t\telse if(\"DBList\".equalsIgnoreCase(key)) zabbixServer.setDefinedDBNames((new ArrayList<String>(Arrays.asList(value.replaceAll(\"\\\\s\",\"\").toUpperCase().split(\",\")))));\t\t\r\n\t\telse\r\n\t\t\tLOG.info(\"Invalid config item: \" + group + \".\" + name + \".\" + key);\t\t\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Return ZServer instance by nameFC in file config (FC)\r\n\t * @param nameFC - nameFC of Zabbix Server in File Config\r\n\t * @return ZServer instance with given nameFC or null\r\n\t */\r\n\tprivate ZabbixServer getZServerByNameFC(String nameFC) {\r\n\t\tZabbixServer result=null;\r\n\t\tfor(ZabbixServer zs:_zabbixServers){\r\n\t\t\tif(zs.getZbxServerNameFC().equals(nameFC)){\r\n\t\t\t\tresult=zs;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\t//if(null==result) throw new NullPointerException(\"Failed to find among zbxServers Zabbix Server for given Zabbix Server nameFC: \"+nameFC);\t\t\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate void readConfigDB(String group, String name, String key, String value) {\r\n\t\tDatabase dbsrv = this.getDatabaseByNameFC(name);\r\n\t\tif (dbsrv == null){\r\n\t\t\tdbsrv = new Database();\r\n\t\t\tdbsrv.setDBNameFC(name);\r\n\t\t\tdatabases.add(dbsrv);\r\n\t\t}\r\n\t\t\r\n\t\tif (\"Type\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.type = DBType.fromString(value);\r\n\t\telse if (\"Url\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.url = value;\r\n\t\telse if (\"Instance\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.instance = value;\r\n\t\telse if (\"User\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.user = value;\r\n\t\telse if (\"Password\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.password = value;\r\n\t\telse if (\"MaxWaitMillis\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.setMaxWaitMillis(Integer.parseInt(value));\r\n\t\telse if (\"QueryTimeout\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.setQueryTimeout(Integer.parseInt(value));\t\t\r\n\t\telse if (\"MaxActive\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.setMaxActive(Integer.parseInt(value));\r\n\t\telse if (\"MaxIdle\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.setMaxIdle(Integer.parseInt(value));\r\n\t\telse if (\"Persistence\".equalsIgnoreCase(key))\r\n\t\t\tdbsrv.setPersistence(value);\r\n\t\telse\r\n\t\t\tLOG.info(\"Invalid config item: \" + group + \".\" + name + \".\" + key);\r\n\t}\r\n\r\n\t\r\n\tprivate Database getDatabaseByNameFC(String nameFC) {\r\n\t\tDatabase result=null;\r\n\t\tfor(Database db:databases){\r\n\t\t\tif(db.getDBNameFC().equals(nameFC)){\r\n\t\t\t\tresult=db;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\t\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * compares config file hashes: previous and actual\r\n\t * @return true or false\r\n\t */\r\n\tpublic boolean checkConfigChanges() {\r\n\t\tConfig newconfig = new Config();\r\n\t\tConfig oldconfig = this;\r\n\t\tnewconfig.setBasedir(oldconfig.getBasedir());\r\n\t\tnewconfig.setConfigFile(oldconfig.getConfigFile());\r\n\t\ttry{\r\n\t\t\tnewconfig.readFileConfig();\r\n\t\t}\r\n\t\tcatch (IOException e) {\r\n\t\t\tLOG.error(\"Error in config: \" + e.getLocalizedMessage());\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tcatch(NullPointerException e){\r\n\t\t\tLOG.error(\"Failed to calculate hash for config file: \"+e.getLocalizedMessage());\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\t boolean configFileChanged=(0==newconfig.getFileConfigHash().compareTo(oldconfig.getFileConfigHash()))?false:true;\r\n\t\t LOG.debug(\"Is config changed: \"+configFileChanged);\r\n\t\t if(configFileChanged) return true;\r\n\t\t \r\n\t\t /**\r\n\t\t * Update configuration from Zabbix Servers\r\n\t\t */\r\n\t\t newconfig.getZabbixConfigurationItems();\r\n\t\t \r\n\t\t \r\n\t\t Set<String> configurationUIDs=oldconfig.getSetOfConfigurationUIDs();\r\n\t\t Set<String> newConfigurationUIDs=newconfig.getSetOfConfigurationUIDs();\r\n\t\t \r\n\t\t /**\r\n\t\t * candidates for update:\r\n\t\t * i.e. zbxServerHost:zbxServerPort, proxy, host, db, item key \r\n\t\t * are the same\r\n\t\t */\r\n\t\t Set<String> toUpdate=new HashSet<>(configurationUIDs);\t\t \r\n\t\t toUpdate.retainAll(newConfigurationUIDs);\r\n\t\t Set<String> toRemoveFromUpdate=new HashSet<>();\r\n\t\t for (String configurationUID:toUpdate){\r\n\t\t\tZabbixServer zabbixServer=oldconfig.getZabbixServerByConfigurationUID(configurationUID);\r\n\t\t\tZabbixServer newZabbixServer=newconfig.getZabbixServerByConfigurationUID(configurationUID);\r\n\t\t\tIConfigurationItem configurationItem=zabbixServer.getConfigurationItemByConfigurationUID(configurationUID);\r\n\t\t\tIConfigurationItem newConfigurationItem=newZabbixServer.getConfigurationItemByConfigurationUID(configurationUID);\r\n\t\t\tString hashParam=configurationItem.getHashParam();\r\n\t\t\tString newHashParam=newConfigurationItem.getHashParam();\r\n\t\t\tif(hashParam.equals(newHashParam)) \r\n\t\t\t\ttoRemoveFromUpdate.add(configurationUID);\r\n\t\t }\r\n\t\t toUpdate.removeAll(toRemoveFromUpdate);\r\n\t\t \r\n\t\t Set<String> toDelete=new HashSet<String>(configurationUIDs);\r\n\t\t toDelete.removeAll(newConfigurationUIDs);\r\n\t\t \r\n\t\t Set<String> toAdd=new HashSet<String>(newConfigurationUIDs);\r\n\t\t toAdd.removeAll(configurationUIDs);\r\n\t\t \r\n\t\t\r\n\t\t if(!toUpdate.isEmpty()||!toAdd.isEmpty()||!toDelete.isEmpty()){\r\n\t\t\t /**\r\n\t\t\t * stop schedulers that are to be deleted and updated\r\n\t\t\t */\r\n\t\t\t stopSchedulers(toDelete);\r\n\t\t\t stopSchedulers(toUpdate);\r\n\t\t\t \r\n\t\t\t /**\r\n\t\t\t * Build new Items\r\n\t\t\t */\r\n\t\t\t newconfig.buildConfigurationElementsAndSchedulers();\r\n\t\t\t \r\n\t\t\t \r\n\t\t\t /**\r\n\t\t\t * delete items configs\r\n\t\t\t */\t\t\t \r\n\t\t\t deleteItemConfigs(toDelete);\r\n\t\t\t \r\n\t\t\t /**\r\n\t\t\t * add item configs\r\n\t\t\t */\r\n\t\t\t addConfigurationItems(newconfig,toAdd);\r\n\t\r\n\t\t\t /**\r\n\t\t\t * update item configs\r\n\t\t\t */\t\t\t \r\n\t\t\t updateItemConfigs(newconfig,toUpdate);\r\n\t\t\t \r\n\t\t\t \r\n\t\t\t /**\r\n\t\t\t * Open new connections to new DBs and Launch schedulers\r\n\t\t\t */\r\n\t\t\t startChecks();\r\n\t\t }\t\t \r\n\t\t return false;\r\n\t}\r\n\r\n\tprivate void stopSchedulers(Set<String> configurationUIDs) {\r\n\t\tfor(String ign:configurationUIDs){\r\n\t\t\t/**\r\n\t\t\t * clean workTimers\r\n\t\t\t */\r\n\t\t\tworkTimers.get(ign).cancel();\r\n\t\t\tworkTimers.remove(ign);\r\n\r\n\t\t\t/**\r\n\t\t\t * Clean schedulers\r\n\t\t\t */\r\n\t\t\tfor(Entry<Integer, Scheduler> s:getSchedulersByConfigurationUID(ign).entrySet()){\r\n\t\t\t\ts.getValue().cancel();\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tThread.sleep(100);\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\tschedulers.remove(ign);\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void startChecks() {\r\n\t\tDBManager manager = DBManager.getInstance();\r\n\t\tfor (Database db:getDatabases()){\r\n\t\t\t/**\r\n\t\t\t * Create adapter only if there are items for this DB\r\n\t\t\t */\r\n\t\t\tif( 0 < db.getConfigurationUIDs().size() ){\r\n\t\t\t\tDBAdapter adapter=manager.getDatabaseByName(db.getDBNameFC());\r\n\t\t\t\tif(null==adapter){\r\n\t\t\t\t\tmanager.addDatabase(db);\r\n\t\t\t\t\tadapter=manager.getDatabaseByName(db.getDBNameFC());\r\n//\t\t\t\t\ttry {\r\n//\t\t\t\t\t\tadapter.getConnection();\r\n//\t\t\t\t\t} catch (ClassNotFoundException | SQLException e) {\r\n//\t\t\t\t\t\te.printStackTrace();\r\n//\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tlaunchSchedulers(db.getConfigurationUIDs());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tprivate void launchSchedulers(Set<String> configurationUIDs) {\r\n\t\tfor (String configurationUID:configurationUIDs){\r\n\t\t\tif(!workTimers.containsKey(configurationUID)){\r\n\t\t\t\tTimer workTimer=new Timer(configurationUID);\r\n\t\t\t\tworkTimers.put(configurationUID,workTimer);\r\n\t\t\t\tint i = 0;\t\t\t\t\t\t\t\t\r\n\t\t\t\tfor (Entry<Integer, Scheduler> element: getSchedulersByConfigurationUID(configurationUID).entrySet()) {\r\n\t\t\t\t\tLOG.info(\"creating worker(\"+configurationUID+\") for timing: \" + element.getKey());\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tworkTimer.scheduleAtFixedRate(element.getValue(), 500 + i * 500, (long)(element.getKey() * 1000));\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t}\t\t\t\t\r\n//\t\t\t\ttry {\r\n//\t\t\t\t\t//Thread.sleep(5000);\r\n//\t\t\t\t} catch (InterruptedException e) {\r\n//\t\t\t\t\te.printStackTrace();\r\n//\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\tprivate void addConfigurationItems(Config newconfig, Set<String> newConfigurationUIDs) {\r\n\t\tfor (String newConfigurationUID:newConfigurationUIDs){\r\n\t\t\tif(this!=newconfig){\t\r\n\t\t\t\t/**\r\n\t\t\t\t * Add/update ZServers\r\n\t\t\t\t */\r\n\t\t\t\tZabbixServer newZabbixServer=newconfig.getZabbixServerByConfigurationUID(newConfigurationUID);\r\n\t\t\t\tZabbixServer zabbixServer=this.getZServerByNameFC(newZabbixServer.getZbxServerNameFC());\r\n\t\t\t\tif (null == zabbixServer){// just add\r\n\t\t\t\t\tLOG.error(\"Can't find ZServer by nameFC: \"+newZabbixServer.getZbxServerNameFC());\r\n\t\t\t\t\tzabbixServer=newZabbixServer;\r\n\t\t\t\t\t_zabbixServers.add(zabbixServer);\r\n\t\t\t\t}else{// update since pointer to existing ZServer may appear in code\r\n\t\t\t\t\tIConfigurationItem newConfigurationItem=newZabbixServer.getConfigurationItemByConfigurationUID(newConfigurationUID);\r\n\t\t\t\t\tzabbixServer.setHashZabbixConfig(newZabbixServer.getHashZabbixConfig());\r\n\t\t\t\t\tzabbixServer.setHosts(newZabbixServer.getHosts());\r\n\t\t\t\t\tzabbixServer.setItems(newZabbixServer.getItems());\r\n\t\t\t\t\tzabbixServer.setHostmacro(newZabbixServer.getHostmacro());\r\n\t\t\t\t\tzabbixServer.setHostsTemplates(newZabbixServer.getHostsTemplates());\r\n\t\t\t\t\tzabbixServer.addConfigurationItem(newConfigurationItem);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t/**\r\n\t\t\t\t * Add/update Databases\r\n\t\t\t\t */\r\n\t\t\t\tDatabase newDatabase=newconfig.getDatabaseByConfigurationUID(newConfigurationUID);\r\n\t\t\t\tDatabase database = this.getDatabaseByNameFC(newDatabase.getDBNameFC());\r\n\t\t\t\tif(null==database){//add\r\n\t\t\t\t\tLOG.debug(\"Add new DB to databases: \"+newDatabase.getDBNameFC());\r\n\t\t\t\t\tdatabase=newDatabase;\r\n\t\t\t\t\tdatabases.add(database);\r\n\t\t\t\t}else{//update\r\n\t\t\t\t\tdatabase.addConfigurationUID(newConfigurationUID);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t/**\r\n\t\t\t\t * Add schedulers\r\n\t\t\t\t */\r\n\t\t\t\tschedulers.put(newConfigurationUID, newconfig.getSchedulersByConfigurationUID(newConfigurationUID));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n\t/**\r\n\t * Delete item group names entities from configuration \r\n\t * @param configurationUIDs set of item group names to delete\r\n\t */\r\n\tprivate void deleteItemConfigs(Collection<String> configurationUIDs) {\r\n\t\t/**\r\n\t\t * zbxServers:\r\n\t\t * 4. Config.getConfigurationItemsFromZabbix: itemsJSON, hosts, configurationElements, hostmacro, configurationItems\r\n\t\t * 5. \r\n\t\t * \r\n\t\t * databases:\r\n\t\t * 1. loadConfigurationItemFromZabbix: configurationUID\r\n\t\t * 2. \r\n\t\t * \r\n\t\t * schedulers:\r\n\t\t * 1. buildServerElements: configurationItem -> Schedulers, configurationUID, time, new Scheduler(time), scheduler.addConfigurationElement(configurationUID, configurationElement)\r\n\t\t * 2. \r\n\t\t */\t\t\r\n\t\t\r\n\t\tfor(String configurationUID:configurationUIDs){\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Clean zbxServers\r\n\t\t\t */\r\n\t\t\tZabbixServer zs=\tthis.getZabbixServerByConfigurationUID(configurationUID);\r\n\t\t\tzs.removeConfigurationItem(configurationUID);\t\t\t\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Clean databases\r\n\t\t\t */\r\n\t\t\tDatabase db=this.getDatabaseByConfigurationUID(configurationUID);\r\n\t\t\tdb.removeConfigurationUID(configurationUID);\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Update DBManager\r\n\t\t */\r\n\t\tDBManager.getInstance().clean(configurationUIDs);\r\n\t\t\r\n\t\t/**\r\n\t\t * find databases without any configurationUID and remove them from collection\r\n\t\t */\r\n\t\tjava.util.function.Predicate<Database> dbPredicate=(Database db)-> db.getConfigurationUIDs().isEmpty();\r\n\t\tdatabases.removeIf(dbPredicate);\r\n\t\t\r\n\t\r\n\t}\r\n\r\n\tprivate Database getDatabaseByConfigurationUID(String configurationUID) {\r\n\t\tDatabase result=null;\r\n\t\tfor(Database db:databases){\r\n\t\t\tif(db.getConfigurationUIDs().contains(configurationUID)) {\r\n\t\t\t\tresult=db;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * Update changed configuration items\r\n\t * @param newconfig config instance to launch schedulers from\r\n\t * @param configurationUIDs set of group names which have to be updated\r\n\t */\r\n\tprivate void updateItemConfigs(Config newConfig, Set<String> configurationUIDs) {\r\n\t\tdeleteItemConfigs(configurationUIDs);\r\n\t\taddConfigurationItems(newConfig,configurationUIDs);\r\n\t}\r\n\r\n\t/**\r\n\t * \r\n\t * @param zabbixServers collection of Zabbix Servers\r\n\t * @return set of strings representing item group names\r\n\t */\r\n\tprivate Set<String> getSetOfConfigurationUIDs() {\r\n\t\tSet<String> result=new HashSet<String>();\r\n\t\tfor(ZabbixServer zs:getZabbixServers()) result.addAll(zs.getConfigurationUIDs());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\r\n\t\r\n\tprivate ZabbixServer getZabbixServerByConfigurationUID(String configurationUID){\r\n\t\tZabbixServer result=null;\t\t\r\n\t\tfor(ZabbixServer zs:getZabbixServers()){\r\n\t\t\tif(zs.getConfigurationUIDs().contains(configurationUID)){\r\n\t\t\t\tresult=zs;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\t\t\t\t\r\n\t\tif(null==result) throw new NullPointerException(\"Failed to find Zabbix Server for given configuration UID: \"+configurationUID);\t\t\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\r\n\t/**\r\n\t * Prepare byte array as a request to Zabbix Server\r\n\t * @param json string to be sent to Zabbix Server as proxy request\r\n\t * @return byte array representation of request ready to be sent\r\n\t */\r\n\tpublic byte[] getRequestToZabbixServer(String json){\r\n\t\tString str=new String(ZBX_HEADER_PREFIX + \"________\"+json);\r\n\t\t//byte[] data=str.getBytes();\r\n\t\tbyte[] data;\r\n\t\ttry {\r\n\t\t\t/**\r\n\t\t\t * For those who want to use russian and other unicode characters\r\n\t\t\t */\r\n\t\t\tdata = str.getBytes(\"UTF-8\");\r\n\t\t} catch (UnsupportedEncodingException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\tLOG.error(\"Problem with encoding json \"+e.getLocalizedMessage());\r\n\t\t\tdata = str.getBytes();\r\n\t\t}\r\n\t\t\r\n\t\t//get size of json request in little-endian format\r\n\t\tbyte[] leSize=null;\r\n\t\tleSize=getNumberInLEFormat8B(json.length());\r\n\t\tif(leSize.length != 8) {\r\n\t\t\tLOG.error(\"getZabbixProxyRequest():leSize has \"+leSize.length +\" != 8 bytes!\");\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\t\r\n\t\tfor(int i=0;i<8;++i) data[i+5]=leSize[i];\r\n\t\t//LOG.debug(\"getZabbixProxyRequest(): data: \"+ new String(data));\r\n\t\treturn data;\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * encode in low-endian format\r\n\t * @param l - number in current OS format\r\n\t * @return little-endian encoded number in byte array\r\n\t */\r\n\tprivate byte[] getNumberInLEFormat8B(long l) {\r\n\t\tbyte[] leL=new byte[8];\r\n\t\tfor(int i=0;i<8;++i){\r\n\t\t\tleL[i]=(byte) (l & 0xFF);\r\n\t\t\tl>>=8;\t\t\t\r\n\t\t}\r\n\t\treturn leL;\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * modify zabbix entity to java Map\r\n\t * @param zEntity - zabbix entity\r\n\t * @return - converted to Map entity\r\n\t */\r\n\tprivate Map<String, List<String>> zJSONObject2Map(JSONObject zEntity) {\r\n\t\tMap<String,List<String> > m=new HashMap<String,List<String> >();\r\n\t\tJSONArray data=zEntity.getJSONArray(\"data\");\r\n\t\tJSONArray fields=zEntity.getJSONArray(\"fields\");\r\n\t\tfor(int i=0;i<fields.size();++i){\r\n\t\t\tm.put(fields.getString(i),new ArrayList<String>());\r\n\t\t\tfor(int j=0;j<data.size();++j){\r\n\t\t\t\tm.get(fields.getString(i)).add(j, data.getJSONArray(j).getString(i));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn m;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Exception if response from Zabbix is empty.\r\n\t */\r\n\tpublic class ZBXBadResponseException extends Exception\r\n\t{\r\n\t\tprivate static final long serialVersionUID = 6490352403263167340L;\r\n\t\t//Parameterless Constructor\r\n\t public ZBXBadResponseException() {super(\"Zabbix Server returned empty response!\");}\r\n\t //Constructors that accept parameters\r\n\t public ZBXBadResponseException(String msg) { super(msg); } \r\n\t public ZBXBadResponseException(Throwable cause) { super(cause); } \r\n\t public ZBXBadResponseException(String msg, Throwable cause) { super(msg, cause); } \r\n\t}\r\n\t\r\n\t/**\r\n\t * Send request to Zabbix Server:\r\n\t * @param host - Zabbix Server\r\n\t * @param port - Zabbix Server Port\r\n\t * @param json - body of request in json format\r\n\t * @return - body of response in json format\r\n\t */\r\n\tpublic String requestZabbix(String host, int port, String json){\r\n\t\tbyte[] response = new byte[2048];\r\n\t\tSocket zabbix = null;\r\n\t\tOutputStreamWriter out = null;\r\n\t\tInputStream in = null;\t\t\t\r\n\t\tbyte[] data=null;\r\n\t\tString resp=new String();\r\n\t\t \r\n\t\t\r\n\t\ttry {\r\n\t\t\tzabbix = new Socket();\r\n\t\t\t//TODO socket timeout has to be read from config file\r\n\t\t\tzabbix.setSoTimeout(30000);\r\n\t\t\t\r\n\t\t\tzabbix.connect(new InetSocketAddress(host, port));\r\n\t\t\tOutputStream os = zabbix.getOutputStream();\r\n\t\t\t\r\n\t\t\tdata=getRequestToZabbixServer(json);\r\n\t\t\t\r\n\t\t\t//send request\r\n\t\t\tos.write(data);\r\n\t\t\tos.flush();\r\n\r\n\t\t\t//read response\r\n\t\t\tin = zabbix.getInputStream();\r\n\t\t\t\r\n\t\t\t//convert response to string (expecting json)\r\n\t\t\tint pos1=13;\r\n\t\t\tint bRead=0;\r\n\t\t\twhile(true){\r\n\t\t\t\tbRead = in.read(response);\r\n\t\t\t\t//LOG.debug(\"read=\"+read+\"\\nresponse=\"+new String(response));\r\n\t\t\t\tif(bRead<=0) break;\t\t\t\r\n\t\t\t\t//remove binary header\r\n\t\t\t\tresp+=new String(Arrays.copyOfRange(response, pos1, bRead));\r\n\t\t\t\tpos1=0;\r\n\t\t\t}\r\n\t\t\t//LOG.debug(\"requestZabbix(): resp: \"+ resp);\r\n\t\t\t//resp=resp.substring(13);//remove binary header\r\n\t\t\tif(resp.isEmpty())\r\n\t\t\t\tthrow new ZBXBadResponseException(\"Zabbix Server (\"+host+\":\"+port+\") has returned empty response for request:\\n\"+json);\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (ZBXBadResponseException respEx){\r\n\t\t\tLOG.error(respEx.getLocalizedMessage());\r\n\t\t}\r\n\t\tcatch (Exception ex) {\r\n\t\t\tLOG.error(\"Error getting data from Zabbix server (\"+host+\":\"+port+\"): \" + ex.getMessage());\r\n\t\t}\r\n\t\tfinally {\r\n\t\t\tif (in != null)\r\n\t\t\t\ttry {\r\n\t\t\t\t\tin.close();\r\n\t\t\t\t}\r\n\t\t\t\tcatch (IOException e) {}\r\n\t\t\tif (out != null)\r\n\t\t\t\ttry {\r\n\t\t\t\t\tout.close();\r\n\t\t\t\t}\r\n\t\t\t\tcatch (IOException e) {}\r\n\t\t\tif (zabbix != null)\r\n\t\t\t\ttry {\r\n\t\t\t\t\tzabbix.close();\r\n\t\t\t\t}\r\n\t\t\t\tcatch (IOException e) {}\r\n\t\t}\r\n\t\t\r\n\t\treturn resp;\r\n\t}\r\n\r\n\t\r\n\t\r\n\t/**\r\n\t * Read configuration items from all configured Zabbix Servers\r\n\t */\r\n\tpublic void getZabbixConfigurationItems(){\r\n\t\t//Get collection of all Zabbix Server instances that we should fill\r\n\t\tCollection<ZabbixServer> zabbixServers=null;\r\n\t\ttry{\r\n\t\t\tzabbixServers = getZabbixServers();\r\n\t\t}catch (Exception ex) {\r\n\t\t\tLOG.error(\"Error getting list of all valid Zabbix server configurations: \" + ex.getMessage());\r\n\t\t}\r\n\r\n\r\n\t\t//filling cycle\r\n\t\tfor (ZabbixServer zabbixServer: zabbixServers){\r\n\t\t\tString zabbixResponse=new String();\r\n\t\t\tzabbixResponse=requestZabbix(zabbixServer.zbxServerHost, zabbixServer.zbxServerPort,zabbixServer.getProxyConfigRequest());\r\n\t\t\tzabbixServer.setHashZabbixConfig(Config.calculateMD5Sum(zabbixResponse));\r\n\r\n\t\t\ttry{\r\n\t\t\t\t//get and parse json data into json object\r\n\t\t\t\tJSONObject zabbixResponseJSON=JSON.parseObject(zabbixResponse);\r\n\r\n\t\t\t\t//check response validity\r\n\t\t\t\tif(zabbixResponseJSON.containsKey(\"response\") && zabbixResponseJSON.getString(\"response\").contains(\"failed\"))\r\n\t\t\t\t\tthrow new ZBXBadResponseException(\"Zabbix Server (\"+zabbixServer+\") has returned failed response with reason: \"+zabbixResponseJSON.getString(\"info\")+\"\\nRequest: \"+zabbixServer.getProxyConfigRequest());\r\n\r\n\t\t\t\t/**result for hosts:\r\n\t\t\t\t * {ipmi_privilege=[2], tls_psk_identity=[], tls_accept=[1], hostid=[11082], tls_issuer=[],\r\n\t\t\t\t * ipmi_password=[], ipmi_authtype=[-1], ipmi_username=[], host=[APISQL], nameFC=[APISQL], tls_connect=[1],\r\n\t\t\t\t * tls_psk=[], tls_subject=[], status=[0]}\r\n\t\t\t\t * \r\n\t\t\t\t * result for items:\r\n\t\t\t\t * {trapper_hosts=[, ], snmpv3_authprotocol=[0, 0], snmpv3_securityname=[, ], flags=[1, 2], password=[, ], interfaceid=[null, null], snmpv3_authpassphrase=[, ], snmpv3_privprotocol=[0, 0],snmp_oid=[, ], delay_flex=[, ], publickey=[, ], ipmi_sensor=[, ], logtimefmt=[, ],\r\n\t\t\t\t * authtype=[0, 0], mtime=[0, 0], snmp_community=[, ], snmpv3_securitylevel=[0, 0], privatekey=[, ], lastlogsize=[0, 0], zbxServerPort=[, ], data_type=[0, 0], snmpv3_privpassphrase=[, ], snmpv3_contextname=[, ], username=[, ]}\r\n\t\t\t\t * status=[0, 0],\r\n\t\t\t\t * type=[11, 11], value_type=[4, 3],\r\n\t\t\t\t * hostid=[11082, 11082], itemid=[143587, 143588], \r\n\t\t\t\t * key_=[db.odbc.discovery[sessions,{$DSN}], db.odbc.select[sessions,{$DSN}]],\r\n\t\t\t\t * params=[select machine, count(1) N from v$session, sessions],\r\n\t\t\t\t * delay=[120, 120],\r\n\t\t\t\t * \r\n\t\t\t\t * hostmacro:\r\n\t\t\t\t * \"hostmacro\":{\"fields\":[\"hostmacroid\",\"hostid\",\"macro\",\"value\"],\"data\":[[450,11082,\"{$DSN}\",\"APISQL\"],[457,11084,\"{$PERF_SCHEMA}\",\"'performance_schema'\"]]},\r\n\t\t\t\t * \r\n\t\t\t\t * hosts_templates:\r\n\t\t\t\t * \"hosts_templates\":{\"fields\":[\"hosttemplateid\",\"hostid\",\"templateid\"],\"data\":[[2195,11082,11084]]},\r\n\t\t\t\t * \r\n\t\t\t\t * \r\n\t\t\t\t * */\r\n\r\n\t\t\t\t//fill ZServer structures with data\r\n\t\t\t\tzabbixServer.setHosts(zJSONObject2Map(zabbixResponseJSON.getJSONObject(\"hosts\")));\r\n\t\t\t\tzabbixServer.setItems(zJSONObject2Map(zabbixResponseJSON.getJSONObject(\"items\")));\r\n\t\t\t\tzabbixServer.setHostmacro(zJSONObject2Map(zabbixResponseJSON.getJSONObject(\"hostmacro\")));\r\n\t\t\t\tzabbixServer.setHostsTemplates(zJSONObject2Map(zabbixResponseJSON.getJSONObject(\"hosts_templates\")));\t\t\t\t\r\n\r\n\t\t\t}\r\n\t\t\tcatch (ZBXBadResponseException e){\r\n\t\t\t\tLOG.error(e.getLocalizedMessage());\r\n\t\t\t}\r\n\t\t\tcatch (Exception ex){\r\n\t\t\t\tLOG.error(\"Error parsing json objects from Zabbix Server (\"+zabbixServer+\"): \" + ex.getLocalizedMessage());\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t//get short references on internal data structures of current ZServer\r\n\t\t\t//hosts structure (example):\r\n\t\t\t//hostid=[11082], host=[APISQL], nameFC=[APISQL], status=[0]\r\n\t\t\t//\r\n\t\t\t//items structure (example):\r\n\t\t\t//status=[0, 0], \r\n\t\t\t//type=[11, 11], value_type=[4, 3],\r\n\t\t\t//hostid=[11082, 11082], itemid=[143587, 143588], \r\n\t\t\t//key_=[DBforBix.config[mysql.database.discovery], db.odbc.select[sessions,{$DSN}]], \r\n\t\t\t//params=[<XML config>, sessions], \r\n\t\t\t//delay=[120, 120]\r\n\t\t\t//\t\t\t\r\n\t\t\tMap<String,List<String> > hosts=zabbixServer.getHosts();\r\n\t\t\tMap<String,List<String> > items=zabbixServer.getItems();\t\t\t\r\n\t\t\t\r\n\r\n\t\t\ttry{\r\n\t\t\t\t\r\n\t\t\t\t/**\r\n\t\t\t\t * Filter out disabled hosts\r\n\t\t\t\t */\r\n\t\t\t\tSet<String> hostFilter=new HashSet<>();\r\n\t\t\t\tList<String> statuses=hosts.get(\"status\");\r\n\t\t\t\tfor(int i=0;i<statuses.size();++i){\r\n\t\t\t\t\tif(!\"0\".equals(statuses.get(i)))\r\n\t\t\t\t\t\thostFilter.add(hosts.get(\"hostid\").get(i));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t/**\r\n\t\t\t\t * fill configuration items collection for current zabbixServer:\r\n\t\t\t\t * iterate over all items looking for configuration item suffixes (DBforBIX.config by default, can be redefined in DBforBix configuration file on per Zabbix Server principle)\r\n\t\t\t\t */\r\n\t\t\t\tboolean foundConfigurationItemSuffix=false;\r\n\t\t\t\tfor(int it=0;it<items.get(\"key_\").size();++it){\r\n\t\t\t\t\tString key=items.get(\"key_\").get(it);\r\n\t\t\t\t\tif(key.contains(zabbixServer.getConfigurationItemSuffix())){\r\n\t\t\t\t\t\tfoundConfigurationItemSuffix=true;\r\n\t\t\t\t\t\tString hostid=items.get(\"hostid\").get(it);\r\n\t\t\t\t\t\tif(hostFilter.contains(hostid)) \r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\tString host=zabbixServer.getHostByHostId(hostid);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t/**\r\n\t\t\t\t\t\t * substitute macro for getting db name\r\n\t\t\t\t\t\t */\r\n\t\t\t\t\t\tString db=key.split(\",\")[1].split(\"]\")[0].trim().toUpperCase();\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(DBforBIXHelper.isMacro(db)){\r\n\t\t\t\t\t\t\tdb=zabbixServer.getMacroValue(hostid,db);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t/**\r\n\t\t\t\t\t\t * Construct configurationUID - stands for Unique IDentifier of Zabbix CONFIGURATION item - unique identifier for configuration item across all Zabbix Servers within DbforBIX instance\r\n\t\t\t\t\t\t * Why we need new name for this entity:\r\n\t\t\t\t\t\t * 1. It's the important key identifier across the whole DBforBIX instance. We should uniquely identify each configuration item from all Zabbix Servers within whole DBforBIX instance!\r\n\t\t\t\t\t\t * 2. Why not use configurationItemName or something like this? It is ambiguous because items in Zabbix have their own defined names.\t\t\t\t\t\t * \r\n\t\t\t\t\t\t * So let it be configurationUID.\r\n\t\t\t\t\t\t */\r\n\t\t\t\t\t\tString configurationUID=constructConfigurationUID(zabbixServer,host,db,key);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t/**\r\n\t\t\t\t\t\t * Register configuration item\r\n\t\t\t\t\t\t */\r\n\t\t\t\t\t\t/*\r\n\t\t\t\t\t\t//TODO refactor the container of configuration item data from Map to ZabbixItem! Using Map is dangerous because of misprints!\r\n\t\t\t\t\t\tMap<String,String> mConfigurationItem = new HashMap<String,String>();\r\n\t\t\t\t\t\tString param=items.get(\"params\").get(it);//Hint for items structure: Map->List[it]\r\n\t\t\t\t\t\tmConfigurationItem.put(\"param\", param);\t\t\t\t\t\t\r\n\t\t\t\t\t\t//Note! Hash together: configuration item XML as is and the result of macros substitution in XML\t\t\t\t\t\t \t\t\t\t\t\t\t\r\n\t\t\t\t\t\tmConfigurationItem.put(\"hashParam\", Config.calculateMD5Sum(param)+Config.calculateMD5Sum(substituteMacros(param,zabbixServer,hostid)));\r\n\t\t\t\t\t\tmConfigurationItem.put(\"hostid\", hostid);\r\n\t\t\t\t\t\tmConfigurationItem.put(\"host\", host);\r\n\t\t\t\t\t\tmConfigurationItem.put(\"db\", db);\r\n\t\t\t\t\t\tmConfigurationItem.put(\"key_\", key);\r\n\t\t\t\t\t\tmConfigurationItem.put(\"configurationUID\",configurationUID);\r\n\t\t\t\t\t\t*/\r\n\t\t\t\t\t\tString param=items.get(\"params\").get(it);//Hint for items structure: Map->List[it]\r\n\t\t\t\t\t\t//Note! Hash together: configuration item XML as is and the result of macros substitution in XML\r\n\t\t\t\t\t\tString hashParam = Config.calculateMD5Sum(param)+Config.calculateMD5Sum(DBforBIXHelper.substituteMacros(param,zabbixServer,hostid));\r\n\t\t\t\t\t\t//prefix is not necessary part of configuration item, and will be added some later\r\n\t\t\t\t\t\tIConfigurationItem configurationItem = new ConfigurationItem(\r\n\t\t\t\t\t\t\t\tconfigurationUID,\r\n\t\t\t\t\t\t\t\tzabbixServer,\r\n\t\t\t\t\t\t\t\thost, hostid, db, key,\r\n\t\t\t\t\t\t\t\tparam, hashParam\r\n\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\tzabbixServer.addConfigurationItem(configurationItem);\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\t/**\r\n\t\t\t\t\t\t * Fill Dbs config with configurationUID Set<String> itemGrouName.\r\n\t\t\t\t\t\t * FC stnds for File Config (DBforBIX configuration file).\r\n\t\t\t\t\t\t * Propagate absence of DB in file config to Zabbix Web interface\r\n\t\t\t\t\t\t */\r\n\t\t\t\t\t\tDatabase dbFC=this.getDatabaseByNameFC(db);\r\n\t\t\t\t\t\tif(null==dbFC){\r\n\t\t\t\t\t\t\tdbFC=new Database();\r\n\t\t\t\t\t\t\tdbFC.setDBNameFC(db);\r\n\t\t\t\t\t\t\tdbFC.url=\"---propagate error---\";\r\n\t\t\t\t\t\t\tdbFC.user=\"---propagate error---\";\r\n\t\t\t\t\t\t\tdbFC.password=\"---propagate error---\";\r\n\t\t\t\t\t\t\tdbFC.type=DBType.DB_NOT_DEFINED;\r\n\t\t\t\t\t\t\tdatabases.add(dbFC);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tdbFC.addConfigurationUID(configurationUID);\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(!foundConfigurationItemSuffix) LOG.warn(\"No items with configuration suffix (DBforBIX.config by default) were found on Zabbix Server \"+zabbixServer+\"! \"\r\n\t\t\t\t\t\t+ \"Please check DBforBIX configuration file for string ZabbixServer.<YourZabbixInstanceName>.ConfigSuffix=<YourConfigSuffix> and define it correctly. \"\r\n\t\t\t\t\t\t+ \"Then check configuration items in your Zabbix Server web interface: they should contain <YourConfigSuffix> in their item keys, e.g.item key: discovery.<YourConfigSuffix>[tralala,<DBDataSourceName>].\"\r\n\t\t\t\t\t\t+ \"Also check that host-owner of configuration item is monitored through Zabbix Proxy name corresponding your DBforBIX parameter \"\r\n\t\t\t\t\t\t+ \"ZabbixServer.<YourZabbixInstanceName>.ProxyName=... in DBforBIX configuration file.\");\r\n\t\t\t\tLOG.debug(\"Done reading configuration items from Zabbix Server \"+zabbixServer);\r\n\t\t\t}\r\n\t\t\tcatch (Exception ex){\r\n\t\t\t\tLOG.error(\"Error getting item Zabbix Config from Zabbix Server (\"+zabbixServer+\"): \" + ex.getLocalizedMessage());\r\n\t\t\t}\r\n\t\t}\t\t\r\n\t}\r\n\r\n\r\n\tpublic static String calculateMD5Sum(String inStr) {\r\n\t\tMessageDigest hasher = null;\r\n\t\ttry{\r\n\t\t\thasher = java.security.MessageDigest.getInstance(\"MD5\");\r\n\t\t}\r\n\t\tcatch(NoSuchAlgorithmException e){\r\n\t\t\tLOG.error(\"Wrong hashing algorithm name provided while getting instance of MessageDigest: \" + e.getLocalizedMessage());\r\n\t\t}\r\n\t\treturn (new HexBinaryAdapter()).marshal(hasher.digest(inStr.getBytes()));\r\n\t}\r\n\r\n\r\n\r\n\t/**\r\n\t * Constructs configurationUID - unique identifier for configuration item across all Zabbix Servers within DbforBIX instance\r\n\t * @param zabbixServer - ZServer instance\r\n\t * @param host - host within Zabbix Server\r\n\t * @param db - database name (Data Source Name)\r\n\t * @param key - configuration item key (should contain suffix like DBforBIX.config or other that you've defined in DBforBIX configuration file for this Zabbix Server)\r\n\t * @return string - configurationUID - cross Zabbix Server unique identifier of Zabbix configuration item\r\n\t */\r\n\tprivate String constructConfigurationUID(ZabbixServer zabbixServer, String host, String db, String key) {\r\n\t\treturn new String(zabbixServer.toString()+\"/\"+zabbixServer.getProxy()+\"/\"+host+\"/\"+db+\"/\"+key);\r\n\t}\r\n\r\n\r\n\tpublic void buildConfigurationElementsAndSchedulers() {\t\t\t\r\n\t\t//result for hosts:\r\n\t\t// hostid=[11082], host=[APISQL], nameFC=[APISQL], status=[0]\r\n\t\t//result for items:\r\n\t\t//status=[0, 0], \r\n\t\t//type=[11, 11], value_type=[4, 3],\r\n\t\t//hostid=[11082, 11082], itemid=[143587, 143588], \r\n\t\t//key_=[db.odbc.discovery[sessions,{$DSN}], db.odbc.select[sessions,{$DSN}]], \r\n\t\t//params=[select machine, count(1) N from v$session, sessions], \r\n\t\t//delay=[120, 120],\r\n\r\n\t\tCollection<ZabbixServer> zabbixServers=null;\r\n\t\ttry{\r\n\t\t\tzabbixServers = getZabbixServers();\r\n\t\t}catch (Exception ex) {\r\n\t\t\tLOG.error(\"Error getting Zabbix servers collection: \" + ex.getLocalizedMessage());\r\n\t\t}\r\n\t\t\r\n\t\tfor (ZabbixServer zabbixServer: zabbixServers){\r\n\t\t\tfor(Entry<String, IConfigurationItem> configurationItemEntry:zabbixServer.getConfigurationItems().entrySet()){\r\n\t\t\t\tString configurationUID=configurationItemEntry.getKey();\r\n\t\t\t\tIConfigurationItem configurationItem=configurationItemEntry.getValue();\r\n\t\t\t\tLOG.debug(\"Building configuration elements for \"+configurationUID);\r\n\t\t\t\ttry {\r\n\t\t\t\t\tString config=configurationItem.getParam();\r\n\t\t\t\t\tconfig=DBforBIXHelper.substituteMacros(config,zabbixServer,configurationItem.getHostid());\r\n\t\t\t\t\tIConfigurationItemParser configurationItemParser = ConfigurationItemParserFactory.getConfigurationItemParser(config);\r\n\t\t\t\t\tSet<IConfigurationElement> configurationElements = configurationItemParser.buildConfigurationElements();\t\t\t\t\t\r\n\t\t\t\t\tconfigurationItem.addConfigurationElements(configurationElements);\r\n\t\t\t\t\tbuildSchedulers(configurationElements);\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Exception ex) {\r\n\t\t\t\t\tLOG.error(\"Error while loading config item \"+configurationItemEntry, ex);\r\n\t\t\t\t\tLOG.error(\"Skipping \"+configurationItemEntry);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t\r\n\tprivate void buildSchedulers(Set<IConfigurationElement> _configurationElements) {\r\n\t\tfor(IConfigurationElement configurationElement:_configurationElements){\t\t\r\n\t\t\tString configurationUID=configurationElement.getConfigurationUID();\r\n\t\t\tMap<Integer,Scheduler> schedulers=getSchedulersByConfigurationUID(configurationUID);\r\n\t\t\tint time=configurationElement.getTime();\r\n\t\t\tif (!schedulers.containsKey(time)) {\r\n\t\t\t\tLOG.debug(\"creating item scheduler with time \" + time);\r\n\t\t\t\tschedulers.put(time, new Scheduler(time));\r\n\t\t\t}\r\n\t\t\tScheduler scheduler = schedulers.get(time);\r\n\t\t\tscheduler.addConfigurationElement(configurationElement);\t\t\t\r\n\t\t}\t\t\r\n\t}\r\n\t\r\n\t\r\n\r\n\tpublic void setBasedir(String basedir) {\r\n\t\tthis.basedir = basedir;\r\n\t}\r\n\r\n\tpublic String getBasedir() {\r\n\t\treturn basedir;\r\n\t}\r\n\r\n\tpublic String getSPDir() {\r\n\t\treturn persistenceDir;\r\n\t}\r\n\r\n\tpublic String getSPType() {\r\n\t\treturn persistenceType;\r\n\t}\r\n\r\n\tpublic int getMaxActive() {\r\n\t\treturn maxActive;\r\n\t}\r\n\r\n\tpublic int getMaxIdle() {\r\n\t\treturn maxIdle;\r\n\t}\r\n\r\n\t/**\r\n\t * @return a list of all VALID zabbix server configurations\r\n\t */\r\n\tpublic Collection<ZabbixServer> getZabbixServers() {\r\n\t\tCollection<ZabbixServer> validServers = _zabbixServers;\r\n\t\tCollectionUtils.filter(validServers, new Predicate <ZabbixServer>() {\t\t\t\r\n\t\t\t@Override\r\n\t\t\tpublic boolean evaluate(ZabbixServer object) {\r\n\t\t\t\treturn ((ZabbixServer) object).isValid();\r\n\t\t\t}\r\n\t\t});\r\n\t\treturn validServers;\r\n\t}\r\n\r\n\t/**\r\n\t * @return a list of all VALID database configurations\r\n\t */\r\n\tpublic Collection<Database> getDatabases() {\r\n\t\tCollection<Database> validDatabases = databases;\r\n\t\tCollectionUtils.filter(validDatabases, new Predicate<Database>() {\r\n\t\t\t\r\n\t\t\t@Override\r\n\t\t\tpublic boolean evaluate(Database object) {\r\n\t\t\t\treturn ((Database) object).isValid();\r\n\t\t\t}\r\n\t\t});\r\n\t\treturn validDatabases;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tStringBuilder builder = new StringBuilder();\r\n\t\tbuilder.append(\"Config:\\n\");\r\n\t\tbuilder.append(\"\\n\");\r\n\t\tbuilder.append(\"BaseDir:\\t\").append(getBasedir()).append(\"\\n\");\r\n\t\tfor (ZabbixServer zsrv: _zabbixServers)\r\n\t\t\tbuilder.append(\"-- Zabbix:\\t\").append(zsrv).append(\"\\n\");\r\n\t\tfor (Database db: databases)\r\n\t\t\tbuilder.append(\"-- Database:\\t\").append(db).append(\"\\n\");\r\n\t\treturn builder.toString();\r\n\t}\r\n\r\n\tpublic int getLoginTimeout() {\r\n\t\treturn this.loginTimeout;\r\n\t}\r\n\r\n\tpublic String getConfigFile() {\r\n\t\treturn configFile;\r\n\t}\r\n\r\n\tpublic void setConfigFile(String configFile) {\r\n\t\tthis.configFile = configFile;\r\n\t}\r\n\r\n\tpublic String getFileConfigHash() {\r\n\t\treturn configFileHash;\r\n\t}\r\n\r\n\tprivate void setFileConfigHash(String fileConfigHash) {\r\n\t\tthis.configFileHash = fileConfigHash;\r\n\t}\r\n\r\n\tpublic static Map<String,Timer> getWorkTimers() {\r\n\t\treturn workTimers;\r\n\t}\r\n\r\n\tpublic static void setWorkTimers(Map<String,Timer> workTimers) {\r\n\t\tConfig.workTimers = workTimers;\r\n\t}\r\n\r\n\tpublic int getUpdateConfigTimeout() {\r\n\t\treturn updateConfigTimeout;\r\n\t}\r\n\r\n\tpublic void setUpdateConfigTimeout(int updateConfigTimeout) {\r\n\t\tthis.updateConfigTimeout = updateConfigTimeout;\r\n\t}\r\n\t\r\n}\r", "public class ZabbixServer implements Validable {\r\n\t\r\n\tString\t\tzbxServerHost\t\t= null;\r\n\tint\t\t\tzbxServerPort\t\t= 10051;\r\n\tprivate String \t\tzbxServerNameFC\t\t= null;\r\n\tString\t\tproxy\t\t= null;\r\n\tprivate PROTOCOL\tprotocol\t= PROTOCOL.V32;\t\t\r\n\tprivate Collection<String> definedDBNames = null;\r\n\t\r\n\t\r\n\t/**\r\n\t * reinit \r\n\t */\r\n\tprivate Map<String,List<String> > hosts=null;\r\n\tprivate Map<String,List<String> > items=null;\r\n\tprivate Map<String,List<String> > hostmacro=null;\r\n\tprivate Map<String,List<String>> hostsTemplates=null;\r\n\tprivate Map<String,IConfigurationItem> configurationItems = new HashMap<>();\r\n\tprivate String hashZabbixConfig\t\t=null;\r\n\tString zabbixConfigurationItemSuffix = \"DBforBIX.config\";\r\n\t\r\n\t\r\n\t\r\n\t/////////////////////////////////////////////////////////\r\n\tpublic String getZbxServerNameFC() {\r\n\t\treturn zbxServerNameFC;\r\n\t}\r\n\r\n\tpublic void setZbxServerNameFC(String zbxServerNameFC) {\r\n\t\tthis.zbxServerNameFC = zbxServerNameFC;\r\n\t}\r\n\t\r\n\t\r\n\tpublic Map<String, IConfigurationItem> getConfigurationItems() {\r\n\t\treturn configurationItems;\r\n\t}\r\n\t\r\n\tpublic String getHashZabbixConfig() {\r\n\t\treturn hashZabbixConfig;\r\n\t}\r\n\t\r\n\tpublic Map<String,List<String> > getHosts() {\r\n\t\treturn hosts;\r\n\t}\r\n\t\r\n\tpublic Map<String,List<String> > getItems() {\r\n\t\treturn items;\r\n\t}\r\n\t\r\n\tpublic Map<String,List<String> > getHostmacro() {\r\n\t\treturn hostmacro;\r\n\t}\t\t\r\n\t////////////////////////\r\n\tpublic void setHashZabbixConfig(String inStr) {\r\n\t\tthis.hashZabbixConfig=inStr;\r\n\t}\r\n\t\r\n\r\n\tpublic void setConfigurationItems(Map<String,IConfigurationItem> configurationItems) {\r\n\t\tthis.configurationItems=configurationItems;\r\n\t}\r\n\t\r\n\tpublic void setHosts(Map<String,List<String> > hosts) {\r\n\t\tthis.hosts = hosts;\r\n\t}\t\t\r\n\r\n\tpublic void setItems(Map<String,List<String> > items) {\r\n\t\tthis.items = items;\r\n\t}\t\t\r\n\r\n\tpublic void setHostmacro(Map<String,List<String> > hostmacro) {\r\n\t\tthis.hostmacro = hostmacro;\r\n\t}\t\t\r\n\t//////////////////////////////////////////////////////////////////\r\n\t\r\n\r\n\tpublic Collection<String> getDefinedDBNames() {\r\n\t\treturn definedDBNames;\r\n\t}\r\n\t\r\n\tpublic void setDefinedDBNames(Collection<String> definedDBNames) {\r\n\t\tthis.definedDBNames = definedDBNames;\r\n\t}\r\n\t\r\n\tpublic String getZServerHost() {\r\n\t\treturn zbxServerHost;\r\n\t}\r\n\t\r\n\tpublic int getZServerPort() {\r\n\t\treturn zbxServerPort;\r\n\t}\r\n\t\r\n\tpublic PROTOCOL getProtocol() {\r\n\t\treturn protocol;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean isValid() {\r\n\t\treturn (zbxServerPort > 0) && (zbxServerHost != null);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn zbxServerHost + \":\" + zbxServerPort;\r\n\t}\r\n\r\n\t\r\n\tpublic String getProxyConfigRequest(){\r\n\t\treturn new String(\"{\\\"request\\\":\\\"proxy config\\\",\\\"host\\\":\\\"\"+getProxy()+\"\\\"}\");\r\n\t}\r\n\r\n\tpublic String getProxy() {\r\n\t\treturn proxy;\r\n\t}\r\n\r\n\tpublic void setProxy(String proxy) {\r\n\t\tthis.proxy = proxy;\r\n\t}\r\n\r\n\tpublic void addConfigurationItem(IConfigurationItem configurationItem) {\r\n\t\tconfigurationItems.put(configurationItem.getConfigurationUID(), configurationItem);\r\n\t}\r\n\t\r\n\tpublic void removeConfigurationItem(String configurationUID) {\r\n\t\tconfigurationItems.remove(configurationUID);\r\n\t}\r\n\r\n\t/**\r\n\t * \r\n\t * @return set of item group names of this Zabbix Server\r\n\t */\r\n\tpublic Collection<String> getConfigurationUIDs() {\t\t\t\r\n\t\treturn configurationItems.keySet();\r\n\t}\r\n\r\n\t/**\r\n\t * \r\n\t * @param configurationUID\r\n\t * @return configuration item\r\n\t * @throws NullPointerException\r\n\t */\r\n\tpublic IConfigurationItem getConfigurationItemByConfigurationUID(String configurationUID){\r\n\t\treturn configurationItems.get(configurationUID);\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\tpublic String getHostByHostId(String hostid) {\r\n\t\tString host=null;\r\n\t\tfor(int hid=0;hid<hosts.get(\"hostid\").size();++hid){\r\n\t\t\tif(hostid.equals(hosts.get(\"hostid\").get(hid))){\r\n\t\t\t\thost=hosts.get(\"host\").get(hid);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn host;\r\n\t}\r\n\r\n\tprivate String getHostMacroValue(String hostid, String macro) {\r\n\t\tfor(int hm=0;hm<hostmacro.get(\"hostid\").size();++hm){\r\n\t\t\tif(hostmacro.get(\"hostid\").get(hm).equals(hostid) \r\n\t\t\t\t&& hostmacro.get(\"macro\").get(hm).equals(macro)){\r\n\t\t\t\treturn hostmacro.get(\"value\").get(hm);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprivate String getTemplateMacroValue(String hostid, String macro) {\r\n\t\t// TODO Check macro resolving method in Zabbix\r\n\t\tString result=null;\r\n\t\t/**\r\n\t\t * hostmacro:\r\n\t\t * \"hostmacro\":{\"fields\":[\"hostmacroid\",\"hostid\",\"macro\",\"value\"],\"data\":[[450,11082,\"{$DSN}\",\"APISQL\"],[457,11084,\"{$PERF_SCHEMA}\",\"'performance_schema'\"]]},\r\n\t\t * \r\n\t\t * hosts_templates:\r\n\t\t * \"hosts_templates\":{\"fields\":[\"hosttemplateid\",\"hostid\",\"templateid\"],\"data\":[[2195,11082,11084]]},\r\n\t\t * */\r\n\t\tSet<String> templateIds=new HashSet<>();\t\t\t\r\n\t\tfor(int hm=0;hm<hostsTemplates.get(\"hostid\").size();++hm){\r\n\t\t\tif(hostsTemplates.get(\"hostid\").get(hm).equals(hostid)){\t\t\t\t\t\r\n\t\t\t\ttemplateIds.add(hostsTemplates.get(\"templateid\").get(hm));\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (String tid:templateIds){\r\n\t\t\t result=getHostMacroValue(tid,macro);\r\n\t\t\t if(null!=result) break;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\r\n\t\r\n\r\n\tpublic void setHostsTemplates(Map<String, List<String>> hostsTemplates) {\r\n\t\tthis.hostsTemplates=hostsTemplates;\t\t\t\r\n\t}\r\n\r\n\tpublic Map<String, List<String>> getHostsTemplates() {\t\t\t\r\n\t\treturn hostsTemplates;\r\n\t}\r\n\r\n\tpublic String getMacroValue(String hostid, String macro) {\r\n\t\tString result=null;\r\n\t\tresult=getHostMacroValue(hostid,macro);\r\n\t\tif(null==result){\r\n\t\t\tresult=this.getTemplateMacroValue(hostid, macro);\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic String getConfigurationItemSuffix() {\r\n\t\treturn zabbixConfigurationItemSuffix;\r\n\t}\t\r\n}", "public class DBManager {\r\n\r\n\tprivate static DBManager\tinstance;\r\n\r\n\tprotected DBManager() {}\r\n\r\n\tprivate Set<DBAdapter>\tdatabases\t= new HashSet<>();\r\n\r\n\tpublic static DBManager getInstance() {\r\n\t\tif (instance == null)\r\n\t\t\tinstance = new DBManager();\r\n\t\treturn instance;\r\n\t}\r\n\t\r\n//DB2, ORACLE, MSSQL, MYSQL, PGSQL, ALLBASE, SYBASE, SQLANY;\r\n\tpublic void addDatabase(Database cfg) {\r\n\t\tif(databases.contains(cfg.getDBNameFC()))\r\n\t\t\treturn;\r\n\t\tswitch (cfg.getType()) {\r\n\t\t\tcase DB2:\r\n\t\t\t\tdatabases.add(new DB2(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(), cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase ORACLE:\r\n\t\t\t\tdatabases.add(new Oracle(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase MSSQL:\r\n\t\t\t\tdatabases.add(new MSSQL(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase MYSQL:\r\n\t\t\t\tdatabases.add(new MySQL(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase PGSQL:\r\n\t\t\t\tdatabases.add(new PGSQL(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase ALLBASE:\r\n\t\t\t\tdatabases.add(new ALLBASE(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase SYBASE:\r\n\t\t\t\tdatabases.add(new SYBASE(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase SQLANY:\r\n\t\t\t\tdatabases.add(new SQLANY(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t\tcase DB_NOT_DEFINED:\r\n\t\t\t\tdatabases.add(new DB_NOT_DEFINED(cfg.getDBNameFC(), cfg.getURL(), cfg.getUser(), cfg.getPassword(),cfg.getMaxActive(),cfg.getMaxIdle()\r\n\t\t\t\t\t\t,cfg.getMaxWaitMillis(),cfg.getQueryTimeout(),cfg.getConfigurationUIDs(),cfg.getPersistence()));\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Get databases by configurationUID\r\n\t * @param configurationUID\r\n\t * @return array of DBs\r\n\t */\r\n\tpublic DBAdapter[] getDBsByConfigurationUID(String configurationUID) {\r\n\t\tArrayList<DBAdapter> result = new ArrayList<DBAdapter>(databases.size());\r\n\t\tfor (DBAdapter db : databases) {\r\n\t\t\tif (db.getConfigurationUIDs().contains(configurationUID))\r\n\t\t\t\tresult.add(db);\r\n\t\t}\r\n\t\treturn result.toArray(new DBAdapter[result.size()]);\r\n\t}\r\n\r\n\tpublic DBAdapter[] getDatabases() {\r\n\t\treturn databases.toArray(new DBAdapter[databases.size()]);\r\n\t}\r\n\t\r\n\tpublic DBManager cleanAll() {\r\n\t\tSet<String> configurationUIDs=new HashSet<>();\t\t\r\n\t\tfor(DBAdapter db:getDatabases()){\r\n\t\t\tconfigurationUIDs.addAll(db.getConfigurationUIDs());\r\n\t\t}\t\t\t\t\r\n\t\treturn clean(configurationUIDs);\r\n\t}\r\n\t\r\n\tpublic DBManager clean(Collection<String> configurationUIDs) {\r\n\t\tif(!configurationUIDs.isEmpty()){\r\n\t\t\tfor(DBAdapter db:getDatabases()){\r\n\t\t\t\tdb.getConfigurationUIDs().removeAll(configurationUIDs);\r\n\t\t\t\tif(db.getConfigurationUIDs().isEmpty())\r\n\t\t\t\t\tdb.abort();\r\n\t\t\t}\r\n\t\t\tjava.util.function.Predicate<DBAdapter> dbPredicate=(DBAdapter db)-> db.getConfigurationUIDs().isEmpty();\r\n\t\t\tdatabases.removeIf(dbPredicate);\r\n\t\t\tif(databases.isEmpty())\r\n\t\t\t\tinstance=null;\r\n\t\t}\r\n\t\treturn getInstance();\r\n\t}\r\n\t\r\n\t\r\n\tpublic DBAdapter getDatabaseByName(String dbNameFC) {\r\n\t\tDBAdapter result=null;\r\n\t\tfor(DBAdapter db:databases){\r\n\t\t\tif(db.getName().equals(dbNameFC)){\r\n\t\t\t\tresult=db;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\t\r\n}\r", "public class PersistentDBSender extends Thread {\r\n\r\n\tpublic enum PROTOCOL {\r\n\t\tV14, V18\r\n\t}\r\n\r\n\tprivate static final Logger\tLOG\t\t\t\t\t= Logger.getLogger(PersistentDBSender.class);\r\n\tprivate boolean\t\t\t\tterminate\t\t\t= false;\r\n\tprivate ZabbixServer[]\tconfiguredServers\t= new ZabbixServer[0];\r\n\tprivate ISenderProtocol\t\tprotocol;\r\n\r\n\t\r\n\tpublic PersistentDBSender(PROTOCOL protVer) {\r\n\t\tsuper(\"PersistentDBSender\");\r\n\t\tswitch (protVer) {\r\n\t\tdefault:\r\n\t\t\tprotocol = new Sender18();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tsetDaemon(true);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tLOG.debug(\"PersistentDBSender - starting sender thread\");\r\n\t\twhile (!terminate) {\r\n\t\t\ttry {\r\n\t\t\t\tif (PersistentDB.getInstance().size() == 0L) {\r\n\t\t\t\t\tThread.sleep(60000);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tZabbixServer[] servers;\r\n\t\t\t\t\tsynchronized (configuredServers) {\r\n\t\t\t\t\t\tservers = configuredServers;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tLOG.info(\"PersistentDBSender - retrieving the first element to send\");\r\n\t\t\t\t\twhile (PersistentDB.getInstance().size() != 0L ){\r\n\t\t\t\t\t\tLOG.info(\"PersistentDBSender - found \"+PersistentDB.getInstance().size()+\" persistent items to send\");\r\n\t\t\t\t\t\tZabbixItem zx = (ZabbixItem) PersistentDB.getInstance().pop();\r\n\t\t\t\t\t\tfor (ZabbixServer serverConfig : servers) {\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\tSocket zabbix = null;\r\n\t\t\t\t\t\t\t\tOutputStreamWriter out = null;\r\n\t\t\t\t\t\t\t\tInputStream in = null;\r\n\t\t\t\t\t\t\t\tbyte[] response = new byte[1024];\r\n\r\n\t\t\t\t\t\t\t\tzabbix = new Socket();\r\n\t\t\t\t\t\t\t\tzabbix.setSoTimeout(5000);\r\n\t\t\t\t\t\t\t\tzabbix.connect(new InetSocketAddress(serverConfig.getZServerHost(), serverConfig.getZServerPort()));\r\n\t\t\t\t\t\t\t\tOutputStream os = zabbix.getOutputStream();\r\n\t\t\t\t\t\t\t\tLOG.debug(\"PersistentDBSender - Sending to \" +zx.getHost() + \" Item=\" + zx.getKey() + \" Value=\" + zx.getValue());\r\n\t\t\t\t\t\t\t\tString data = protocol.encodeItem(zx);\r\n\t\t\t\t\t\t\t\tout = new OutputStreamWriter(os);\r\n\t\t\t\t\t\t\t\tout.write(data);\r\n\t\t\t\t\t\t\t\tout.flush();\r\n\r\n\t\t\t\t\t\t\t\tin = zabbix.getInputStream();\r\n\t\t\t\t\t\t\t\tfinal int read = in.read(response);\r\n\t\t\t\t\t\t\t\tif (!protocol.isResponeOK(read, response))\r\n\t\t\t\t\t\t\t\t\tLOG.warn(\"PersistentDBSender - Received unexpected response '\" + new String(response).trim() + \"' for key '\" + zx.getKey()\r\n\t\t\t\t\t\t\t\t\t+ \"'\");\r\n\t\t\t\t\t\t\t\tin.close();\r\n\t\t\t\t\t\t\t\tout.close();\r\n\t\t\t\t\t\t\t\tzabbix.close();\r\n\t\t\t\t\t\t\t}\t\t\t \r\n\t\t\t\t\t\t\tcatch (Exception ex) {\r\n\t\t\t\t\t\t\t\tLOG.error(\"PersistentDBSender - Error contacting Zabbix server \" + configuredServers[0].getZServerHost() +\" port \"+ configuredServers[0].getZServerPort()+ \" - \" + ex.getMessage());\r\n\t\t\t\t\t\t\t\tLOG.debug(\"PersistentDBSender - Current PersistentDB size =\"+PersistentDB.getInstance().size());\r\n\t\t\t\t\t\t\t\tLOG.info(\"PersistentDBSender - Adding the item Adding the item=\"+zx.getHost()+\" key=\"+zx.getKey()+\" value=\"+zx.getValue()+\" clock=\"+zx.getClock()+ \" back to the persisent stack\");\r\n\t\t\t\t\t\t\t\tPersistentDB.getInstance().push(zx);\r\n\t\t\t\t\t\t\t\tLOG.info(\"PersistentDBSender - going to sleep for 1 minute\");\r\n\t\t\t\t\t\t\t\tThread.sleep(60000);\t\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (Exception e) {\r\n\t\t\t\tLOG.debug(\"PersistentDBSender - issue \"+e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tsynchronized public void updateServerList(ZabbixServer[] newServers) {\r\n\t\tsynchronized (configuredServers) {\r\n\t\t\tconfiguredServers = newServers;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void terminate() {\r\n\t\tterminate = true;\r\n\t}\r\n}\r", "public class ZabbixSender extends Thread {\r\n\r\n\tpublic enum PROTOCOL {\r\n\t\tV14, V18, V32\r\n\t}\r\n\r\n\tprivate static final Logger\tLOG\t\t\t\t\t= Logger.getLogger(ZabbixSender.class);\r\n\r\n\tprivate Queue<ZabbixItem>\titems\t\t\t\t= new LinkedBlockingQueue<ZabbixItem>(1000);\r\n\tprivate boolean\t\t\t\tterminate\t\t\t= false;\r\n\tprivate ZabbixServer[]\tconfiguredServers\t= new ZabbixServer[0];\r\n\tprivate ISenderProtocol\t\tprotocol;\r\n\r\n\tpublic ZabbixSender(PROTOCOL protVer) {\r\n\t\tsuper(\"ZabbixSender\");\r\n\t\tswitch (protVer) {\r\n\t\t\tdefault:\r\n\t\t\t\tprotocol = new Sender32();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tsetDaemon(true);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tLOG.debug(\"ZabbixSender - starting sender thread\");\r\n\t\twhile (!terminate) {\r\n\t\t\tif (items.peek() == null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tThread.sleep(100);\r\n\t\t\t\t}\r\n\t\t\t\tcatch (InterruptedException e) {}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//TODO maxItems should be taken from configuration file\r\n\t\t\t\t//take bulk of items to send\r\n\t\t\t\tint maxItems=100;\r\n\t\t\t\t//ZabbixItem[] itemsReady=new ZabbixItem[maxItems];\r\n\t\t\t\t/**\r\n\t\t\t\t * Put item to corresponding Zabbix Server\r\n\t\t\t\t */\r\n\t\t\t\tMap<ZabbixServer,Collection<ZabbixItem>> mZServer2ZItems = new HashMap<>();\r\n\t\t\t\tfor(int i=0;(i<maxItems)&&(items.peek()!=null);++i){\r\n\t\t\t\t\tZabbixItem nextItem=items.poll();\t\t\t\t\t\r\n\t\t\t\t\tif(nextItem.getValue().isEmpty()) {\r\n\t\t\t\t\t\tLOG.warn(\"Item \"+nextItem+\" has empty value!\");\r\n\t\t\t\t\t\t//continue;\r\n\t\t\t\t\t\tnextItem.setValue(\"Item \"+nextItem+\" has empty value!\");\r\n\t\t\t\t\t\tnextItem.setState(ZabbixItem.ZBX_STATE_NOTSUPPORTED);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tZabbixServer zs=nextItem.getConfigurationElement().getZabbixServer();\r\n\t\t\t\t\tif(null == mZServer2ZItems.get(zs))\r\n\t\t\t\t\t\tmZServer2ZItems.put(zs, new HashSet<ZabbixItem>());\r\n\t\t\t\t\tmZServer2ZItems.get(zs).add(nextItem);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor(Entry<ZabbixServer, Collection<ZabbixItem>> m:mZServer2ZItems.entrySet()){\r\n\t\t\t\t\tLOG.debug(\"ZabbixSender: Sending to \" + m.getKey() + \" Items[\" + m.getValue().size() + \"]=\" + m.getValue());\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tConfig config = Config.getInstance();\r\n\t\t\t\t\r\n\t\t\t\tfor (Entry<ZabbixServer, Collection<ZabbixItem>> entry : mZServer2ZItems.entrySet()) {\t\t\t\t\t\r\n\t\t\t\t\tZabbixServer zs=entry.getKey();\r\n\t\t\t\t\tCollection<ZabbixItem> zItems=entry.getValue();\r\n//\t\t\t\t\tCollection<ZabbixItem> zDiscoveries= new HashSet<ZabbixItem>();\r\n//\t\t\t\t\tCollection<ZabbixItem> zHistories = new HashSet<ZabbixItem>();\r\n//\r\n//\t\t\t\t\t// separate Discovery and History data: they should be run in different requests with different types \r\n//\t\t\t\t\tfor(ZabbixItem zItem:zItems){\r\n//\t\t\t\t\t\tif(zItem.getConfItem() instanceof Discovery){\r\n//\t\t\t\t\t\t\tzDiscoveries.add(zItem);\r\n//\t\t\t\t\t\t}else{\r\n//\t\t\t\t\t\t\tzHistories.add(zItem);\r\n//\t\t\t\t\t\t}\r\n//\t\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\t\tboolean persistent = false;\r\n\t\t\t\t\tfor (int i = 0; i < 3; ++i) {\r\n\t\t\t\t\t\tString resp=new String();\r\n\t\t\t\t\t\ttry {\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tString data = protocol.encodeItems(zItems.toArray(new ZabbixItem[0]));\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tLOG.debug(\"ZabbixSender[data]: \"+data);\r\n\t\t\t\t\t\t\tresp=config.requestZabbix(zs.getZServerHost(),zs.getZServerPort(),data);\r\n\t\t\t\t\t\t\tLOG.debug(\"ZabbixSender[resp]: \"+resp);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcatch (Exception ex) {\r\n\t\t\t\t\t\t\tLOG.error(\"ZabbixSender: Error contacting Zabbix server \" + zs.getZServerHost() + \" - \" + ex.getMessage());\r\n\t\t\t\t\t\t\tif (persistent){\r\n\t\t\t\t\t\t\t\tLOG.debug(\"ZabbixSender: Current PeristentStack size =\"+StackSingletonPersistent.getInstance().size());\r\n\t\t\t\t\t\t\t\tLOG.info(\"ZabbixSender - Adding to the persisent stack items: \"+zItems);\r\n\t\t\t\t\t\t\t\tPersistentDB.getInstance().add(zItems);\r\n\t\t\t\t\t\t\t\tLOG.debug(\"ZabbixSender - Current PersistentDB size =\"+PersistentDB.getInstance().size());\t\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tfinally{\r\n\t\t\t\t\t\t\tpersistent = false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void addItem(ZabbixItem item) {\r\n\t\tif (items.size() < 1000)\r\n\t\t\titems.offer(item);\r\n\t}\r\n\r\n\tsynchronized public void updateServerList(ZabbixServer[] newServers) {\r\n\t\tsynchronized (configuredServers) {\r\n\t\t\tconfiguredServers = newServers;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void terminate() {\r\n\t\tterminate = true;\r\n\t}\r\n}\r" ]
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Collection; import java.util.Date; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.daemon.Daemon; import org.apache.commons.daemon.DaemonContext; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import com.smartmarmot.common.Constants; import com.smartmarmot.dbforbix.config.Config; import com.smartmarmot.dbforbix.config.ZabbixServer; import com.smartmarmot.dbforbix.db.DBManager; import com.smartmarmot.dbforbix.zabbix.PersistentDBSender; import com.smartmarmot.dbforbix.zabbix.ZabbixSender;
/* * This file is part of DBforBix. * * DBforBix 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. * * DBforBix 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 * DBforBix. If not, see <http://www.gnu.org/licenses/>. */ package com.smartmarmot.dbforbix; /** * DBforBix daemon main class */ public class DBforBix implements Daemon { private static final Logger LOG = Logger.getLogger(DBforBix.class); private static ZabbixSender _zabbixSender; private static PersistentDBSender persSender; //private static boolean debug = false; private static Options options; private static void reinit(){ //get config instance Config config = Config.getInstance(); // read config file try { config.readFileConfig(); } catch (IOException e) { System.err.println("Error in config: " + e.getLocalizedMessage()); System.exit(-1); } catch (NullPointerException e) { System.err.println("Error while getting config hash file: " + e.getLocalizedMessage()); System.exit(-1); } // init logging // try { // String logfile = config.getLogFile(); // // if (logfile.startsWith("./")) // logfile = logfile.replaceFirst(".", config.getBasedir()); // // PatternLayout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss}] [%-5p] [%t[%M(%F:%L)]]: %m%n"); // RollingFileAppender rfa = new RollingFileAppender(layout, logfile, true); // rfa.setMaxFileSize(config.getLogFileSize()); // rfa.setMaxBackupIndex(1); // // Logger.getRootLogger().addAppender(rfa); // if (!debug) // Logger.getRootLogger().setLevel(config.getLogLevel()); // } // catch (IOException ex) { // System.err.println("Error while configuring logging: " + ex.getLocalizedMessage()); // LOG.error(ex.getLocalizedMessage(), ex); // }
LOG.info("### executing " + Constants.BANNER + ": " + new Date().toString());
0
StephenBlackWasAlreadyTaken/xDrip-Experimental
app/src/main/java/com/eveningoutpost/dexdrip/NavDrawerBuilder.java
[ "@Table(name = \"BgReadings\", id = BaseColumns._ID)\npublic class BgReading extends Model implements ShareUploadableBg{\n public static final double AGE_ADJUSTMENT_TIME = 86400000 * 1.9;\n public static final double AGE_ADJUSTMENT_FACTOR = .45;\n private static boolean predictBG;\n private final static String TAG = BgReading.class.getSimpleName();\n private final static String TAG_ALERT = TAG +\" AlertBg\";\n //TODO: Have these as adjustable settings!!\n public final static double BESTOFFSET = (60000 * 0); // Assume readings are about x minutes off from actual!\n\n @Column(name = \"sensor\", index = true)\n public Sensor sensor;\n\n @Column(name = \"calibration\", index = true)\n public Calibration calibration;\n\n @Expose\n @Column(name = \"timestamp\", index = true)\n public long timestamp;\n\n @Expose\n @Column(name = \"time_since_sensor_started\")\n public double time_since_sensor_started;\n\n @Expose\n @Column(name = \"raw_data\")\n public double raw_data;\n\n @Expose\n @Column(name = \"filtered_data\")\n public double filtered_data;\n\n @Expose\n @Column(name = \"age_adjusted_raw_value\")\n public double age_adjusted_raw_value;\n\n @Expose\n @Column(name = \"calibration_flag\")\n public boolean calibration_flag;\n\n @Expose\n @Column(name = \"calculated_value\")\n public double calculated_value;\n\n @Expose\n @Column(name = \"filtered_calculated_value\")\n public double filtered_calculated_value;\n\n @Expose\n @Column(name = \"calculated_value_slope\")\n public double calculated_value_slope;\n\n @Expose\n @Column(name = \"a\")\n public double a;\n\n @Expose\n @Column(name = \"b\")\n public double b;\n\n @Expose\n @Column(name = \"c\")\n public double c;\n\n @Expose\n @Column(name = \"ra\")\n public double ra;\n\n @Expose\n @Column(name = \"rb\")\n public double rb;\n\n @Expose\n @Column(name = \"rc\")\n public double rc;\n @Expose\n @Column(name = \"uuid\", unique = true , onUniqueConflicts = Column.ConflictAction.IGNORE)\n public String uuid;\n\n @Expose\n @Column(name = \"calibration_uuid\")\n public String calibration_uuid;\n\n @Expose\n @Column(name = \"sensor_uuid\", index = true)\n public String sensor_uuid;\n\n // mapped to the no longer used \"synced\" to keep DB Scheme compatible\n @Column(name = \"snyced\")\n public boolean ignoreForStats;\n\n @Column(name = \"raw_calculated\")\n public double raw_calculated;\n\n @Column(name = \"hide_slope\")\n public boolean hide_slope;\n\n @Column(name = \"noise\")\n public String noise;\n\n public double calculated_value_mmol() {\n return mmolConvert(calculated_value);\n }\n\n public double mmolConvert(double mgdl) {\n return mgdl * Constants.MGDL_TO_MMOLL;\n }\n\n public String displayValue(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String unit = prefs.getString(\"units\", \"mgdl\");\n DecimalFormat df = new DecimalFormat(\"#\");\n df.setMaximumFractionDigits(0);\n\n if (calculated_value >= 400) {\n return \"HIGH\";\n } else if (calculated_value >= 40) {\n if(unit.compareTo(\"mgdl\") == 0) {\n df.setMaximumFractionDigits(0);\n return df.format(calculated_value);\n } else {\n df.setMaximumFractionDigits(1);\n return df.format(calculated_value_mmol());\n }\n } else {\n return \"LOW\";\n }\n }\n\n public static double activeSlope() {\n BgReading bgReading = BgReading.lastNoSenssor();\n if (bgReading != null) {\n double slope = (2 * bgReading.a * (new Date().getTime() + BESTOFFSET)) + bgReading.b;\n Log.i(TAG, \"ESTIMATE SLOPE\" + slope);\n return slope;\n }\n return 0;\n }\n\n public static double activePrediction() {\n BgReading bgReading = BgReading.lastNoSenssor();\n if (bgReading != null) {\n double currentTime = new Date().getTime();\n if (currentTime >= bgReading.timestamp + (60000 * 7)) { currentTime = bgReading.timestamp + (60000 * 7); }\n double time = currentTime + BESTOFFSET;\n return ((bgReading.a * time * time) + (bgReading.b * time) + bgReading.c);\n }\n return 0;\n }\n\n public static Pair<Double, Boolean> calculateSlope(BgReading current, BgReading last) {\n \n if (current.timestamp == last.timestamp || \n current.timestamp - last.timestamp > BgGraphBuilder.MAX_SLOPE_MINUTES * 60 * 1000) {\n return Pair.create(0d, true);\n\n }\n double slope = (last.calculated_value - current.calculated_value) / (last.timestamp - current.timestamp);\n return Pair.create(slope, false);\n }\n\n public static double currentSlope(){\n List<BgReading> last_2 = BgReading.latest(2);\n if (last_2.size() == 2) {\n Pair<Double, Boolean> slopePair = calculateSlope(last_2.get(0), last_2.get(1));\n return slopePair.first;\n } else{\n return 0d;\n }\n\n }\n\n\n //*******CLASS METHODS***********//\n public static void create(EGVRecord[] egvRecords, long addativeOffset, Context context) {\n for(EGVRecord egvRecord : egvRecords) { BgReading.create(egvRecord, addativeOffset, context); }\n }\n\n public static void create(SensorRecord[] sensorRecords, long addativeOffset, Context context) {\n for(SensorRecord sensorRecord : sensorRecords) { BgReading.create(sensorRecord, addativeOffset, context); }\n }\n\n public static void create(SensorRecord sensorRecord, long addativeOffset, Context context) {\n Log.i(TAG, \"create: gonna make some sensor records: \" + sensorRecord.getUnfiltered());\n if(BgReading.is_new(sensorRecord, addativeOffset)) {\n BgReading bgReading = new BgReading();\n Sensor sensor = Sensor.currentSensor();\n Calibration calibration = Calibration.getForTimestamp(sensorRecord.getSystemTime().getTime() + addativeOffset);\n if(sensor != null && calibration != null) {\n bgReading.sensor = sensor;\n bgReading.sensor_uuid = sensor.uuid;\n bgReading.calibration = calibration;\n bgReading.calibration_uuid = calibration.uuid;\n bgReading.raw_data = (sensorRecord.getUnfiltered() / 1000);\n bgReading.filtered_data = (sensorRecord.getFiltered() / 1000);\n bgReading.timestamp = sensorRecord.getSystemTime().getTime() + addativeOffset;\n if(bgReading.timestamp > new Date().getTime()) { return; }\n bgReading.uuid = UUID.randomUUID().toString();\n bgReading.time_since_sensor_started = bgReading.timestamp - sensor.started_at;\n bgReading.calculateAgeAdjustedRawValue(context);\n bgReading.save();\n }\n }\n }\n\n public static void create(EGVRecord egvRecord, long addativeOffset, Context context) {\n BgReading bgReading = BgReading.getForTimestamp(egvRecord.getSystemTime().getTime() + addativeOffset);\n Log.i(TAG, \"create: Looking for BG reading to tag this thing to: \" + egvRecord.getBGValue());\n if(bgReading != null) {\n bgReading.calculated_value = egvRecord.getBGValue();\n if (egvRecord.getBGValue() <= 13) {\n Calibration calibration = bgReading.calibration;\n double firstAdjSlope = calibration.first_slope + (calibration.first_decay * (Math.ceil(new Date().getTime() - calibration.timestamp)/(1000 * 60 * 10)));\n double calSlope = (calibration.first_scale / firstAdjSlope)*1000;\n double calIntercept = ((calibration.first_scale * calibration.first_intercept) / firstAdjSlope)*-1;\n bgReading.raw_calculated = (((calSlope * bgReading.raw_data) + calIntercept) - 5);\n }\n Log.i(TAG, \"create: NEW VALUE CALCULATED AT: \" + bgReading.calculated_value);\n Pair<Double, Boolean> slopePair = BgReading.slopefromName(egvRecord.getTrend().friendlyTrendName());\n bgReading.calculated_value_slope = slopePair.first;\n bgReading.hide_slope = slopePair.second;\n bgReading.noise = egvRecord.noiseValue();\n bgReading.save();\n bgReading.find_new_curve();\n bgReading.find_new_raw_curve();\n context.startService(new Intent(context, Notifications.class));\n BgSendQueue.handleNewBgReading(bgReading, \"create\", context);\n }\n }\n\n public static BgReading getForTimestamp(double timestamp) {\n Sensor sensor = Sensor.currentSensor();\n if(sensor != null) {\n BgReading bgReading = new Select()\n .from(BgReading.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"timestamp <= ?\", (timestamp + (60 * 1000))) // 1 minute padding (should never be that far off, but why not)\n .where(\"calculated_value = 0\")\n .where(\"raw_calculated = 0\")\n .orderBy(\"timestamp desc\")\n .executeSingle();\n if(bgReading != null && Math.abs(bgReading.timestamp - timestamp) < (3*60*1000)) { //cool, so was it actually within 4 minutes of that bg reading?\n Log.i(TAG, \"getForTimestamp: Found a BG timestamp match\");\n return bgReading;\n }\n }\n Log.d(TAG, \"getForTimestamp: No luck finding a BG timestamp match\");\n return null;\n }\n\n public static boolean is_new(SensorRecord sensorRecord, long addativeOffset) {\n double timestamp = sensorRecord.getSystemTime().getTime() + addativeOffset;\n Sensor sensor = Sensor.currentSensor();\n if(sensor != null) {\n BgReading bgReading = new Select()\n .from(BgReading.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"timestamp <= ?\", (timestamp + (60*1000))) // 1 minute padding (should never be that far off, but why not)\n .orderBy(\"timestamp desc\")\n .executeSingle();\n if(bgReading != null && Math.abs(bgReading.timestamp - timestamp) < (3*60*1000)) { //cool, so was it actually within 4 minutes of that bg reading?\n Log.i(TAG, \"isNew; Old Reading\");\n return false;\n }\n }\n Log.i(TAG, \"isNew: New Reading\");\n return true;\n }\n\n public static BgReading create(double raw_data, double filtered_data, Context context, Long timestamp) {\n BgReading bgReading = new BgReading();\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) {\n Log.i(\"BG GSON: \",bgReading.toS());\n\n return bgReading;\n }\n\n Calibration calibration = Calibration.last();\n if (calibration == null) {\n Log.d(TAG, \"create: No calibration yet\");\n bgReading.sensor = sensor;\n bgReading.sensor_uuid = sensor.uuid;\n bgReading.raw_data = (raw_data / 1000);\n bgReading.filtered_data = (filtered_data / 1000);\n bgReading.timestamp = timestamp;\n bgReading.uuid = UUID.randomUUID().toString();\n bgReading.time_since_sensor_started = bgReading.timestamp - sensor.started_at;\n bgReading.calibration_flag = false;\n\n bgReading.calculateAgeAdjustedRawValue(context);\n\n bgReading.save();\n bgReading.perform_calculations();\n } else {\n Log.d(TAG,\"Calibrations, so doing everything\");\n bgReading.sensor = sensor;\n bgReading.sensor_uuid = sensor.uuid;\n bgReading.calibration = calibration;\n bgReading.calibration_uuid = calibration.uuid;\n bgReading.raw_data = (raw_data/1000);\n bgReading.filtered_data = (filtered_data/1000);\n bgReading.timestamp = timestamp;\n bgReading.uuid = UUID.randomUUID().toString();\n bgReading.time_since_sensor_started = bgReading.timestamp - sensor.started_at;\n\n bgReading.calculateAgeAdjustedRawValue(context);\n\n if(calibration.check_in) {\n double firstAdjSlope = calibration.first_slope + (calibration.first_decay * (Math.ceil(new Date().getTime() - calibration.timestamp)/(1000 * 60 * 10)));\n double calSlope = (calibration.first_scale / firstAdjSlope)*1000;\n double calIntercept = ((calibration.first_scale * calibration.first_intercept) / firstAdjSlope)*-1;\n bgReading.calculated_value = (((calSlope * bgReading.raw_data) + calIntercept) - 5);\n bgReading.filtered_calculated_value = (((calSlope * bgReading.ageAdjustedFiltered()) + calIntercept) -5);\n\n } else {\n BgReading lastBgReading = BgReading.last();\n if (lastBgReading != null && lastBgReading.calibration != null) {\n if (lastBgReading.calibration_flag == true && ((lastBgReading.timestamp + (60000 * 20)) > bgReading.timestamp) && ((lastBgReading.calibration.timestamp + (60000 * 20)) > bgReading.timestamp)) {\n lastBgReading.calibration.rawValueOverride(BgReading.weightedAverageRaw(lastBgReading.timestamp, bgReading.timestamp, lastBgReading.calibration.timestamp, lastBgReading.age_adjusted_raw_value, bgReading.age_adjusted_raw_value), context);\n }\n }\n bgReading.calculated_value = ((calibration.slope * bgReading.age_adjusted_raw_value) + calibration.intercept);\n bgReading.filtered_calculated_value = ((calibration.slope * bgReading.ageAdjustedFiltered()) + calibration.intercept);\n }\n updateCalculatedValue(bgReading);\n\n bgReading.save();\n bgReading.perform_calculations();\n context.startService(new Intent(context, Notifications.class));\n BgSendQueue.handleNewBgReading(bgReading, \"create\", context);\n }\n\n Log.i(\"BG GSON: \",bgReading.toS());\n\n return bgReading;\n }\n\n static void updateCalculatedValue(BgReading bgReading ) {\n if (bgReading.calculated_value < 10) {\n bgReading.calculated_value = 38;\n bgReading.hide_slope = true;\n } else {\n bgReading.calculated_value = Math.min(400, Math.max(39, bgReading.calculated_value));\n }\n Log.i(TAG, \"NEW VALUE CALCULATED AT: \" + bgReading.calculated_value);\n }\n\n // Used by xDripViewer\n public static void create(Context context, double raw_data, double age_adjusted_raw_value, double filtered_data, Long timestamp,\n double calculated_bg, double calculated_current_slope, boolean hide_slope, double xdrip_filtered_calculated_value) {\n \n BgReading bgReading = new BgReading();\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) {\n Log.w(TAG, \"No sensor, ignoring this bg reading\");\n return ;\n }\n\n Calibration calibration = Calibration.last();\n if (calibration == null) {\n Log.d(TAG, \"create: No calibration yet\");\n } else {\n Log.d(TAG,\"Calibrations, so doing everything bgReading = \" + bgReading);\n bgReading.calibration = calibration;\n bgReading.calibration_uuid = calibration.uuid;\n }\n \n bgReading.sensor = sensor;\n bgReading.sensor_uuid = sensor.uuid;\n bgReading.raw_data = (raw_data/1000);\n bgReading.age_adjusted_raw_value = age_adjusted_raw_value;\n bgReading.filtered_data = (filtered_data/1000);\n bgReading.timestamp = timestamp;\n bgReading.uuid = UUID.randomUUID().toString();\n bgReading.calculated_value = calculated_bg;\n bgReading.calculated_value_slope = calculated_current_slope;\n bgReading.hide_slope = hide_slope;\n bgReading.filtered_calculated_value = xdrip_filtered_calculated_value;\n bgReading.save();\n\n BgSendQueue.handleNewBgReading(bgReading, \"create\", context);\n\n Log.i(\"BG GSON: \",bgReading.toS());\n }\n\n public static String activeSlopeArrow() {\n double slope = (float) (BgReading.activeSlope() * 60000);\n return slopeToArrowSymbol(slope);\n }\n\n public static String slopeToArrowSymbol(double slope) {\n if (slope <= (-3.5)) {\n return \"\\u21ca\";\n } else if (slope <= (-2)) {\n return \"\\u2193\";\n } else if (slope <= (-1)) {\n return \"\\u2198\";\n } else if (slope <= (1)) {\n return \"\\u2192\";\n } else if (slope <= (2)) {\n return \"\\u2197\";\n } else if (slope <= (3.5)) {\n return \"\\u2191\";\n } else {\n return \"\\u21c8\";\n }\n }\n\n public String slopeArrow(){\n return slopeToArrowSymbol(this.calculated_value_slope*60000);\n }\n\n public String slopeName() {\n double slope_by_minute = calculated_value_slope * 60000;\n String arrow = \"NONE\";\n if (slope_by_minute <= (-3.5)) {\n arrow = \"DoubleDown\";\n } else if (slope_by_minute <= (-2)) {\n arrow = \"SingleDown\";\n } else if (slope_by_minute <= (-1)) {\n arrow = \"FortyFiveDown\";\n } else if (slope_by_minute <= (1)) {\n arrow = \"Flat\";\n } else if (slope_by_minute <= (2)) {\n arrow = \"FortyFiveUp\";\n } else if (slope_by_minute <= (3.5)) {\n arrow = \"SingleUp\";\n } else if (slope_by_minute <= (40)) {\n arrow = \"DoubleUp\";\n }\n if(hide_slope) {\n arrow = \"NOT COMPUTABLE\";\n }\n return arrow;\n }\n\n public static Pair<Double, Boolean> slopefromName(String slope_name) {\n\n double slope_by_minute = 0;\n boolean hide = false;\n if (slope_name.compareTo(\"DoubleDown\") == 0) {\n slope_by_minute = -3.5;\n } else if (slope_name.compareTo(\"SingleDown\") == 0) {\n slope_by_minute = -2;\n } else if (slope_name.compareTo(\"FortyFiveDown\") == 0) {\n slope_by_minute = -1;\n } else if (slope_name.compareTo(\"Flat\") == 0) {\n slope_by_minute = 0;\n } else if (slope_name.compareTo(\"FortyFiveUp\") == 0) {\n slope_by_minute = 2;\n } else if (slope_name.compareTo(\"SingleUp\") == 0) {\n slope_by_minute = 3.5;\n } else if (slope_name.compareTo(\"DoubleUp\") == 0) {\n slope_by_minute = 4;\n } else if (slope_name.compareTo(\"NOT_COMPUTABLE\") == 0 ||\n slope_name.compareTo(\"NOT COMPUTABLE\") == 0 ||\n slope_name.compareTo(\"OUT_OF_RANGE\") == 0 ||\n slope_name.compareTo(\"OUT OF RANGE\") == 0 ||\n slope_name.compareTo(\"NONE\") == 0) {\n slope_by_minute = 0;\n hide = true;\n }\n\n slope_by_minute /= 60000;\n return Pair.create(slope_by_minute, hide);\n }\n\n public static BgReading last() {\n Sensor sensor = Sensor.currentSensor();\n if (sensor != null) {\n return new Select()\n .from(BgReading.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"calculated_value != 0\")\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .executeSingle();\n }\n return null;\n }\n public static List<BgReading> latest_by_size(int number) {\n Sensor sensor = Sensor.currentSensor();\n return new Select()\n .from(BgReading.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .limit(number)\n .execute();\n }\n\n public static BgReading lastNoSenssor() {\n return new Select()\n .from(BgReading.class)\n .where(\"calculated_value != 0\")\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .executeSingle();\n }\n\n public static List<BgReading> latest(int number) {\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) { return null; }\n return new Select()\n .from(BgReading.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"calculated_value != 0\")\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .limit(number)\n .execute();\n }\n\n public static List<BgReading> latestUnCalculated(int number) {\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) { return null; }\n return new Select()\n .from(BgReading.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .limit(number)\n .execute();\n }\n\n public static List<BgReading> latestForGraph(int number, long startTime) {\n return latestForGraph(number, startTime, Long.MAX_VALUE);\n }\n\n public static List<BgReading> latestForGraph(int number, long startTime, long endTime) {\n return new Select()\n .from(BgReading.class)\n .where(\"timestamp >= \" + Math.max(startTime, 0))\n .where(\"timestamp <= \" + endTime)\n .where(\"calculated_value != 0\")\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .limit(number)\n .execute();\n }\n\n public static List<BgReading> last30Minutes() {\n double timestamp = (new Date().getTime()) - (60000 * 30);\n return new Select()\n .from(BgReading.class)\n .where(\"timestamp >= \" + timestamp)\n .where(\"calculated_value != 0\")\n .where(\"raw_data != 0\")\n .orderBy(\"timestamp desc\")\n .execute();\n }\n\n public static List<BgReading> futureReadings() {\n double timestamp = new Date().getTime();\n return new Select()\n .from(BgReading.class)\n .where(\"timestamp > \" + timestamp)\n .orderBy(\"timestamp desc\")\n .execute();\n }\n\n public static BgReading findByUuid(String uuid) {\n return new Select()\n .from(BgReading.class)\n .where(\"uuid = ?\", uuid)\n .executeSingle();\n }\n\n public static double estimated_bg(double timestamp) {\n timestamp = timestamp + BESTOFFSET;\n BgReading latest = BgReading.last();\n if (latest == null) {\n return 0;\n } else {\n return (latest.a * timestamp * timestamp) + (latest.b * timestamp) + latest.c;\n }\n }\n\n public static double estimated_raw_bg(double timestamp) {\n timestamp = timestamp + BESTOFFSET;\n double estimate;\n BgReading latest = BgReading.last();\n if (latest == null) {\n Log.i(TAG, \"No data yet, assume perfect!\");\n estimate = 160;\n } else {\n estimate = (latest.ra * timestamp * timestamp) + (latest.rb * timestamp) + latest.rc;\n }\n Log.i(TAG, \"ESTIMATE RAW BG\" + estimate);\n return estimate;\n }\n\n //*******INSTANCE METHODS***********//\n public void perform_calculations() {\n find_new_curve();\n find_new_raw_curve();\n find_slope();\n }\n\n public void find_slope() {\n List<BgReading> last_2 = BgReading.latest(2);\n\n assert last_2.get(0)==this : \"Invariant condition not fulfilled: calculating slope and current reading wasn't saved before\";\n\n hide_slope = true;\n if (last_2.size() == 2) {\n Pair<Double, Boolean> slopePair = calculateSlope(this, last_2.get(1));\n calculated_value_slope = slopePair.first;\n hide_slope = slopePair.second;\n } else if (last_2.size() == 1) {\n calculated_value_slope = 0;\n } else {\n Log.w(TAG, \"NO BG? COULDNT FIND SLOPE!\");\n calculated_value_slope = 0;\n }\n save();\n }\n\n\n public void find_new_curve() {\n List<BgReading> last_3 = BgReading.latest(3);\n if (last_3.size() == 3) {\n BgReading latest = last_3.get(0);\n BgReading second_latest = last_3.get(1);\n BgReading third_latest = last_3.get(2);\n\n double y3 = latest.calculated_value;\n double x3 = latest. timestamp;\n double y2 = second_latest.calculated_value;\n double x2 = second_latest.timestamp;\n double y1 = third_latest.calculated_value;\n double x1 = third_latest.timestamp;\n\n a = y1/((x1-x2)*(x1-x3))+y2/((x2-x1)*(x2-x3))+y3/((x3-x1)*(x3-x2));\n b = (-y1*(x2+x3)/((x1-x2)*(x1-x3))-y2*(x1+x3)/((x2-x1)*(x2-x3))-y3*(x1+x2)/((x3-x1)*(x3-x2)));\n c = (y1*x2*x3/((x1-x2)*(x1-x3))+y2*x1*x3/((x2-x1)*(x2-x3))+y3*x1*x2/((x3-x1)*(x3-x2)));\n\n Log.i(TAG, \"find_new_curve: BG PARABOLIC RATES: \"+a+\"x^2 + \"+b+\"x + \"+c);\n\n save();\n } else if (last_3.size() == 2) {\n\n Log.i(TAG, \"find_new_curve: Not enough data to calculate parabolic rates - assume Linear\");\n BgReading latest = last_3.get(0);\n BgReading second_latest = last_3.get(1);\n\n double y2 = latest.calculated_value;\n double x2 = latest.timestamp;\n double y1 = second_latest.calculated_value;\n double x1 = second_latest.timestamp;\n\n if(y1 == y2) {\n b = 0;\n } else {\n b = (y2 - y1)/(x2 - x1);\n }\n a = 0;\n c = -1 * ((latest.b * x1) - y1);\n\n Log.i(TAG, \"\"+latest.a+\"x^2 + \"+latest.b+\"x + \"+latest.c);\n save();\n } else {\n Log.i(TAG, \"find_new_curve: Not enough data to calculate parabolic rates - assume static data\");\n a = 0;\n b = 0;\n c = calculated_value;\n\n Log.i(TAG, \"\"+a+\"x^2 + \"+b+\"x + \"+c);\n save();\n }\n }\n\n public void calculateAgeAdjustedRawValue(Context context){\n double adjust_for = AGE_ADJUSTMENT_TIME - time_since_sensor_started;\n if (adjust_for <= 0 || CollectionServiceStarter.isLimitter(context)) {\n age_adjusted_raw_value = raw_data;\n } else {\n age_adjusted_raw_value = ((AGE_ADJUSTMENT_FACTOR * (adjust_for / AGE_ADJUSTMENT_TIME)) * raw_data) + raw_data;\n Log.i(TAG, \"calculateAgeAdjustedRawValue: RAW VALUE ADJUSTMENT FROM:\" + raw_data + \" TO: \" + age_adjusted_raw_value);\n }\n }\n\n public void find_new_raw_curve() {\n List<BgReading> last_3 = BgReading.latest(3);\n if (last_3.size() == 3) {\n BgReading latest = last_3.get(0);\n BgReading second_latest = last_3.get(1);\n BgReading third_latest = last_3.get(2);\n\n double y3 = latest.age_adjusted_raw_value;\n double x3 = latest.timestamp;\n double y2 = second_latest.age_adjusted_raw_value;\n double x2 = second_latest.timestamp;\n double y1 = third_latest.age_adjusted_raw_value;\n double x1 = third_latest.timestamp;\n\n ra = y1/((x1-x2)*(x1-x3))+y2/((x2-x1)*(x2-x3))+y3/((x3-x1)*(x3-x2));\n rb = (-y1*(x2+x3)/((x1-x2)*(x1-x3))-y2*(x1+x3)/((x2-x1)*(x2-x3))-y3*(x1+x2)/((x3-x1)*(x3-x2)));\n rc = (y1*x2*x3/((x1-x2)*(x1-x3))+y2*x1*x3/((x2-x1)*(x2-x3))+y3*x1*x2/((x3-x1)*(x3-x2)));\n\n Log.i(TAG, \"find_new_raw_curve: RAW PARABOLIC RATES: \"+ra+\"x^2 + \"+rb+\"x + \"+rc);\n save();\n } else if (last_3.size() == 2) {\n BgReading latest = last_3.get(0);\n BgReading second_latest = last_3.get(1);\n\n double y2 = latest.age_adjusted_raw_value;\n double x2 = latest.timestamp;\n double y1 = second_latest.age_adjusted_raw_value;\n double x1 = second_latest.timestamp;\n if(y1 == y2) {\n rb = 0;\n } else {\n rb = (y2 - y1)/(x2 - x1);\n }\n ra = 0;\n rc = -1 * ((latest.rb * x1) - y1);\n\n Log.i(TAG, \"find_new_raw_curve: Not enough data to calculate parabolic rates - assume Linear data\");\n\n Log.i(TAG, \"RAW PARABOLIC RATES: \"+ra+\"x^2 + \"+rb+\"x + \"+rc);\n save();\n } else {\n Log.i(TAG, \"find_new_raw_curve: Not enough data to calculate parabolic rates - assume static data\");\n BgReading latest_entry = BgReading.lastNoSenssor();\n ra = 0;\n rb = 0;\n if (latest_entry != null) {\n rc = latest_entry.age_adjusted_raw_value;\n } else {\n rc = 105;\n }\n\n save();\n }\n }\n public static double weightedAverageRaw(double timeA, double timeB, double calibrationTime, double rawA, double rawB) {\n double relativeSlope = (rawB - rawA)/(timeB - timeA);\n double relativeIntercept = rawA - (relativeSlope * timeA);\n return ((relativeSlope * calibrationTime) + relativeIntercept);\n }\n\n public String toS() {\n Gson gson = new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation()\n .registerTypeAdapter(Date.class, new DateTypeAdapter())\n .serializeSpecialFloatingPointValues()\n .create();\n return gson.toJson(this);\n }\n\n public int noiseValue() {\n if(noise == null || noise.compareTo(\"\") == 0) {\n return 1;\n } else {\n return Integer.valueOf(noise);\n }\n }\n\n // list(0) is the most recent reading.\n public static List<BgReading> getXRecentPoints(int NumReadings) {\n List<BgReading> latest = BgReading.latest(NumReadings);\n if (latest == null || latest.size() != NumReadings) {\n // for less than NumReadings readings, we can't tell what the situation\n //\n Log.d(TAG_ALERT, \"getXRecentPoints we don't have enough readings, returning null\");\n return null;\n }\n // So, we have at least three values...\n for(BgReading bgReading : latest) {\n Log.d(TAG_ALERT, \"getXRecentPoints - reading: time = \" + bgReading.timestamp + \" calculated_value \" + bgReading.calculated_value);\n }\n\n // now let's check that they are relevant. the last reading should be from the last 5 minutes,\n // x-1 more readings should be from the last (x-1)*5 minutes. we will allow 5 minutes for the last\n // x to allow one packet to be missed.\n if (new Date().getTime() - latest.get(NumReadings - 1).timestamp > (NumReadings * 5 + 6) * 60 * 1000) {\n Log.d(TAG_ALERT, \"getXRecentPoints we don't have enough points from the last \" + (NumReadings * 5 + 6) + \" minutes, returning null\");\n return null;\n }\n return latest;\n\n }\n\n public static void checkForRisingAllert(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n Boolean rising_alert = prefs.getBoolean(\"rising_alert\", false);\n if(!rising_alert) {\n return;\n }\n if(prefs.getLong(\"alerts_disabled_until\", 0) > new Date().getTime()){\n Log.i(\"NOTIFICATIONS\", \"checkForRisingAllert: Notifications are currently disabled!!\");\n return;\n }\n\n if(IsUnclearTime(context)) {\n Log.d(TAG_ALERT, \"checkForRisingAllert we are in an clear time, returning without doing anything\");\n return ;\n }\n\n String riseRate = prefs.getString(\"rising_bg_val\", \"2\");\n float friseRate = 2;\n\n try\n {\n friseRate = Float.parseFloat(riseRate);\n }\n catch (NumberFormatException nfe)\n {\n Log.e(TAG_ALERT, \"checkForRisingAllert reading falling_bg_val failed, continuing with 2\", nfe);\n }\n Log.d(TAG_ALERT, \"checkForRisingAllert will check for rate of \" + friseRate);\n\n boolean riseAlert = checkForDropRiseAllert(friseRate, false);\n Notifications.RisingAlert(context, riseAlert);\n }\n\n\n public static void checkForDropAllert(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n Boolean falling_alert = prefs.getBoolean(\"falling_alert\", false);\n if(!falling_alert) {\n return;\n }\n if(prefs.getLong(\"alerts_disabled_until\", 0) > new Date().getTime()){\n Log.d(\"NOTIFICATIONS\", \"checkForDropAllert: Notifications are currently disabled!!\");\n return;\n }\n\n if(IsUnclearTime(context)) {\n Log.d(TAG_ALERT, \"checkForDropAllert we are in an clear time, returning without doing anything\");\n return ;\n }\n\n String dropRate = prefs.getString(\"falling_bg_val\", \"2\");\n float fdropRate = 2;\n\n try\n {\n fdropRate = Float.parseFloat(dropRate);\n }\n catch (NumberFormatException nfe)\n {\n Log.e(TAG_ALERT, \"reading falling_bg_val failed, continuing with 2\", nfe);\n }\n Log.i(TAG_ALERT, \"checkForDropAllert will check for rate of \" + fdropRate);\n\n boolean dropAlert = checkForDropRiseAllert(fdropRate, true);\n Notifications.DropAlert(context, dropAlert);\n }\n\n // true say, alert is on.\n private static boolean checkForDropRiseAllert(float MaxSpeed, boolean drop) {\n Log.d(TAG_ALERT, \"checkForDropRiseAllert called drop=\" + drop);\n List<BgReading> latest = getXRecentPoints(4);\n if(latest == null) {\n Log.d(TAG_ALERT, \"checkForDropRiseAllert we don't have enough points from the last 15 minutes, returning false\");\n return false;\n }\n float time3 = (latest.get(0).timestamp - latest.get(3).timestamp) / 60000;\n double bg_diff3 = latest.get(3).calculated_value - latest.get(0).calculated_value;\n if (!drop) {\n bg_diff3 *= (-1);\n }\n Log.i(TAG_ALERT, \"bg_diff3=\" + bg_diff3 + \" time3 = \" + time3);\n if(bg_diff3 < time3 * MaxSpeed) {\n Log.d(TAG_ALERT, \"checkForDropRiseAllert for latest 4 points not fast enough, returning false\");\n return false;\n }\n // we should alert here, but if the last measurement was less than MaxSpeed / 2, I won't.\n\n\n float time1 = (latest.get(0).timestamp - latest.get(1).timestamp) / 60000;\n double bg_diff1 = latest.get(1).calculated_value - latest.get(0).calculated_value;\n if (!drop) {\n bg_diff1 *= (-1);\n }\n\n if(time1 > 7.0) {\n Log.d(TAG_ALERT, \"checkForDropRiseAllert the two points are not close enough, returning true\");\n return true;\n }\n if(bg_diff1 < time1 * MaxSpeed /2) {\n Log.d(TAG_ALERT, \"checkForDropRiseAllert for latest 2 points not fast enough, returning false\");\n return false;\n }\n Log.d(TAG_ALERT, \"checkForDropRiseAllert returning true speed is \" + (bg_diff3 / time3));\n return true;\n }\n\n private static boolean IsUnclearTime(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n Boolean bg_unclear_readings_alerts = prefs.getBoolean(\"bg_unclear_readings_alerts\", false);\n if(bg_unclear_readings_alerts) {\n Long UnclearTimeSetting = Long.parseLong(prefs.getString(\"bg_unclear_readings_minutes\", \"90\")) * 60000;\n Long unclearTime = getUnclearTime(UnclearTimeSetting);\n if (unclearTime > 0) {\n Log.d(TAG_ALERT, \"IsUnclearTime we are in an clear time, returning true\");\n return true;\n }\n }\n return false;\n }\n /*\n * This function comes to check weather we are in a case that we have an allert but since things are\n * getting better we should not do anything. (This is only in the case that the alert was snoozed before.)\n * This means that if this is a low alert, and we have two readings in the last 15 minutes, and\n * either we have gone in 10 in the last two readings, or we have gone in 3 in the last reading, we\n * don't play the alert again, but rather wait for the alert to finish.\n * I'll start with having the same values for the high alerts.\n */\n\n public static boolean trendingToAlertEnd(Context context, boolean above) {\n // TODO: check if we are not in an UnclerTime.\n Log.d(TAG_ALERT, \"trendingToAlertEnd called\");\n\n if(IsUnclearTime(context)) {\n Log.d(TAG_ALERT, \"trendingToAlertEnd we are in an clear time, returning false\");\n return false;\n }\n\n List<BgReading> latest = getXRecentPoints(3);\n if(latest == null) {\n Log.d(TAG_ALERT, \"trendingToAlertEnd we don't have enough points from the last 15 minutes, returning false\");\n return false;\n }\n\n if(above == false) {\n // This is a low alert, we should be going up\n if((latest.get(0).calculated_value - latest.get(1).calculated_value > 4) ||\n (latest.get(0).calculated_value - latest.get(2).calculated_value > 10)) {\n Log.d(TAG_ALERT, \"trendingToAlertEnd returning true for low alert\");\n return true;\n }\n } else {\n // This is a high alert we should be heading down\n if((latest.get(1).calculated_value - latest.get(0).calculated_value > 4) ||\n (latest.get(2).calculated_value - latest.get(0).calculated_value > 10)) {\n Log.d(TAG_ALERT, \"trendingToAlertEnd returning true for high alert\");\n return true;\n }\n }\n Log.d(TAG_ALERT, \"trendingToAlertEnd returning false, not in the right direction (or not fast enough)\");\n return false;\n\n }\n\n // Should that be combined with noiseValue?\n private Boolean Unclear() {\n Log.d(TAG_ALERT, \"Unclear filtered_data=\" + filtered_data + \" raw_data=\" + raw_data);\n return raw_data > filtered_data * 1.3 || raw_data < filtered_data * 0.7;\n }\n\n /*\n * returns the time (in ms) that the state is not clear and no alerts should work\n * The base of the algorithm is that any period can be bad or not. bgReading.Unclear() tells that.\n * a non clear bgReading means MAX_INFLUANCE time after it we are in a bad position\n * Since this code is based on heuristics, and since times are not accurate, boundary issues can be ignored.\n *\n * interstingTime is the period to check. That is if the last period is bad, we want to know how long does it go bad...\n * */\n\n // The extra 120,000 is to allow the packet to be delayed for some time and still be counted in that group\n // Please don't use for MAX_INFLUANCE a number that is complete multiply of 5 minutes (300,000)\n static final int MAX_INFLUANCE = 30 * 60000 - 120000; // A bad point means data is untrusted for 30 minutes.\n private static Long getUnclearTimeHelper(List<BgReading> latest, Long interstingTime, final Long now) {\n\n // The code ignores missing points (that is they some times are treated as good and some times as bad.\n // If this bothers someone, I believe that the list should be filled with the missing points as good and continue to run.\n\n Long LastGoodTime = 0l; // 0 represents that we are not in a good part\n\n Long UnclearTime = 0l;\n for(BgReading bgReading : latest) {\n // going over the readings from latest to first\n if(bgReading.timestamp < now - (interstingTime + MAX_INFLUANCE)) {\n // Some readings are missing, we can stop checking\n break;\n }\n if(bgReading.timestamp <= now - MAX_INFLUANCE && UnclearTime == 0) {\n Log.d(TAG_ALERT, \"We did not have a problematic reading for MAX_INFLUANCE time, so now all is well\");\n return 0l;\n\n }\n if (bgReading.Unclear()) {\n // here we assume that there are no missing points. Missing points might join the good and bad values as well...\n // we should have checked if we have a period, but it is hard to say how to react to them.\n Log.d(TAG_ALERT, \"We have a bad reading, so setting UnclearTime to \" + bgReading.timestamp);\n UnclearTime = bgReading.timestamp;\n LastGoodTime = 0l;\n } else {\n if (LastGoodTime == 0l) {\n Log.d(TAG_ALERT, \"We are starting a good period at \"+ bgReading.timestamp);\n LastGoodTime = bgReading.timestamp;\n } else {\n // we have some good period, is it good enough?\n if(LastGoodTime - bgReading.timestamp >= MAX_INFLUANCE) {\n // Here UnclearTime should be already set, otherwise we will return a toob big value\n if (UnclearTime ==0) {\n Log.wtf(TAG_ALERT, \"ERROR - UnclearTime must not be 0 here !!!\");\n }\n Log.d(TAG_ALERT, \"We have a good period from \" + bgReading.timestamp + \" to \" + LastGoodTime + \"returning \" + (now - UnclearTime +5 *60000));\n return now - UnclearTime + 5 *60000;\n }\n }\n }\n }\n // if we are here, we have a problem... or not.\n if(UnclearTime == 0l) {\n Log.d(TAG_ALERT, \"Since we did not find a good period, but we also did not find a single bad value, we assume things are good\");\n return 0l;\n }\n Log.d(TAG_ALERT, \"We scanned all over, but could not find a good period. we have a bad value, so assuming that the whole period is bad\" +\n \" returning \" + interstingTime);\n // Note that we might now have all the points, and in this case, since we don't have a good period I return a bad period.\n return interstingTime;\n\n }\n\n // This is to enable testing of the function, by passing different values\n public static Long getUnclearTime(Long interstingTime) {\n List<BgReading> latest = BgReading.latest((interstingTime.intValue() + MAX_INFLUANCE)/ 60000 /5 );\n if (latest == null) {\n return 0L;\n }\n final Long now = new Date().getTime();\n return getUnclearTimeHelper(latest, interstingTime, now);\n\n }\n\n public static Long getTimeSinceLastReading() {\n BgReading bgReading = BgReading.last();\n if (bgReading != null) {\n return (new Date().getTime() - bgReading.timestamp);\n }\n return (long) 0;\n }\n\n public double usedRaw() {\n Calibration calibration = Calibration.last();\n if (calibration != null && calibration.check_in) {\n return raw_data;\n }\n return age_adjusted_raw_value;\n }\n\n public double ageAdjustedFiltered(){\n double usedRaw = usedRaw();\n if(usedRaw == raw_data || raw_data == 0d){\n return filtered_data;\n } else {\n // adjust the filtered_data with the same factor as the age adjusted raw value\n return filtered_data * (usedRaw/raw_data);\n }\n }\n\n // the input of this function is a string. each char can be g(=good) or b(=bad) or s(=skip, point unmissed).\n static List<BgReading> createlatestTest(String input, Long now) {\n Random randomGenerator = new Random();\n List<BgReading> out = new LinkedList<BgReading> ();\n char[] chars= input.toCharArray();\n for(int i=0; i < chars.length; i++) {\n BgReading bg = new BgReading();\n int rand = randomGenerator.nextInt(20000) - 10000;\n bg.timestamp = now - i * 5 * 60000 + rand;\n bg.raw_data = 150;\n if(chars[i] == 'g') {\n bg.filtered_data = 151;\n } else if (chars[i] == 'b') {\n bg.filtered_data = 110;\n } else {\n continue;\n }\n out.add(bg);\n }\n return out;\n\n\n }\n static void TestgetUnclearTime(String input, Long interstingTime, Long expectedResult) {\n final Long now = new Date().getTime();\n List<BgReading> readings = createlatestTest(input, now);\n Long result = getUnclearTimeHelper(readings, interstingTime * 60000, now);\n if (result >= expectedResult * 60000 - 20000 && result <= expectedResult * 60000+20000) {\n Log.d(TAG_ALERT, \"Test passed\");\n } else {\n Log.d(TAG_ALERT, \"Test failed expectedResult = \" + expectedResult + \" result = \"+ result / 60000.0);\n }\n\n }\n\n public static void TestgetUnclearTimes() {\n TestgetUnclearTime(\"gggggggggggggggggggggggg\", 90l, 0l * 5);\n TestgetUnclearTime(\"bggggggggggggggggggggggg\", 90l, 1l * 5);\n TestgetUnclearTime(\"bbgggggggggggggggggggggg\", 90l, 2l *5 );\n TestgetUnclearTime(\"gbgggggggggggggggggggggg\", 90l, 2l * 5);\n TestgetUnclearTime(\"gbgggbggbggbggbggbggbgbg\", 90l, 18l * 5);\n TestgetUnclearTime(\"bbbgggggggbbgggggggggggg\", 90l, 3l * 5);\n TestgetUnclearTime(\"ggggggbbbbbbgggggggggggg\", 90l, 0l * 5);\n TestgetUnclearTime(\"ggssgggggggggggggggggggg\", 90l, 0l * 5);\n TestgetUnclearTime(\"ggssbggssggggggggggggggg\", 90l, 5l * 5);\n TestgetUnclearTime(\"bb\", 90l, 18l * 5);\n\n // intersting time is 2 minutes, we should always get 0 (in 5 minutes units\n TestgetUnclearTime(\"gggggggggggggggggggggggg\", 2l, 0l * 5);\n TestgetUnclearTime(\"bggggggggggggggggggggggg\", 2l, 2l);\n TestgetUnclearTime(\"bbgggggggggggggggggggggg\", 2l, 2l);\n TestgetUnclearTime(\"gbgggggggggggggggggggggg\", 2l, 2l);\n TestgetUnclearTime(\"gbgggbggbggbggbggbggbgbg\", 2l, 2l);\n\n // intersting time is 10 minutes, we should always get 0 (in 5 minutes units\n TestgetUnclearTime(\"gggggggggggggggggggggggg\", 10l, 0l * 5);\n TestgetUnclearTime(\"bggggggggggggggggggggggg\", 10l, 1l * 5);\n TestgetUnclearTime(\"bbgggggggggggggggggggggg\", 10l, 2l * 5);\n TestgetUnclearTime(\"gbgggggggggggggggggggggg\", 10l, 2l * 5);\n TestgetUnclearTime(\"gbgggbggbggbggbggbggbgbg\", 10l, 2l * 5);\n TestgetUnclearTime(\"bbbgggggggbbgggggggggggg\", 10l, 2l * 5);\n TestgetUnclearTime(\"ggggggbbbbbbgggggggggggg\", 10l, 0l * 5);\n TestgetUnclearTime(\"ggssgggggggggggggggggggg\", 10l, 0l * 5);\n TestgetUnclearTime(\"ggssbggssggggggggggggggg\", 10l, 2l * 5);\n TestgetUnclearTime(\"bb\", 10l, 2l * 5);\n }\n\n public int getSlopeOrdinal() {\n double slope_by_minute = calculated_value_slope * 60000;\n int ordinal = 0;\n if(!hide_slope) {\n if (slope_by_minute <= (-3.5)) {\n ordinal = 7;\n } else if (slope_by_minute <= (-2)) {\n ordinal = 6;\n } else if (slope_by_minute <= (-1)) {\n ordinal = 5;\n } else if (slope_by_minute <= (1)) {\n ordinal = 4;\n } else if (slope_by_minute <= (2)) {\n ordinal = 3;\n } else if (slope_by_minute <= (3.5)) {\n ordinal = 2;\n } else {\n ordinal = 1;\n }\n }\n return ordinal;\n }\n\n public int getMgdlValue() {\n return (int) calculated_value;\n }\n\n public long getEpochTimestamp() {\n return timestamp;\n }\n}", "@Table(name = \"Calibration\", id = BaseColumns._ID)\npublic class Calibration extends Model {\n private final static String TAG = Calibration.class.getSimpleName();\n\n @Expose\n @Column(name = \"timestamp\", index = true)\n public long timestamp;\n\n @Expose\n @Column(name = \"sensor_age_at_time_of_estimation\")\n public double sensor_age_at_time_of_estimation;\n\n @Column(name = \"sensor\", index = true)\n public Sensor sensor;\n\n @Expose\n @Column(name = \"bg\")\n public double bg;\n\n @Expose\n @Column(name = \"raw_value\")\n public double raw_value;\n//\n// @Expose\n// @Column(name = \"filtered_value\")\n// public double filtered_value;\n\n @Expose\n @Column(name = \"adjusted_raw_value\")\n public double adjusted_raw_value;\n\n @Expose\n @Column(name = \"sensor_confidence\")\n public double sensor_confidence;\n\n @Expose\n @Column(name = \"slope_confidence\")\n public double slope_confidence;\n\n @Expose\n @Column(name = \"raw_timestamp\")\n public long raw_timestamp;\n\n @Expose\n @Column(name = \"slope\")\n public double slope;\n\n @Expose\n @Column(name = \"intercept\")\n public double intercept;\n\n @Expose\n @Column(name = \"distance_from_estimate\")\n public double distance_from_estimate;\n\n @Expose\n @Column(name = \"estimate_raw_at_time_of_calibration\")\n public double estimate_raw_at_time_of_calibration;\n\n @Expose\n @Column(name = \"estimate_bg_at_time_of_calibration\")\n public double estimate_bg_at_time_of_calibration;\n\n @Expose\n @Column(name = \"uuid\", index = true)\n public String uuid;\n\n @Expose\n @Column(name = \"sensor_uuid\", index = true)\n public String sensor_uuid;\n\n @Expose\n @Column(name = \"possible_bad\")\n public Boolean possible_bad;\n\n @Expose\n @Column(name = \"check_in\")\n public boolean check_in;\n\n @Expose\n @Column(name = \"first_decay\")\n public double first_decay;\n\n @Expose\n @Column(name = \"second_decay\")\n public double second_decay;\n\n @Expose\n @Column(name = \"first_slope\")\n public double first_slope;\n\n @Expose\n @Column(name = \"second_slope\")\n public double second_slope;\n\n @Expose\n @Column(name = \"first_intercept\")\n public double first_intercept;\n\n @Expose\n @Column(name = \"second_intercept\")\n public double second_intercept;\n\n @Expose\n @Column(name = \"first_scale\")\n public double first_scale;\n\n @Expose\n @Column(name = \"second_scale\")\n public double second_scale;\n\n public static void initialCalibration(double bg1, double bg2, Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String unit = prefs.getString(\"units\", \"mgdl\");\n\n if(unit.compareTo(\"mgdl\") != 0 ) {\n bg1 = bg1 * Constants.MMOLL_TO_MGDL;\n bg2 = bg2 * Constants.MMOLL_TO_MGDL;\n }\n clear_all_existing_calibrations();\n\n Calibration higherCalibration = new Calibration();\n Calibration lowerCalibration = new Calibration();\n Sensor sensor = Sensor.currentSensor();\n List<BgReading> bgReadings = BgReading.latest_by_size(2);\n BgReading bgReading1 = bgReadings.get(0);\n BgReading bgReading2 = bgReadings.get(1);\n BgReading highBgReading;\n BgReading lowBgReading;\n double higher_bg = Math.max(bg1, bg2);\n double lower_bg = Math.min(bg1, bg2);\n\n if (bgReading1.raw_data > bgReading2.raw_data) {\n highBgReading = bgReading1;\n lowBgReading = bgReading2;\n } else {\n highBgReading = bgReading2;\n lowBgReading = bgReading1;\n }\n\n higherCalibration.bg = higher_bg;\n higherCalibration.slope = 1;\n higherCalibration.intercept = higher_bg;\n higherCalibration.sensor = sensor;\n higherCalibration.estimate_raw_at_time_of_calibration = highBgReading.age_adjusted_raw_value;\n higherCalibration.adjusted_raw_value = highBgReading.age_adjusted_raw_value;\n higherCalibration.raw_value = highBgReading.raw_data;\n higherCalibration.raw_timestamp = highBgReading.timestamp;\n higherCalibration.save();\n\n highBgReading.calculated_value = higher_bg;\n highBgReading.calibration_flag = true;\n highBgReading.calibration = higherCalibration;\n highBgReading.save();\n higherCalibration.save();\n\n lowerCalibration.bg = lower_bg;\n lowerCalibration.slope = 1;\n lowerCalibration.intercept = lower_bg;\n lowerCalibration.sensor = sensor;\n lowerCalibration.estimate_raw_at_time_of_calibration = lowBgReading.age_adjusted_raw_value;\n lowerCalibration.adjusted_raw_value = lowBgReading.age_adjusted_raw_value;\n lowerCalibration.raw_value = lowBgReading.raw_data;\n lowerCalibration.raw_timestamp = lowBgReading.timestamp;\n lowerCalibration.save();\n\n lowBgReading.calculated_value = lower_bg;\n lowBgReading.calibration_flag = true;\n lowBgReading.calibration = lowerCalibration;\n lowBgReading.save();\n lowerCalibration.save();\n\n highBgReading.find_new_curve();\n highBgReading.find_new_raw_curve();\n lowBgReading.find_new_curve();\n lowBgReading.find_new_raw_curve();\n\n List<Calibration> calibrations = new ArrayList<Calibration>();\n calibrations.add(lowerCalibration);\n calibrations.add(higherCalibration);\n\n for(Calibration calibration : calibrations) {\n calibration.timestamp = new Date().getTime();\n calibration.sensor_uuid = sensor.uuid;\n calibration.slope_confidence = .5;\n calibration.distance_from_estimate = 0;\n calibration.check_in = false;\n calibration.sensor_confidence = ((-0.0018 * calibration.bg * calibration.bg) + (0.6657 * calibration.bg) + 36.7505) / 100;\n\n calibration.sensor_age_at_time_of_estimation = calibration.timestamp - sensor.started_at;\n calibration.uuid = UUID.randomUUID().toString();\n calibration.save();\n\n calculate_w_l_s(context);\n CalibrationSendQueue.addToQueue(calibration, context);\n }\n adjustRecentBgReadings(5);\n CalibrationRequest.createOffset(lowerCalibration.bg, 35);\n context.startService(new Intent(context, Notifications.class));\n }\n\n //Create Calibration Checkin\n public static void create(CalRecord[] calRecords, long addativeOffset, Context context) { create(calRecords, context, false, addativeOffset); }\n public static void create(CalRecord[] calRecords, Context context) { create(calRecords, context, false, 0); }\n public static void create(CalRecord[] calRecords, Context context, boolean override, long addativeOffset) {\n //TODO: Change calibration.last and other queries to order calibrations by timestamp rather than ID\n Log.i(\"CALIBRATION-CHECK-IN: \", \"Creating Calibration Record\");\n Sensor sensor = Sensor.currentSensor();\n CalRecord firstCalRecord = calRecords[0];\n CalRecord secondCalRecord = calRecords[0];\n// CalRecord secondCalRecord = calRecords[calRecords.length - 1];\n //TODO: Figgure out how the ratio between the two is determined\n double calSlope = ((secondCalRecord.getScale() / secondCalRecord.getSlope()) + (3 * firstCalRecord.getScale() / firstCalRecord.getSlope())) * 250;\n\n double calIntercept = (((secondCalRecord.getScale() * secondCalRecord.getIntercept()) / secondCalRecord.getSlope()) + ((3 * firstCalRecord.getScale() * firstCalRecord.getIntercept()) / firstCalRecord.getSlope())) / -4;\n if (sensor != null) {\n for(int i = 0; i < firstCalRecord.getCalSubrecords().length - 1; i++) {\n if (((firstCalRecord.getCalSubrecords()[i] != null && Calibration.is_new(firstCalRecord.getCalSubrecords()[i], addativeOffset))) || (i == 0 && override)) {\n CalSubrecord calSubrecord = firstCalRecord.getCalSubrecords()[i];\n\n Calibration calibration = new Calibration();\n calibration.bg = calSubrecord.getCalBGL();\n calibration.timestamp = calSubrecord.getDateEntered().getTime() + addativeOffset;\n calibration.raw_timestamp = calibration.timestamp;\n if (calibration.timestamp > new Date().getTime()) {\n Log.d(TAG, \"ERROR - Calibration timestamp is from the future, wont save!\");\n return;\n }\n calibration.raw_value = calSubrecord.getCalRaw() / 1000;\n calibration.slope = calSlope;\n calibration.intercept = calIntercept;\n\n calibration.sensor_confidence = ((-0.0018 * calibration.bg * calibration.bg) + (0.6657 * calibration.bg) + 36.7505) / 100;\n if (calibration.sensor_confidence <= 0) {\n calibration.sensor_confidence = 0;\n }\n calibration.slope_confidence = 0.8; //TODO: query backwards to find this value near the timestamp\n calibration.estimate_raw_at_time_of_calibration = calSubrecord.getCalRaw() / 1000;\n calibration.sensor = sensor;\n calibration.sensor_age_at_time_of_estimation = calibration.timestamp - sensor.started_at;\n calibration.uuid = UUID.randomUUID().toString();\n calibration.sensor_uuid = sensor.uuid;\n calibration.check_in = true;\n\n calibration.first_decay = firstCalRecord.getDecay();\n calibration.second_decay = secondCalRecord.getDecay();\n calibration.first_slope = firstCalRecord.getSlope();\n calibration.second_slope = secondCalRecord.getSlope();\n calibration.first_scale = firstCalRecord.getScale();\n calibration.second_scale = secondCalRecord.getScale();\n calibration.first_intercept = firstCalRecord.getIntercept();\n calibration.second_intercept = secondCalRecord.getIntercept();\n\n calibration.save();\n CalibrationSendQueue.addToQueue(calibration, context);\n Calibration.requestCalibrationIfRangeTooNarrow();\n }\n }\n if(firstCalRecord.getCalSubrecords()[0] != null && firstCalRecord.getCalSubrecords()[2] == null) {\n if(Calibration.latest(2).size() == 1) {\n Calibration.create(calRecords, context, true, 0);\n }\n }\n context.startService(new Intent(context, Notifications.class));\n }\n }\n\n public static boolean is_new(CalSubrecord calSubrecord, long addativeOffset) {\n Sensor sensor = Sensor.currentSensor();\n Calibration calibration = new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"timestamp <= ?\", calSubrecord.getDateEntered().getTime() + addativeOffset + (1000 * 60 * 2))\n .orderBy(\"timestamp desc\")\n .executeSingle();\n if(calibration != null && Math.abs(calibration.timestamp - (calSubrecord.getDateEntered().getTime() + addativeOffset)) < (4*60*1000)) {\n Log.d(\"CAL CHECK IN \", \"Already have that calibration!\");\n return false;\n } else {\n Log.d(\"CAL CHECK IN \", \"Looks like a new calibration!\");\n return true;\n }\n }\n public static Calibration getForTimestamp(double timestamp) {\n Sensor sensor = Sensor.currentSensor();\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .where(\"timestamp < ?\", timestamp)\n .orderBy(\"timestamp desc\")\n .executeSingle();\n }\n\n public static Calibration getByTimestamp(double timestamp) {\n Sensor sensor = Sensor.currentSensor();\n if(sensor == null) {\n return null;\n }\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"timestamp = ?\", timestamp)\n .executeSingle();\n }\n\n public static Calibration create(double bg, Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String unit = prefs.getString(\"units\", \"mgdl\");\n boolean adjustPast = prefs.getBoolean(\"adjust_past\", false);\n\n if(unit.compareTo(\"mgdl\") != 0 ) {\n bg = bg * Constants.MMOLL_TO_MGDL;\n }\n\n CalibrationRequest.clearAll();\n Calibration calibration = new Calibration();\n Sensor sensor = Sensor.currentSensor();\n\n if (sensor != null) {\n BgReading bgReading = BgReading.last();\n if (bgReading != null) {\n calibration.sensor = sensor;\n calibration.bg = bg;\n calibration.check_in = false;\n calibration.timestamp = new Date().getTime();\n calibration.raw_value = bgReading.raw_data;\n calibration.adjusted_raw_value = bgReading.age_adjusted_raw_value;\n calibration.sensor_uuid = sensor.uuid;\n calibration.slope_confidence = Math.min(Math.max(((4 - Math.abs((bgReading.calculated_value_slope) * 60000))/4), 0), 1);\n\n double estimated_raw_bg = BgReading.estimated_raw_bg(new Date().getTime());\n calibration.raw_timestamp = bgReading.timestamp;\n if (Math.abs(estimated_raw_bg - bgReading.age_adjusted_raw_value) > 20) {\n calibration.estimate_raw_at_time_of_calibration = bgReading.age_adjusted_raw_value;\n } else {\n calibration.estimate_raw_at_time_of_calibration = estimated_raw_bg;\n }\n calibration.distance_from_estimate = Math.abs(calibration.bg - bgReading.calculated_value);\n calibration.sensor_confidence = Math.max(((-0.0018 * bg * bg) + (0.6657 * bg) + 36.7505) / 100, 0);\n calibration.sensor_age_at_time_of_estimation = calibration.timestamp - sensor.started_at;\n calibration.uuid = UUID.randomUUID().toString();\n calibration.save();\n\n bgReading.calibration = calibration;\n bgReading.calibration_flag = true;\n bgReading.save();\n BgSendQueue.handleNewBgReading(bgReading, \"update\", context);\n\n calculate_w_l_s(context);\n\n adjustRecentBgReadings(adjustPast?30:1);\n CalibrationSendQueue.addToQueue(calibration, context);\n context.startService(new Intent(context, Notifications.class));\n Calibration.requestCalibrationIfRangeTooNarrow();\n }\n } else {\n Log.d(\"CALIBRATION\", \"No sensor, cant save!\");\n }\n return Calibration.last();\n }\n\n // Used by xDripViewer\n public static void createUpdate(String xDrip_sensor_uuid, double bg, long timeStamp, double intercept, double slope, \n double estimate_raw_at_time_of_calibration, double slope_confidence , double sensor_confidence, \n long raw_timestamp) {\n Sensor sensor = Sensor.getByUuid(xDrip_sensor_uuid);\n\n if (sensor == null) {\n Log.d(\"CALIBRATION\", \"No sensor found, ignoring cailbration\");\n return;\n }\n \n Calibration calibration = getByTimestamp(timeStamp);\n if (calibration != null) {\n Log.d(\"CALIBRATION\", \"updatinga an existing calibration\");\n } else {\n Log.d(\"CALIBRATION\", \"creating a new calibration\");\n calibration = new Calibration();\n }\n\n calibration.sensor = sensor;\n calibration.bg = bg;\n calibration.timestamp = timeStamp;\n calibration.sensor_uuid = sensor.uuid;\n calibration.uuid = UUID.randomUUID().toString();\n calibration.intercept = intercept;\n calibration.slope = slope;\n calibration.estimate_raw_at_time_of_calibration = estimate_raw_at_time_of_calibration;\n calibration.slope_confidence = slope_confidence;\n calibration.sensor_confidence = sensor_confidence;\n calibration.raw_timestamp = raw_timestamp;\n calibration.check_in = false;\n calibration.save();\n }\n \n public static List<Calibration> allForSensorInLastFiveDays() {\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) { return null; }\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .where(\"timestamp > ?\", (new Date().getTime() - (60000 * 60 * 24 * 5)))\n .orderBy(\"timestamp desc\")\n .execute();\n }\n\n private static void calculate_w_l_s(Context context) {\n\n SlopeParameters sParams = getSlopeParameters(context);\n\n if (Sensor.isActive()) {\n double l = 0;\n double m = 0;\n double n = 0;\n double p = 0;\n double q = 0;\n double w;\n List<Calibration> calibrations = allForSensorInLastFourDays(); //5 days was a bit much, dropped this to 4\n if (calibrations.size() <= 1) {\n Calibration calibration = Calibration.last();\n calibration.slope = 1;\n calibration.intercept = calibration.bg - (calibration.raw_value * calibration.slope);\n calibration.save();\n CalibrationRequest.createOffset(calibration.bg, 25);\n } else {\n for (Calibration calibration : calibrations) {\n w = calibration.calculateWeight();\n l += (w);\n m += (w * calibration.estimate_raw_at_time_of_calibration);\n n += (w * calibration.estimate_raw_at_time_of_calibration * calibration.estimate_raw_at_time_of_calibration);\n p += (w * calibration.bg);\n q += (w * calibration.estimate_raw_at_time_of_calibration * calibration.bg);\n }\n\n Calibration last_calibration = Calibration.last();\n w = (last_calibration.calculateWeight() * (calibrations.size() * 0.14));\n l += (w);\n m += (w * last_calibration.estimate_raw_at_time_of_calibration);\n n += (w * last_calibration.estimate_raw_at_time_of_calibration * last_calibration.estimate_raw_at_time_of_calibration);\n p += (w * last_calibration.bg);\n q += (w * last_calibration.estimate_raw_at_time_of_calibration * last_calibration.bg);\n\n double d = (l * n) - (m * m);\n Calibration calibration = Calibration.last();\n calibration.intercept = ((n * p) - (m * q)) / d;\n calibration.slope = ((l * q) - (m * p)) / d;\n if ((calibrations.size() == 2 && calibration.slope < sParams.getLowSlope1()) || (calibration.slope < sParams.getLowSlope2())) { // I have not seen a case where a value below 7.5 proved to be accurate but we should keep an eye on this\n calibration.slope = calibration.slopeOOBHandler(0, context);\n if(calibrations.size() > 2) { calibration.possible_bad = true; }\n calibration.intercept = calibration.bg - (calibration.estimate_raw_at_time_of_calibration * calibration.slope);\n CalibrationRequest.createOffset(calibration.bg, 25);\n }\n if ((calibrations.size() == 2 && calibration.slope > sParams.getHighSlope1()) || (calibration.slope > sParams.getHighSlope2())) {\n calibration.slope = calibration.slopeOOBHandler(1, context);\n if(calibrations.size() > 2) { calibration.possible_bad = true; }\n calibration.intercept = calibration.bg - (calibration.estimate_raw_at_time_of_calibration * calibration.slope);\n CalibrationRequest.createOffset(calibration.bg, 25);\n }\n Log.d(TAG, \"Calculated Calibration Slope: \" + calibration.slope);\n Log.d(TAG, \"Calculated Calibration intercept: \" + calibration.intercept);\n calibration.save();\n }\n } else {\n Log.d(TAG, \"NO Current active sensor found!!\");\n }\n }\n\n @NonNull\n private static SlopeParameters getSlopeParameters(Context context) {\n return CollectionServiceStarter.isLimitter(context)? new LiParameters(): new DexParameters();\n }\n\n private double slopeOOBHandler(int status, Context context) {\n\n SlopeParameters sParams = getSlopeParameters(context);\n\n // If the last slope was reasonable and reasonably close, use that, otherwise use a slope that may be a little steep, but its best to play it safe when uncertain\n List<Calibration> calibrations = Calibration.latest(3);\n Calibration thisCalibration = calibrations.get(0);\n if(status == 0) {\n if (calibrations.size() == 3) {\n if ((Math.abs(thisCalibration.bg - thisCalibration.estimate_bg_at_time_of_calibration) < 30) && (calibrations.get(1).possible_bad != null && calibrations.get(1).possible_bad == true)) {\n return calibrations.get(1).slope;\n } else {\n return Math.max(((-0.048) * (thisCalibration.sensor_age_at_time_of_estimation / (60000 * 60 * 24))) + 1.1, sParams.getDefaultLowSlopeLow());\n }\n } else if (calibrations.size() == 2) {\n return Math.max(((-0.048) * (thisCalibration.sensor_age_at_time_of_estimation / (60000 * 60 * 24))) + 1.1, sParams.getDefaultLowSlopeHigh());\n }\n return sParams.getDefaultSlope();\n } else {\n if (calibrations.size() == 3) {\n if ((Math.abs(thisCalibration.bg - thisCalibration.estimate_bg_at_time_of_calibration) < 30) && (calibrations.get(1).possible_bad != null && calibrations.get(1).possible_bad == true)) {\n return calibrations.get(1).slope;\n } else {\n return sParams.getDefaultHighSlopeHigh();\n }\n } else if (calibrations.size() == 2) {\n return sParams.getDefaulHighSlopeLow();\n }\n }\n return sParams.getDefaultSlope();\n }\n\n private static List<Calibration> calibrations_for_sensor(Sensor sensor) {\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ?\", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .orderBy(\"timestamp desc\")\n .execute();\n }\n\n private double calculateWeight() {\n double firstTimeStarted = Calibration.first().sensor_age_at_time_of_estimation;\n double lastTimeStarted = Calibration.last().sensor_age_at_time_of_estimation;\n double time_percentage = Math.min(((sensor_age_at_time_of_estimation - firstTimeStarted) / (lastTimeStarted - firstTimeStarted)) / (.85), 1);\n time_percentage = (time_percentage + .01);\n Log.i(TAG, \"CALIBRATIONS TIME PERCENTAGE WEIGHT: \" + time_percentage);\n return Math.max((((((slope_confidence + sensor_confidence) * (time_percentage))) / 2) * 100), 1);\n }\n public static void adjustRecentBgReadings() {// This just adjust the last 30 bg readings transition from one calibration point to the next\n adjustRecentBgReadings(30);\n }\n\n public static void adjustRecentBgReadings(int adjustCount) {\n //TODO: add some handling around calibration overrides as they come out looking a bit funky\n List<Calibration> calibrations = Calibration.latest(3);\n List<BgReading> bgReadings = BgReading.latestUnCalculated(adjustCount);\n if (calibrations.size() == 3) {\n int denom = bgReadings.size();\n Calibration latestCalibration = calibrations.get(0);\n int i = 0;\n for (BgReading bgReading : bgReadings) {\n double oldYValue = bgReading.calculated_value;\n double newYvalue = (bgReading.age_adjusted_raw_value * latestCalibration.slope) + latestCalibration.intercept;\n bgReading.calculated_value = ((newYvalue * (denom - i)) + (oldYValue * ( i ))) / denom;\n bgReading.save();\n i += 1;\n }\n } else if (calibrations.size() == 2) {\n Calibration latestCalibration = calibrations.get(0);\n for (BgReading bgReading : bgReadings) {\n double newYvalue = (bgReading.age_adjusted_raw_value * latestCalibration.slope) + latestCalibration.intercept;\n bgReading.calculated_value = newYvalue;\n BgReading.updateCalculatedValue(bgReading);\n bgReading.save();\n\n }\n }\n bgReadings.get(0).find_new_raw_curve();\n bgReadings.get(0).find_new_curve();\n }\n\n public void rawValueOverride(double rawValue, Context context) {\n estimate_raw_at_time_of_calibration = rawValue;\n save();\n calculate_w_l_s(context);\n CalibrationSendQueue.addToQueue(this, context);\n }\n\n public static void requestCalibrationIfRangeTooNarrow() {\n double max = Calibration.max_recent();\n double min = Calibration.min_recent();\n if ((max - min) < 55) {\n double avg = ((min + max) / 2);\n double dist = max - avg;\n CalibrationRequest.createOffset(avg, dist + 20);\n }\n }\n\n public static void clear_all_existing_calibrations() {\n CalibrationRequest.clearAll();\n List<Calibration> pastCalibrations = Calibration.allForSensor();\n if (pastCalibrations != null) {\n for(Calibration calibration : pastCalibrations){\n calibration.slope_confidence = 0;\n calibration.sensor_confidence = 0;\n calibration.save();\n }\n }\n\n }\n \n public static void clearLastCalibration(Context context) {\n \n Calibration last_calibration = Calibration.last();\n if(last_calibration == null) {\n return;\n }\n last_calibration.sensor_confidence = 0;\n last_calibration.slope_confidence = 0;\n last_calibration.save();\n CalibrationSendQueue.addToQueue(last_calibration, context);\n }\n\n public String toS() {\n Gson gson = new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation()\n .registerTypeAdapter(Date.class, new DateTypeAdapter())\n .serializeSpecialFloatingPointValues()\n .create();\n return gson.toJson(this);\n }\n\n //COMMON SCOPES!\n public static Calibration last() {\n Sensor sensor = Sensor.currentSensor();\n if(sensor == null) {\n return null;\n }\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .orderBy(\"timestamp desc\")\n .executeSingle();\n }\n\n public static Calibration first() {\n Sensor sensor = Sensor.currentSensor();\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .orderBy(\"timestamp asc\")\n .executeSingle();\n }\n public static double max_recent() {\n Sensor sensor = Sensor.currentSensor();\n Calibration calibration = new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .where(\"timestamp > ?\", (new Date().getTime() - (60000 * 60 * 24 * 4)))\n .orderBy(\"bg desc\")\n .executeSingle();\n if(calibration != null) {\n return calibration.bg;\n } else {\n return 120;\n }\n }\n\n public static double min_recent() {\n Sensor sensor = Sensor.currentSensor();\n Calibration calibration = new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .where(\"timestamp > ?\", (new Date().getTime() - (60000 * 60 * 24 * 4)))\n .orderBy(\"bg asc\")\n .executeSingle();\n if(calibration != null) {\n return calibration.bg;\n } else {\n return 100;\n }\n }\n\n public static List<Calibration> latest(int number) {\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) { return null; }\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .orderBy(\"timestamp desc\")\n .limit(number)\n .execute();\n }\n\n public static List<Calibration> latestForGraph(int number, long startTime, long endTime) {\n return new Select()\n .from(Calibration.class)\n .where(\"timestamp >= \" + Math.max(startTime, 0))\n .where(\"timestamp <= \" + endTime)\n .orderBy(\"timestamp desc\")\n .limit(number)\n .execute();\n }\n\n public static List<Calibration> allForSensor() {\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) { return null; }\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .orderBy(\"timestamp desc\")\n .execute();\n }\n\n public static List<Calibration> allForSensorInLastFourDays() {\n Sensor sensor = Sensor.currentSensor();\n if (sensor == null) { return null; }\n return new Select()\n .from(Calibration.class)\n .where(\"Sensor = ? \", sensor.getId())\n .where(\"slope_confidence != 0\")\n .where(\"sensor_confidence != 0\")\n .where(\"timestamp > ?\", (new Date().getTime() - (60000 * 60 * 24 * 4)))\n .orderBy(\"timestamp desc\")\n .execute();\n }\n\n public static List<Calibration> futureCalibrations() {\n double timestamp = new Date().getTime();\n return new Select()\n .from(Calibration.class)\n .where(\"timestamp > \" + timestamp)\n .orderBy(\"timestamp desc\")\n .execute();\n }\n}", "@Table(name = \"Sensors\", id = BaseColumns._ID)\npublic class Sensor extends Model {\n\n// @Expose\n @Column(name = \"started_at\", index = true)\n public long started_at;\n\n// @Expose\n @Column(name = \"stopped_at\")\n public long stopped_at;\n\n// @Expose\n //latest minimal battery level\n @Column(name = \"latest_battery_level\")\n public int latest_battery_level;\n\n// @Expose\n @Column(name = \"uuid\", index = true)\n public String uuid;\n\n// @Expose\n @Column(name = \"sensor_location\")\n public String sensor_location;\n\n public static Sensor create(long started_at, String uuid) {\n Sensor sensor = new Sensor();\n sensor.started_at = started_at;\n sensor.uuid = uuid;\n\n sensor.save();\n SensorSendQueue.addToQueue(sensor);\n Log.d(\"SENSOR MODEL:\", sensor.toString());\n return sensor;\n }\n \n // Used by xDripViewer\n public static void createUpdate(long started_at, long stopped_at, int latest_battery_level, String uuid) {\n\n Sensor sensor = getByTimestamp(started_at);\n if (sensor != null) {\n Log.d(\"SENSOR\", \"updatinga an existing sensor\");\n } else {\n Log.d(\"SENSOR\", \"creating a new sensor\");\n sensor = new Sensor();\n }\n sensor.started_at = started_at;\n sensor.stopped_at = stopped_at;\n sensor.latest_battery_level = latest_battery_level;\n sensor.uuid = uuid;\n sensor.save();\n }\n \n public static void stopSensor() {\n Sensor sensor = currentSensor();\n if(sensor == null) {\n return;\n }\n sensor.stopped_at = new Date().getTime();\n Log.i(\"SENSOR\", \"Sensor stopped at \" + sensor.stopped_at);\n sensor.save();\n SensorSendQueue.addToQueue(sensor);\n \n }\n\n public static Sensor currentSensor() {\n Sensor sensor = new Select()\n .from(Sensor.class)\n .where(\"started_at != 0\")\n .where(\"stopped_at = 0\")\n .orderBy(\"_ID desc\")\n .limit(1)\n .executeSingle();\n return sensor;\n }\n\n public static boolean isActive() {\n Sensor sensor = new Select()\n .from(Sensor.class)\n .where(\"started_at != 0\")\n .where(\"stopped_at = 0\")\n .orderBy(\"_ID desc\")\n .limit(1)\n .executeSingle();\n if(sensor == null) {\n return false;\n } else {\n return true;\n }\n }\n \n public static Sensor getByTimestamp(double started_at) {\n return new Select()\n .from(Sensor.class)\n .where(\"started_at = ?\", started_at)\n .executeSingle();\n }\n \n public static Sensor getByUuid(String xDrip_sensor_uuid) {\n if(xDrip_sensor_uuid == null) {\n Log.e(\"SENSOR\", \"xDrip_sensor_uuid is null\");\n return null;\n }\n Log.e(\"SENSOR\", \"xDrip_sensor_uuid is \" + xDrip_sensor_uuid);\n \n return new Select()\n .from(Sensor.class)\n .where(\"uuid = ?\", xDrip_sensor_uuid)\n .executeSingle();\n }\n \n public static Sensor last() {\n Sensor sensor = new Select()\n .from(Sensor.class)\n .orderBy(\"_ID desc\")\n .limit(1)\n .executeSingle();\n return sensor;\n }\n\n public static void updateBatteryLevel(Sensor sensor, int sensorBatteryLevel) {\n if(sensorBatteryLevel < 120) {\n // This must be a wrong battery level. Some transmitter send those every couple of readings\n // even if the battery is ok.\n return;\n }\n int startBatteryLevel = sensor.latest_battery_level;\n if(sensor.latest_battery_level == 0) {\n sensor.latest_battery_level = sensorBatteryLevel;\n } else {\n sensor.latest_battery_level = Math.min(sensor.latest_battery_level, sensorBatteryLevel);\n }\n if(startBatteryLevel == sensor.latest_battery_level) {\n // no need to update anything if nothing has changed.\n return;\n }\n sensor.save();\n SensorSendQueue.addToQueue(sensor);\n }\n \n public static void updateSensorLocation(String sensor_location) {\n Sensor sensor = currentSensor();\n if (sensor == null) {\n Log.e(\"SENSOR\", \"updateSensorLocation called but sensor is null\");\n return;\n }\n sensor.sensor_location = sensor_location;\n sensor.save();\n }\n}", "public class XDripViewer extends AsyncTaskBase {\r\n\r\n static Sensor sensor_exists = null; // Will hold reference to any existing sensor, to avoid looking in DB\r\n static Boolean isNightScoutMode = null;\r\n public final static String NIGHTSCOUT_SENSOR_UUID = \"c5f1999c-4ec5-449e-adad-3980b172b921\";\r\n\r\n private final static String TAG = XDripViewer.class.getName();\r\n \r\n XDripViewer(Context ctx) {\r\n super(ctx, TAG);\r\n }\r\n\r\n @Override\r\n public void readData() {\r\n try {\r\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\r\n String rest_addresses = prefs.getString(\"xdrip_viewer_ns_addresses\", \"\");\r\n String hashedSecret = \"\";\r\n readSensorData(rest_addresses, hashedSecret);\r\n readCalData(rest_addresses, hashedSecret);\r\n readBgData(rest_addresses, hashedSecret);\r\n } catch (Exception e) {\r\n Log.e(TAG, \"readData cought exception in xDrip viewer mode \", e);\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n\r\n private void readSensorData(String baseUrl, String key) {\r\n\r\n NsRestApiReader nsRestApiReader = new NsRestApiReader();\r\n Long LastReportedTime = 0L;\r\n\r\n Sensor lastSensor = Sensor.currentSensor();\r\n\r\n if(lastSensor != null) {\r\n LastReportedTime = (long)lastSensor.started_at;\r\n }\r\n Log.e(TAG, \"readSensorData LastReportedTime = \" + LastReportedTime);\r\n\r\n List<NightscoutSensor> nightscoutSensors = nsRestApiReader.readSensorDataFromNs(baseUrl, key, LastReportedTime, 10 );\r\n if(nightscoutSensors == null) {\r\n Log.e(TAG, \"readBgDataFromNs returned null\");\r\n return;\r\n }\r\n\r\n ListIterator<NightscoutSensor> li = nightscoutSensors.listIterator(nightscoutSensors.size());\r\n long lastInserted = 0;\r\n while(li.hasPrevious()) {\r\n NightscoutSensor nightscoutSensor = li.previous();\r\n Log.e(TAG, \"nightscoutSensor \" + nightscoutSensor.xDrip_uuid + \" \" + nightscoutSensor.xDrip_started_at);\r\n if(nightscoutSensor.xDrip_started_at < lastInserted) {\r\n Log.e(TAG, \"not inserting Sensor, since order is wrong. \");\r\n continue;\r\n }\r\n Sensor.createUpdate(nightscoutSensor.xDrip_started_at, nightscoutSensor.xDrip_stopped_at, nightscoutSensor.xDrip_latest_battery_level, nightscoutSensor.xDrip_uuid);\r\n lastInserted = nightscoutSensor.xDrip_started_at;\r\n }\r\n } \r\n\r\n private void readCalData(String baseUrl, String key) {\r\n\r\n NsRestApiReader nsRestApiReader = new NsRestApiReader();\r\n Long LastReportedTime = 0L;\r\n\r\n Calibration lastCalibration = Calibration.last();\r\n\r\n if(lastCalibration != null) {\r\n LastReportedTime = (long)lastCalibration.timestamp;\r\n }\r\n Log.e(TAG, \"readCalData LastReportedTime = \" + LastReportedTime);\r\n\r\n List<NightscoutMbg> nightscoutMbgs = nsRestApiReader.readCalDataFromNs(baseUrl, key, LastReportedTime, 10 );\r\n if(nightscoutMbgs == null) {\r\n Log.e(TAG, \"readCalDataFromNs returned null\");\r\n return;\r\n }\r\n\r\n ListIterator<NightscoutMbg> li = nightscoutMbgs.listIterator(nightscoutMbgs.size());\r\n long lastInserted = 0;\r\n while(li.hasPrevious()) {\r\n NightscoutMbg nightscoutMbg = li.previous();\r\n Log.e(TAG, \"NightscoutMbg \" + nightscoutMbg.mbg + \" \" + nightscoutMbg.date);\r\n if(nightscoutMbg.date < lastInserted) {\r\n Log.e(TAG, \"not inserting calibratoin, since order is wrong. \");\r\n continue;\r\n }\r\n \r\n verifyViewerNightscoutMode(mContext, nightscoutMbg);\r\n \r\n Calibration.createUpdate(nightscoutMbg.xDrip_sensor_uuid, nightscoutMbg.mbg, nightscoutMbg.date, nightscoutMbg.xDrip_intercept, nightscoutMbg.xDrip_slope, nightscoutMbg.xDrip_estimate_raw_at_time_of_calibration,\r\n nightscoutMbg.xDrip_slope_confidence , nightscoutMbg.xDrip_sensor_confidence, nightscoutMbg.xDrip_raw_timestamp);\r\n lastInserted = nightscoutMbg.date;\r\n }\r\n } \r\n \r\n \r\n private void readBgData(String baseUrl, String key) {\r\n \r\n NsRestApiReader nsRestApiReader = new NsRestApiReader();\r\n Long LastReportedTime = 0L;\r\n TransmitterData lastTransmitterData = TransmitterData.last();\r\n if(lastTransmitterData != null) {\r\n LastReportedTime = lastTransmitterData.timestamp;\r\n }\r\n Log.e(TAG, \"readBgData LastReportedTime = \" + LastReportedTime);\r\n \r\n List<NightscoutBg> nightscoutBgs = nsRestApiReader.readBgDataFromNs(baseUrl,key, LastReportedTime, 12 * 36 );\r\n if(nightscoutBgs == null) {\r\n Log.e(TAG, \"readBgDataFromNs returned null\");\r\n return;\r\n }\r\n Log.e(TAG, \"readBgData finished reading from ns\");\r\n \r\n ListIterator<NightscoutBg> li = nightscoutBgs.listIterator(nightscoutBgs.size());\r\n long lastInserted = 0;\r\n while(li.hasPrevious()) {\r\n // also load to other table !!!\r\n NightscoutBg nightscoutBg = li.previous();\r\n Log.e(TAG, \"nightscoutBg \" + nightscoutBg.sgv + \" \" + nightscoutBg.xDrip_raw + \" \" + mContext);\r\n if(nightscoutBg.date == lastInserted) {\r\n Log.w(TAG, \"not inserting packet, since it seems duplicate \");\r\n continue;\r\n }\r\n if(nightscoutBg.date < lastInserted) {\r\n Log.e(TAG, \"not inserting packet, since order is wrong. \");\r\n continue;\r\n }\r\n \r\n verifyViewerNightscoutMode(mContext, nightscoutBg);\r\n \r\n TransmitterData.create((int)nightscoutBg.xDrip_raw, 100 /* ??????? */, nightscoutBg.date);\r\n BgReading.create(mContext, \r\n nightscoutBg.xDrip_raw != 0 ? nightscoutBg.xDrip_raw * 1000 : nightscoutBg.unfiltered,\r\n nightscoutBg.xDrip_age_adjusted_raw_value,\r\n nightscoutBg.xDrip_raw != 0 ? nightscoutBg.xDrip_filtered * 1000 : nightscoutBg.filtered,\r\n nightscoutBg.date, \r\n nightscoutBg.xDrip_calculated_value != 0 ? nightscoutBg.xDrip_calculated_value : nightscoutBg.sgv,\r\n nightscoutBg.xDrip_calculated_current_slope,\r\n nightscoutBg.xDrip_hide_slope,\r\n nightscoutBg.xDrip_filtered_calculated_value);\r\n \r\n lastInserted = nightscoutBg.date;\r\n }\r\n \r\n Log.e(TAG, \"readBgData finished with BgReading.create \");\r\n if(nightscoutBgs.size() > 0) {\r\n // Call the notification service only if we have new data...\r\n mContext.startService(new Intent(mContext, Notifications.class));\r\n }\r\n }\r\n \r\n static public boolean isxDripViewerMode(Context context) {\r\n return (context.getPackageName().equals(\"com.eveningoutpost.dexdrip\")) ? false : true;\r\n }\r\n \r\n public static boolean isxDripViewerConfigured(Context ctx) {\r\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);\r\n String recieversIpAddresses = prefs.getString(\"xdrip_viewer_ns_addresses\", \"\");\r\n if(recieversIpAddresses == null || recieversIpAddresses.equals(\"\") ||\r\n recieversIpAddresses.equals(ctx.getString(R.string.xdrip_viewer_ns_example))) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n \r\n // This function checkes if we are looking at a nightscout site that is being uploaded by dexcom.\r\n // In this case, we will not see sensors, and we need to create one.\r\n // We identify such a mod by the fact that there are no sensors, and by the fact that on this bg,\r\n // we see device == dexcom\r\n // We make sure that all decisions will be cached.\r\n \r\n public static boolean isNightScoutMode(Context context) {\r\n if (isNightScoutMode != null) {\r\n Log.e(TAG, \"IsNightScoutMode returning \" + isNightScoutMode); //???\r\n return isNightScoutMode;\r\n }\r\n if(!isxDripViewerMode(context)) {\r\n return false;\r\n }\r\n Sensor sensor = Sensor.last();\r\n if(sensor == null) {\r\n return false;\r\n }\r\n isNightScoutMode = new Boolean( sensor.uuid.equals(NIGHTSCOUT_SENSOR_UUID));\r\n Log.e(TAG, \"IsNightScoutMode = \" + isNightScoutMode);\r\n return isNightScoutMode;\r\n }\r\n \r\n private static void verifyViewerNightscoutMode(Context context, NightscoutBg nightscoutBg) {\r\n verifyViewerNightscoutModeSensor(nightscoutBg.device);\r\n if(!isNightScoutMode(context)) {\r\n return;\r\n }\r\n // There are some fields that we might be missing, fix that\r\n if(nightscoutBg.unfiltered == 0 ) {\r\n nightscoutBg.unfiltered = nightscoutBg.sgv;\r\n }\r\n if(nightscoutBg.filtered == 0 ) {\r\n nightscoutBg.filtered = nightscoutBg.sgv;\r\n }\r\n \r\n Pair<Double, Boolean> slopePair = BgReading.slopefromName(nightscoutBg.direction);\r\n\r\n nightscoutBg.xDrip_calculated_current_slope = slopePair.first;\r\n nightscoutBg.xDrip_hide_slope = slopePair.second;\r\n }\r\n \r\n private static void verifyViewerNightscoutMode(Context context, NightscoutMbg nightscoutMbg ) {\r\n verifyViewerNightscoutModeSensor(nightscoutMbg.device);\r\n if(!isNightScoutMode(context)) {\r\n return;\r\n }\r\n // There are some fields that we might be missing, fix that\r\n nightscoutMbg.xDrip_sensor_uuid = NIGHTSCOUT_SENSOR_UUID;\r\n \r\n }\r\n \r\n \r\n private static void verifyViewerNightscoutModeSensor(String device) {\r\n if(sensor_exists != null) {\r\n // We already have a cached sensor, no need to continue.\r\n return;\r\n }\r\n sensor_exists = Sensor.last();\r\n if(sensor_exists != null) {\r\n // We already have a sensor, no need to continue.\r\n return;\r\n }\r\n \r\n if(device == null) {\r\n return;\r\n }\r\n if(!device.equals(\"dexcom\")) {\r\n return;\r\n }\r\n // No sensor exists, uploader is dexcom, let's create one.\r\n Log.e(TAG, \"verifyViewerNightscoutModeSensor creating nightscout sensor\");\r\n Sensor.create(new Date().getTime(), NIGHTSCOUT_SENSOR_UUID);\r\n isNightScoutMode = new Boolean(true);\r\n }\r\n \r\n \r\n/*\r\n * curl examples\r\n * curl -X GET --header \"Accept: application/json api-secret: 6aaafe81264eb79d079caa91bbf25dba379ff6e2\" \"https://snirdar.azurewebsites.net/api/v1/entries/cal?count=122\" -k\r\n * curl -X GET --header \"Accept: application/json api-secret: 6aaafe81264eb79d079caa91bbf25dba379ff6e2\" \"https://snirdar.azurewebsites.net/api/v1/entries.json?find%5Btype%5D%5B%24eq%5D=cal&count=1\" -k \r\n * \r\n * \r\n *\r\n */\r\n}\r", "public class BgReadingTable extends ListActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {\n private String menu_name = \"BG Data Table\";\n private NavigationDrawerFragment mNavigationDrawerFragment;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.raw_data_list);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);\n mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), menu_name, this);\n\n getData();\n }\n\n @Override\n public void onNavigationDrawerItemSelected(int position) {\n mNavigationDrawerFragment.swapContext(position);\n }\n\n private void getData() {\n final List<BgReading> latest = BgReading.latest(5000);\n ListAdapter adapter = new BgReadingAdapter(this, latest);\n\n this.setListAdapter(adapter);\n }\n\n public static class BgReadingCursorAdapterViewHolder {\n TextView calculated_value;\n TextView filtered_calculated_value;\n TextView age_adjusted_raw_value;\n TextView raw_data;\n TextView raw_data_timestamp;\n\n public BgReadingCursorAdapterViewHolder(View root) {\n \tcalculated_value = (TextView) root.findViewById(R.id.calculated_value);\n \tfiltered_calculated_value = (TextView) root.findViewById(R.id.filtered_calculated_value);\n \tage_adjusted_raw_value = (TextView) root.findViewById(R.id.age_adjusted_raw_value);\n \traw_data = (TextView) root.findViewById(R.id.raw_data);\n raw_data_timestamp = (TextView) root.findViewById(R.id.raw_data_timestamp);\n }\n }\n\n public static class BgReadingAdapter extends BaseAdapter {\n private final Context context;\n private final List<BgReading> readings;\n\n public BgReadingAdapter(Context context, List<BgReading> readings) {\n this.context = context;\n if(readings == null)\n readings = new ArrayList<>();\n\n this.readings = readings;\n }\n\n public View newView(Context context, ViewGroup parent) {\n final View view = LayoutInflater.from(context).inflate(R.layout.bg_table_list_item, parent, false);\n\n final BgReadingCursorAdapterViewHolder holder = new BgReadingCursorAdapterViewHolder(view);\n view.setTag(holder);\n\n return view;\n }\n\n public void bindView(View view, final Context context, final BgReading bgReading) {\n final BgReadingCursorAdapterViewHolder tag = (BgReadingCursorAdapterViewHolder) view.getTag();\n tag.calculated_value.setText(Double.toString(bgReading.calculated_value));\n tag.filtered_calculated_value.setText(Double.toString(bgReading.filtered_calculated_value));\n tag.age_adjusted_raw_value.setText(Double.toString(bgReading.age_adjusted_raw_value));\n tag.raw_data.setText(Double.toString(bgReading.raw_data));\n tag.raw_data_timestamp.setText(new Date(bgReading.timestamp).toString());\n view.setLongClickable(true);\n view.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n switch (which){\n case DialogInterface.BUTTON_POSITIVE:\n bgReading.ignoreForStats = true;\n bgReading.save();\n break;\n\n case DialogInterface.BUTTON_NEGATIVE:\n bgReading.ignoreForStats = false;\n bgReading.save();\n break;\n }\n }\n };\n\n AlertDialog.Builder builder = new AlertDialog.Builder(context);\n builder.setMessage(\"Flag reading as \\\"bad\\\".\\nFlagged readings have no impact on the statistics.\").setPositiveButton(\"Yes\", dialogClickListener)\n .setNegativeButton(\"No\", dialogClickListener).show();\n return true;\n }\n });\n }\n\n @Override\n public int getCount() {\n return readings.size();\n }\n\n @Override\n public BgReading getItem(int position) {\n return readings.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return getItem(position).getId();\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (convertView == null)\n convertView = newView(context, parent);\n\n bindView(convertView, context, getItem(position));\n return convertView;\n }\n }\n}", "public class CollectionServiceStarter {\n private Context mContext;\n\n private final static String TAG = CollectionServiceStarter.class.getSimpleName();\n\n\n public static boolean isWifiandBTWixel(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"WifiBlueToothWixel\") == 0) {\n return true;\n }\n return false;\n }\n \n private static boolean isWifiandBTWixel(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n return collection_method.equals(\"WifiBlueToothWixel\"); \n }\n\n \n public static boolean isWifiandDexbridgeWixel(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"WifiDexbridgeWixel\") == 0) {\n return true;\n }\n return false;\n }\n \n private static boolean isWifiandDexbridgeWixel(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n return collection_method.equals(\"WifiDexbridgeWixel\"); \n }\n\n \n \n \n public static boolean isBTWixel(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"BluetoothWixel\") == 0 || isLimitter(context)) {\n return true;\n }\n return false;\n }\n\n /*\n * LimiTTer emulates a BT-Wixel and works with the BT-Wixel service.\n * It would work without any changes but in some cases knowing that the data does not\n * come from a Dexcom sensor but from a Libre sensor might enhance the performance.\n * */\n\n public static boolean isLimitter(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"LimiTTer\") == 0) {\n return true;\n }\n return false;\n }\n\n private static boolean isBTWixel(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n //LimiTTer hardware emulates BTWixel packages\n return collection_method.equals(\"BluetoothWixel\")||collection_method.equals(\"LimiTTer\");\n }\n \n // returns true if this DexBridge or DexBrige + wifi togeather.\n public static boolean isBteWixelorWifiandBtWixel(Context context) {\n return isBTWixel(context) || isWifiandBTWixel(context);\n }\n\n // returns true if this DexBridge or DexBrige + wifi togeather.\n public static boolean isDexbridgeWixelorWifiandDexbridgeWixel(Context context) {\n return isDexbridgeWixel(context) || isWifiandDexbridgeWixel(context);\n }\n \n private static boolean isDexbridgeWixel(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"DexbridgeWixel\") == 0) {\n return true;\n }\n return false;\n }\n \n private static boolean isDexbridgeWixel(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n return collection_method.equals(\"DexbridgeWixel\"); \n }\n\n public static boolean isBTShare(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"DexcomShare\") == 0) {\n return true;\n }\n return false;\n }\n public static boolean isBTShare(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n return collection_method.equals(\"DexcomShare\"); \n }\n\n public static boolean isBTG5(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return false;\n }\n return collection_method.equals(\"DexcomG5\");\n }\n\n\n public static boolean isBTG5(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"DexcomG5\") == 0) {\n return true;\n }\n return false;\n }\n\n public static boolean isWifiWixel(Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return true;\n }\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n if(collection_method.compareTo(\"WifiWixel\") == 0) {\n return true;\n }\n return false;\n }\n public static boolean isWifiWixel(String collection_method, Context context) {\n if(XDripViewer.isxDripViewerMode(context)) {\n return true;\n }\n return collection_method.equals(\"WifiWixel\"); \n }\n\n public static void newStart(Context context) {\n CollectionServiceStarter collectionServiceStarter = new CollectionServiceStarter(context);\n collectionServiceStarter.start(context);\n }\n\n public void start(Context context, String collection_method) {\n mContext = context;\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if(isBTWixel(collection_method, context)||isDexbridgeWixel(collection_method, context)) {\n Log.d(\"DexDrip\", \"Starting bt wixel collector\");\n stopWifWixelThread();\n stopBtShareService();\n stopG5ShareService();\n startBtWixelService();\n } else if(isWifiWixel(collection_method, context)){\n Log.d(\"DexDrip\", \"Starting wifi wixel collector\");\n stopBtWixelService();\n stopBtShareService();\n stopG5ShareService();\n startWifWixelThread();\n } else if(isBTShare(collection_method, context)) {\n Log.d(\"DexDrip\", \"Starting bt share collector\");\n stopBtWixelService();\n stopWifWixelThread();\n stopG5ShareService();\n startBtShareService();\n } else if(isBTG5(collection_method, context)) {\n Log.d(\"DexDrip\", \"Starting G5 share collector\");\n stopBtWixelService();\n stopWifWixelThread();\n stopBtShareService();\n startBtG5Service();\n } else if (isWifiandBTWixel(collection_method, context) || isWifiandDexbridgeWixel(collection_method, context)) {\n Log.d(\"DexDrip\", \"Starting wifi and bt wixel collector\");\n stopBtWixelService();\n stopWifWixelThread();\n stopBtShareService();\n stopG5ShareService();\n // start both\n Log.d(\"DexDrip\", \"Starting wifi wixel collector first\");\n startWifWixelThread();\n Log.d(\"DexDrip\", \"Starting bt wixel collector second\");\n startBtWixelService();\n Log.d(\"DexDrip\", \"Started wifi and bt wixel collector\");\n }\n if(prefs.getBoolean(\"broadcast_to_pebble\", false)){\n startPebbleSyncService();\n }\n startSyncService();\n startDailyIntentService();\n Log.d(TAG, collection_method);\n\n // Start logging to logcat\n if(prefs.getBoolean(\"store_logs\",false)) {\n String filePath = Environment.getExternalStorageDirectory() + \"/xdriplogcat.txt\";\n try {\n String[] cmd = {\"/system/bin/sh\", \"-c\", \"ps | grep logcat || logcat -f \" + filePath +\n \" -v threadtime AlertPlayer:V com.eveningoutpost.dexdrip.Services.WixelReader:V *:E \"};\n Runtime.getRuntime().exec(cmd);\n } catch (IOException e2) {\n Log.e(TAG, \"running logcat failed, is the device rooted?\", e2);\n }\n }\n\n }\n\n public void start(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String collection_method = prefs.getString(\"dex_collection_method\", \"BluetoothWixel\");\n\n start(context, collection_method);\n }\n\n public CollectionServiceStarter(Context context) {\n mContext = context;\n }\n\n public static void restartCollectionService(Context context) {\n CollectionServiceStarter collectionServiceStarter = new CollectionServiceStarter(context);\n collectionServiceStarter.stopBtShareService();\n collectionServiceStarter.stopBtWixelService();\n collectionServiceStarter.stopWifWixelThread();\n collectionServiceStarter.stopG5ShareService();\n collectionServiceStarter.start(context);\n }\n\n public static void restartCollectionService(Context context, String collection_method) {\n CollectionServiceStarter collectionServiceStarter = new CollectionServiceStarter(context);\n collectionServiceStarter.stopBtShareService();\n collectionServiceStarter.stopBtWixelService();\n collectionServiceStarter.stopWifWixelThread();\n collectionServiceStarter.stopG5ShareService();\n collectionServiceStarter.start(context, collection_method);\n }\n\n private void startBtWixelService() {\n Log.d(TAG, \"starting bt wixel service\");\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {\n mContext.startService(new Intent(mContext, DexCollectionService.class));\n \t}\n }\n private void stopBtWixelService() {\n Log.d(TAG, \"stopping bt wixel service\");\n mContext.stopService(new Intent(mContext, DexCollectionService.class));\n }\n\n private void startBtShareService() {\n Log.d(TAG, \"starting bt share service\");\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {\n mContext.startService(new Intent(mContext, DexShareCollectionService.class));\n }\n }\n\n private void startBtG5Service() {\n Log.d(TAG, \"starting G5 share service\");\n //if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {\n mContext.startService(new Intent(mContext, G5CollectionService.class));\n //}\n }\n\n private void startPebbleSyncService() {\n Log.d(TAG, \"starting PebbleSync service\");\n mContext.startService(new Intent(mContext, PebbleSync.class));\n }\n private void startSyncService() {\n Log.d(TAG, \"starting Sync service\");\n mContext.startService(new Intent(mContext, SyncService.class));\n }\n private void startDailyIntentService() {\n Calendar calendar = Calendar.getInstance();\n calendar.set(Calendar.HOUR_OF_DAY, 4);\n calendar.set(Calendar.MINUTE, 0);\n calendar.set(Calendar.SECOND, 0);\n\n PendingIntent pi = PendingIntent.getService(mContext, 0, new Intent(mContext, DailyIntentService.class),PendingIntent.FLAG_UPDATE_CURRENT);\n AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);\n am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);\n }\n private void stopBtShareService() {\n Log.d(TAG, \"stopping bt share service\");\n mContext.stopService(new Intent(mContext, DexShareCollectionService.class));\n }\n\n private void startWifWixelThread() {\n Log.d(TAG, \"starting wifi wixel service\");\n mContext.startService(new Intent(mContext, WifiCollectionService.class));\n }\n private void stopWifWixelThread() {\n Log.d(TAG, \"stopping wifi wixel service\");\n mContext.stopService(new Intent(mContext, WifiCollectionService.class));\n }\n\n private void stopG5ShareService() {\n Log.d(TAG, \"stopping G5 service\");\n mContext.stopService(new Intent(mContext, G5CollectionService.class));\n }\n\n\n}", "public class Preferences extends PreferenceActivity {\n private static final String TAG = \"PREFS\";\n private AllPrefsFragment preferenceFragment;\n\n\n private void refreshFragments() {\n preferenceFragment = new AllPrefsFragment();\n getFragmentManager().beginTransaction().replace(android.R.id.content,\n preferenceFragment).commit();\n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n if (scanResult == null || scanResult.getContents() == null) {\n return;\n }\n if (scanResult.getFormatName().equals(\"QR_CODE\")) {\n NSBarcodeConfig barcode = new NSBarcodeConfig(scanResult.getContents());\n if (barcode.hasMongoConfig()) {\n if (barcode.getMongoUri().isPresent()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"cloud_storage_mongodb_uri\", barcode.getMongoUri().get());\n editor.putString(\"cloud_storage_mongodb_collection\", barcode.getMongoCollection().or(\"entries\"));\n editor.putString(\"cloud_storage_mongodb_device_status_collection\", barcode.getMongoDeviceStatusCollection().or(\"devicestatus\"));\n editor.putBoolean(\"cloud_storage_mongodb_enable\", true);\n editor.apply();\n }\n if (barcode.hasApiConfig()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putBoolean(\"cloud_storage_api_enable\", true);\n editor.putString(\"cloud_storage_api_base\", Joiner.on(' ').join(barcode.getApiUris()));\n editor.apply();\n } else {\n prefs.edit().putBoolean(\"cloud_storage_api_enable\", false).apply();\n }\n }\n if (barcode.hasApiConfig()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putBoolean(\"cloud_storage_api_enable\", true);\n editor.putString(\"cloud_storage_api_base\", Joiner.on(' ').join(barcode.getApiUris()));\n editor.apply();\n } else {\n prefs.edit().putBoolean(\"cloud_storage_api_enable\", false).apply();\n }\n\n if (barcode.hasMqttConfig()) {\n if (barcode.getMqttUri().isPresent()) {\n URI uri = URI.create(barcode.getMqttUri().or(\"\"));\n if (uri.getUserInfo() != null) {\n String[] userInfo = uri.getUserInfo().split(\":\");\n if (userInfo.length == 2) {\n String endpoint = uri.getScheme() + \"://\" + uri.getHost() + \":\" + uri.getPort();\n if (userInfo[0].length() > 0 && userInfo[1].length() > 0) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"cloud_storage_mqtt_endpoint\", endpoint);\n editor.putString(\"cloud_storage_mqtt_user\", userInfo[0]);\n editor.putString(\"cloud_storage_mqtt_password\", userInfo[1]);\n editor.putBoolean(\"cloud_storage_mqtt_enable\", true);\n editor.apply();\n }\n }\n }\n }\n } else {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putBoolean(\"cloud_storage_mqtt_enable\", false);\n editor.apply();\n }\n } else if (scanResult.getFormatName().equals(\"CODE_128\")) {\n Log.d(TAG, \"Setting serial number to: \" + scanResult.getContents());\n prefs.edit().putString(\"share_key\", scanResult.getContents()).apply();\n }\n refreshFragments();\n }\n\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n preferenceFragment = new AllPrefsFragment();\n getFragmentManager().beginTransaction().replace(android.R.id.content,\n preferenceFragment).commit();\n }\n\n @Override\n protected void onPostCreate(Bundle savedInstanceState) {\n super.onPostCreate(savedInstanceState);\n// addPreferencesFromResource(R.xml.pref_general);\n\n }\n\n @Override\n protected boolean isValidFragment(String fragmentName) {\n if (AllPrefsFragment.class.getName().equals(fragmentName)){ return true; }\n return false;\n }\n\n @Override\n public boolean onIsMultiPane() {\n return isXLargeTablet(this);\n }\n private static boolean isXLargeTablet(Context context) {\n return (context.getResources().getConfiguration().screenLayout\n & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;\n }\n\n @Override\n public void onBuildHeaders(List<Header> target) {\n loadHeadersFromResource(R.xml.pref_headers, target);\n }\n\n private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object value) {\n String stringValue = value.toString();\n if (preference instanceof ListPreference) {\n ListPreference listPreference = (ListPreference) preference;\n int index = listPreference.findIndexOfValue(stringValue);\n preference.setSummary(\n index >= 0\n ? listPreference.getEntries()[index]\n : null);\n\n } else if (preference instanceof RingtonePreference) {\n // For ringtone preferences, look up the correct display value\n // using RingtoneManager.\n if (TextUtils.isEmpty(stringValue)) {\n // Empty values correspond to 'silent' (no ringtone).\n preference.setSummary(R.string.pref_ringtone_silent);\n\n } else {\n Ringtone ringtone = RingtoneManager.getRingtone(\n preference.getContext(), Uri.parse(stringValue));\n\n if (ringtone == null) {\n // Clear the summary if there was a lookup error.\n preference.setSummary(null);\n } else {\n // Set the summary to reflect the new ringtone display\n // name.\n String name = ringtone.getTitle(preference.getContext());\n preference.setSummary(name);\n }\n }\n\n } else {\n // For all other preferences, set the summary to the value's\n // simple string representation.\n preference.setSummary(stringValue);\n }\n return true;\n }\n };\n private static Preference.OnPreferenceChangeListener sBindNumericPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object value) {\n String stringValue = value.toString();\n if (isNumeric(stringValue)) {\n preference.setSummary(stringValue);\n return true;\n }\n return false;\n }\n };\n\n private static void bindPreferenceSummaryToValue(Preference preference) {\n preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);\n sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,\n PreferenceManager\n .getDefaultSharedPreferences(preference.getContext())\n .getString(preference.getKey(), \"\"));\n }\n private static void bindPreferenceSummaryToValueAndEnsureNumeric(Preference preference) {\n preference.setOnPreferenceChangeListener(sBindNumericPreferenceSummaryToValueListener);\n sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,\n PreferenceManager\n .getDefaultSharedPreferences(preference.getContext())\n .getString(preference.getKey(), \"\"));\n }\n\n\n // This class is used by android, so it must stay public although this will compile when it is private.\n public static class AllPrefsFragment extends PreferenceFragment {\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());\n\n DecimalFormat df;\n addPreferencesFromResource(R.xml.pref_license);\n addPreferencesFromResource(R.xml.pref_general);\n final EditTextPreference highValue = (EditTextPreference)findPreference(\"highValue\");\n bindPreferenceSummaryToValueAndEnsureNumeric(highValue);\n final EditTextPreference lowValue = (EditTextPreference)findPreference(\"lowValue\");\n bindPreferenceSummaryToValueAndEnsureNumeric(lowValue);\n final ListPreference units = (ListPreference) findPreference(\"units\");\n\n bindPreferenceSummaryToValue(units);\n\n addPreferencesFromResource(R.xml.pref_notifications);\n bindPreferenceSummaryToValue(findPreference(\"bg_alert_profile\"));\n bindPreferenceSummaryToValue(findPreference(\"calibration_notification_sound\"));\n bindPreferenceSummaryToValueAndEnsureNumeric(findPreference(\"calibration_snooze\"));\n bindPreferenceSummaryToValueAndEnsureNumeric(findPreference(\"bg_unclear_readings_minutes\"));\n bindPreferenceSummaryToValueAndEnsureNumeric(findPreference(\"disable_alerts_stale_data_minutes\"));\n bindPreferenceSummaryToValue(findPreference(\"falling_bg_val\"));\n bindPreferenceSummaryToValue(findPreference(\"rising_bg_val\"));\n bindPreferenceSummaryToValue(findPreference(\"other_alerts_sound\"));\n bindPreferenceSummaryToValueAndEnsureNumeric(findPreference(\"other_alerts_snooze\"));\n\n addPreferencesFromResource(R.xml.pref_data_source);\n\n\n addPreferencesFromResource(R.xml.pref_data_sync);\n setupBarcodeConfigScanner();\n setupBarcodeShareScanner();\n bindPreferenceSummaryToValue(findPreference(\"cloud_storage_mongodb_uri\"));\n bindPreferenceSummaryToValue(findPreference(\"cloud_storage_mongodb_collection\"));\n bindPreferenceSummaryToValue(findPreference(\"cloud_storage_mongodb_device_status_collection\"));\n bindPreferenceSummaryToValue(findPreference(\"cloud_storage_api_base\"));\n\n addPreferencesFromResource(R.xml.pref_advanced_settings);\n //addPreferencesFromResource(R.xml.pref_pebble_settings);\n addPreferencesFromResource(R.xml.pref_community_help);\n\n bindTTSListener();\n bindBgMissedAlertsListener();\n final Preference collectionMethod = findPreference(\"dex_collection_method\");\n final Preference displayBridgeBatt = findPreference(\"display_bridge_battery\");\n final Preference runInForeground = findPreference(\"run_service_in_foreground\");\n final Preference scanConstantly = findPreference(\"run_ble_scan_constantly\");\n final Preference runOnMain = findPreference(\"run_G5_ble_tasks_on_uithread\");\n final Preference reAuth = findPreference(\"always_get_new_keys\");\n final Preference reBond = findPreference(\"always_unbond_G5\");\n final Preference wifiRecievers = findPreference(\"wifi_recievers_addresses\");\n final Preference xDripViewerNsAdresses = findPreference(\"xdrip_viewer_ns_addresses\");\n final Preference predictiveBG = findPreference(\"predictive_bg\");\n final Preference interpretRaw = findPreference(\"interpret_raw\");\n\n final Preference shareKey = findPreference(\"share_key\");\n shareKey.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {\n @Override\n public boolean onPreferenceClick(Preference preference) {\n prefs.edit().remove(\"dexcom_share_session_id\").apply();\n return true;\n }\n });\n\n Preference.OnPreferenceChangeListener shareTokenResettingListener = new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n prefs.edit().remove(\"dexcom_share_session_id\").apply();\n return true;\n }\n };\n\n final Preference sharePassword = findPreference(\"dexcom_account_password\");\n sharePassword.setOnPreferenceChangeListener(shareTokenResettingListener);\n final Preference shareAccountName = findPreference(\"dexcom_account_name\");\n shareAccountName.setOnPreferenceChangeListener(shareTokenResettingListener);\n\n final Preference scanShare = findPreference(\"scan_share2_barcode\");\n final EditTextPreference transmitterId = (EditTextPreference) findPreference(\"dex_txid\");\n final SwitchPreference pebbleSync = (SwitchPreference) findPreference(\"broadcast_to_pebble\");\n final Preference pebbleTrend = findPreference(\"pebble_display_trend\");\n final Preference pebbleHighLine = findPreference(\"pebble_high_line\");\n final Preference pebbleLowLine = findPreference(\"pebble_low_line\");\n final Preference pebbleTrendPeriod = findPreference(\"pebble_trend_period\");\n final Preference pebbleDelta = findPreference(\"pebble_show_delta\");\n final Preference pebbleDeltaUnits = findPreference(\"pebble_show_delta_units\");\n final Preference pebbleShowArrows = findPreference(\"pebble_show_arrows\");\n final EditTextPreference pebbleSpecialValue = (EditTextPreference) findPreference(\"pebble_special_value\");\n bindPreferenceSummaryToValueAndEnsureNumeric(pebbleSpecialValue);\n final Preference pebbleSpecialText = findPreference(\"pebble_special_text\");\n bindPreferenceSummaryToValue(pebbleSpecialText);\n final SwitchPreference broadcastLocally = (SwitchPreference) findPreference(\"broadcast_data_through_intents\");\n final PreferenceCategory watchCategory = (PreferenceCategory) findPreference(\"watch_integration\");\n final PreferenceCategory collectionCategory = (PreferenceCategory) findPreference(\"collection_category\");\n final PreferenceCategory otherCategory = (PreferenceCategory) findPreference(\"other_category\");\n final PreferenceScreen calibrationAlertsScreen = (PreferenceScreen) findPreference(\"calibration_alerts_screen\");\n final PreferenceCategory alertsCategory = (PreferenceCategory) findPreference(\"alerts_category\");\n final Preference disableAlertsStaleDataMinutes = findPreference(\"disable_alerts_stale_data_minutes\");\n\n disableAlertsStaleDataMinutes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n if (!isNumeric(newValue.toString())) {\n return false;\n }\n if ((Integer.parseInt(newValue.toString())) < 10 ) {\n Toast.makeText(preference.getContext(),\n \"Value must be at least 10 minutes\", Toast.LENGTH_LONG).show();\n return false;\n }\n preference.setSummary(newValue.toString());\n return true;\n }\n });\n Log.d(TAG, prefs.getString(\"dex_collection_method\", \"BluetoothWixel\"));\n if(prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"DexcomShare\") != 0) {\n collectionCategory.removePreference(shareKey);\n collectionCategory.removePreference(scanShare);\n otherCategory.removePreference(interpretRaw);\n alertsCategory.addPreference(calibrationAlertsScreen);\n } else {\n otherCategory.removePreference(predictiveBG);\n alertsCategory.removePreference(calibrationAlertsScreen);\n prefs.edit().putBoolean(\"calibration_notifications\", false).apply();\n }\n\n if ((prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"WifiWixel\") != 0)\n && (prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"WifiBlueToothWixel\") != 0)\n && (prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"WifiDexbridgeWixel\") != 0)) {\n String receiversIpAddresses;\n receiversIpAddresses = prefs.getString(\"wifi_recievers_addresses\", \"\");\n // only hide if non wifi wixel mode and value not previously set to cope with\n // dynamic mode changes. jamorham\n if (receiversIpAddresses == null || receiversIpAddresses.equals(\"\")) {\n collectionCategory.removePreference(wifiRecievers);\n }\n }\n\n if(prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"DexbridgeWixel\") != 0) {\n collectionCategory.removePreference(transmitterId);\n collectionCategory.removePreference(displayBridgeBatt);\n }\n\n if(prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"DexcomG5\") == 0) {\n collectionCategory.addPreference(transmitterId);\n }\n\n if(prefs.getString(\"units\", \"mgdl\").compareTo(\"mmol\")!=0) {\n df = new DecimalFormat(\"#.#\");\n df.setMaximumFractionDigits(0);\n pebbleSpecialValue.setDefaultValue(\"99\");\n if(pebbleSpecialValue.getText().compareTo(\"5.5\")==0) {\n pebbleSpecialValue.setText(df.format(Double.valueOf(pebbleSpecialValue.getText()) * Constants.MMOLL_TO_MGDL));\n }\n }else{\n df = new DecimalFormat(\"#.#\");\n df.setMaximumFractionDigits(1);\n pebbleSpecialValue.setDefaultValue(\"5.5\");\n if(pebbleSpecialValue.getText().compareTo(\"99\") ==0) {\n pebbleSpecialValue.setText(df.format(Double.valueOf(pebbleSpecialValue.getText()) / Constants.MMOLL_TO_MGDL));\n }\n }\n units.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n //Context context = preference.getContext();\n DecimalFormat df = new DecimalFormat(\"#.#\");\n Double tmp = 0.0;\n Double highVal = 0.0;\n Double lowVal = 0.0;\n preference.setSummary(newValue.toString());\n if(newValue.toString().compareTo(\"mgdl\")==0) {\n df.setMaximumFractionDigits(0);\n pebbleSpecialValue.setDefaultValue(\"99\");\n tmp=Double.valueOf(pebbleSpecialValue.getText());\n tmp= tmp*Constants.MMOLL_TO_MGDL;\n highVal = Double.valueOf(highValue.getText());\n highVal = highVal*Constants.MMOLL_TO_MGDL;\n lowVal = Double.valueOf(lowValue.getText());\n lowVal = lowVal*Constants.MMOLL_TO_MGDL;\n } else {\n df.setMaximumFractionDigits(1);\n pebbleSpecialValue.setDefaultValue(\"5.5\");\n tmp=Double.valueOf(pebbleSpecialValue.getText());\n tmp= tmp/Constants.MMOLL_TO_MGDL;\n highVal = Double.valueOf(highValue.getText());\n highVal = highVal/Constants.MMOLL_TO_MGDL;\n lowVal = Double.valueOf(lowValue.getText());\n lowVal = lowVal/Constants.MMOLL_TO_MGDL;\n }\n pebbleSpecialValue.setText(df.format(tmp));\n pebbleSpecialValue.setSummary(pebbleSpecialValue.getText());\n highValue.setText(df.format(highVal));\n highValue.setSummary(highValue.getText());\n lowValue.setText(df.format(lowVal));\n lowValue.setSummary(lowValue.getText());\n return true;\n }\n });\n pebbleSync.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n Context context = preference.getContext();\n if ((Boolean) newValue) {\n context.startService(new Intent(context, PebbleSync.class));\n } else {\n context.stopService(new Intent(context, PebbleSync.class));\n }\n return true;\n }\n });\n\n //bindWidgetUpdater();\n\n pebbleTrend.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n pebbleHighLine.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n\n pebbleLowLine.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n\n pebbleTrendPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n pebbleDelta.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n pebbleDeltaUnits.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n pebbleShowArrows.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue){\n Context context = preference.getContext();\n context.startService(new Intent(context, PebbleSync.class));\n return true;\n }\n });\n bindWidgetUpdater();\n\n bindPreferenceSummaryToValue(collectionMethod);\n bindPreferenceSummaryToValue(shareKey);\n bindPreferenceSummaryToValue(wifiRecievers);\n bindPreferenceSummaryToValue(xDripViewerNsAdresses);\n bindPreferenceSummaryToValue(transmitterId);\n\n if(prefs.getString(\"dex_collection_method\", \"BluetoothWixel\").compareTo(\"DexcomG5\") == 0) {\n // Transmitter Id max length is 6.\n transmitterId.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(6), new InputFilter.AllCaps()});\n }\n else {\n transmitterId.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(10), new InputFilter.AllCaps()});\n collectionCategory.removePreference(scanConstantly);\n collectionCategory.removePreference(reAuth);\n collectionCategory.removePreference(reBond);\n collectionCategory.removePreference(runOnMain);\n }\n\n // Allows enter to confirm for transmitterId.\n transmitterId.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n transmitterId.onClick(transmitterId.getDialog(), Dialog.BUTTON_POSITIVE);\n transmitterId.getDialog().dismiss();\n return true;\n }\n return false;\n }\n });\n\n collectionMethod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n if (((String) newValue).compareTo(\"DexcomShare\") != 0) { // NOT USING SHARE\n collectionCategory.removePreference(shareKey);\n collectionCategory.removePreference(scanShare);\n otherCategory.removePreference(interpretRaw);\n otherCategory.addPreference(predictiveBG);\n alertsCategory.addPreference(calibrationAlertsScreen);\n } else {\n collectionCategory.addPreference(shareKey);\n collectionCategory.addPreference(scanShare);\n otherCategory.addPreference(interpretRaw);\n otherCategory.removePreference(predictiveBG);\n alertsCategory.removePreference(calibrationAlertsScreen);\n prefs.edit().putBoolean(\"calibration_notifications\", false).apply();\n }\n\n if (((String) newValue).compareTo(\"BluetoothWixel\") != 0\n && ((String) newValue).compareTo(\"DexcomShare\") != 0\n && ((String) newValue).compareTo(\"DexbridgeWixel\") != 0\n && ((String) newValue).compareTo(\"WifiBlueToothWixel\") != 0\n && ((String) newValue).compareTo(\"WifiDexbridgeWixel\") != 0\n && ((String) newValue).compareTo(\"DexcomG5\") != 0\n && ((String) newValue).compareTo(\"LimiTTer\") != 0){\n collectionCategory.removePreference(runInForeground);\n } else {\n collectionCategory.addPreference(runInForeground);\n }\n\n // jamorham always show wifi receivers option if populated as we may switch modes dynamically\n if ((((String) newValue).compareTo(\"WifiWixel\") != 0)\n && (((String) newValue).compareTo(\"WifiBlueToothWixel\") != 0)\n && (((String) newValue).compareTo(\"WifiDexbridgeWixel\") != 0)) {\n String receiversIpAddresses;\n receiversIpAddresses = prefs.getString(\"wifi_recievers_addresses\", \"\");\n if (receiversIpAddresses == null || receiversIpAddresses.equals(\"\")) {\n collectionCategory.removePreference(wifiRecievers);\n } else {\n collectionCategory.addPreference(wifiRecievers);\n }\n } else {\n collectionCategory.addPreference(wifiRecievers);\n }\n\n if (((String) newValue).compareTo(\"DexbridgeWixel\") != 0) {\n collectionCategory.removePreference(transmitterId);\n collectionCategory.removePreference(displayBridgeBatt);\n } else {\n collectionCategory.addPreference(transmitterId);\n collectionCategory.addPreference(displayBridgeBatt);\n }\n\n if (((String) newValue).compareTo(\"DexcomG5\") == 0) {\n collectionCategory.addPreference(transmitterId);\n collectionCategory.addPreference(scanConstantly);\n collectionCategory.addPreference(reAuth);\n collectionCategory.addPreference(reBond);\n collectionCategory.addPreference(runOnMain);\n\n\n } else {\n collectionCategory.removePreference(transmitterId);\n collectionCategory.removePreference(scanConstantly);\n collectionCategory.removePreference(reAuth);\n collectionCategory.removePreference(reBond);\n collectionCategory.removePreference(runOnMain);\n\n }\n\n String stringValue = newValue.toString();\n if (preference instanceof ListPreference) {\n ListPreference listPreference = (ListPreference) preference;\n int index = listPreference.findIndexOfValue(stringValue);\n preference.setSummary(\n index >= 0\n ? listPreference.getEntries()[index]\n : null);\n\n } else if (preference instanceof RingtonePreference) {\n if (TextUtils.isEmpty(stringValue)) {\n preference.setSummary(R.string.pref_ringtone_silent);\n\n } else {\n Ringtone ringtone = RingtoneManager.getRingtone(\n preference.getContext(), Uri.parse(stringValue));\n if (ringtone == null) {\n preference.setSummary(null);\n } else {\n String name = ringtone.getTitle(preference.getContext());\n preference.setSummary(name);\n }\n }\n } else {\n preference.setSummary(stringValue);\n }\n if (preference.getKey().equals(\"dex_collection_method\")) {\n CollectionServiceStarter.restartCollectionService(preference.getContext(), (String) newValue);\n } else {\n CollectionServiceStarter.restartCollectionService(preference.getContext());\n }\n return true;\n }\n });\n \n // Remove all the parts that are not needed in xDripViewer (doing it all in one place to avoid having many ifs)\n if(XDripViewer.isxDripViewerMode(getActivity())) {\n collectionCategory.removePreference(collectionMethod);\n collectionCategory.removePreference(shareKey);\n collectionCategory.removePreference(scanShare);\n collectionCategory.removePreference(wifiRecievers);\n collectionCategory.removePreference(transmitterId);\n collectionCategory.removePreference(displayBridgeBatt);\n \n final PreferenceCategory dataSyncCategory = (PreferenceCategory) findPreference(\"dataSync\");\n final Preference autoConfigure = findPreference(\"auto_configure\");\n final Preference cloudStorageMongo = findPreference(\"cloud_storage_mongo\");\n final Preference cloudStorageApi = findPreference(\"cloud_storage_api\");\n final Preference dexcomServerUploadScreen = findPreference(\"dexcom_server_upload_screen\");\n final Preference xDripViewerUploadMode = findPreference(\"xDripViewer_upload_mode\");\n \n dataSyncCategory.removePreference(autoConfigure);\n dataSyncCategory.removePreference(cloudStorageMongo);\n dataSyncCategory.removePreference(cloudStorageApi);\n dataSyncCategory.removePreference(dexcomServerUploadScreen);\n dataSyncCategory.removePreference(xDripViewerUploadMode);\n \n } else {\n collectionCategory.removePreference(xDripViewerNsAdresses);\n }\n }\n\n private void bindWidgetUpdater() {\n findPreference(\"widget_range_lines\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"extra_status_line\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"widget_status_line\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_calibration_long\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_calibration_short\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_avg\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_a1c_dcct\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_a1c_ifcc\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_in\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_high\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"status_line_low\").setOnPreferenceChangeListener(new WidgetListener());\n findPreference(\"extra_status_line\").setOnPreferenceChangeListener(new WidgetListener());\n }\n\n private void setupBarcodeConfigScanner() {\n findPreference(\"auto_configure\").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {\n @Override\n public boolean onPreferenceClick(Preference preference) {\n new AndroidBarcode(getActivity()).scan();\n return true;\n }\n });\n }\n\n\n private void setupBarcodeShareScanner() {\n findPreference(\"scan_share2_barcode\").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {\n @Override\n public boolean onPreferenceClick(Preference preference) {\n new AndroidBarcode(getActivity()).scan();\n return true;\n }\n });\n }\n\n private void bindTTSListener(){\n findPreference(\"bg_to_speech\").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n if ((Boolean)newValue) {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());\n alertDialog.setTitle(\"Install Text-To-Speech Data?\");\n alertDialog.setMessage(\"Install Text-To-Speech Data?\\n(After installation of languages you might have to press \\\"Restart Collector\\\" in System Status.)\");\n alertDialog.setCancelable(true);\n alertDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n BgToSpeech.installTTSData(getActivity());\n }\n });\n alertDialog.setNegativeButton(R.string.no, null);\n AlertDialog alert = alertDialog.create();\n alert.show();\n }\n return true;\n }\n });\n }\n\n private static Preference.OnPreferenceChangeListener sBgMissedAlertsHandler = new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n Context context = preference.getContext();\n context.startService(new Intent(context, MissedReadingService.class));\n return true;\n }\n };\n\n \n private void bindBgMissedAlertsListener(){\n findPreference(\"other_alerts_snooze\").setOnPreferenceChangeListener(sBgMissedAlertsHandler);\n findPreference(\"other_alerts_snooze\").setOnPreferenceChangeListener(sBgMissedAlertsHandler);\n }\n\n private static class WidgetListener implements Preference.OnPreferenceChangeListener {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n Context context = preference.getContext();\n if(AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, xDripWidget.class)).length > 0){\n context.startService(new Intent(context, WidgetUpdateService.class));\n }\n return true;\n }\n }\n }\n\n public static boolean isNumeric(String str) {\n try {\n Double.parseDouble(str);\n } catch(NumberFormatException nfe) {\n return false;\n }\n return true;\n }\n}" ]
import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.eveningoutpost.dexdrip.Models.BgReading; import com.eveningoutpost.dexdrip.Models.Calibration; import com.eveningoutpost.dexdrip.Models.Sensor; import com.eveningoutpost.dexdrip.Services.XDripViewer; import com.eveningoutpost.dexdrip.Tables.BgReadingTable; import com.eveningoutpost.dexdrip.Tables.CalibrationDataTable; import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter; import com.eveningoutpost.dexdrip.stats.StatsActivity; import com.eveningoutpost.dexdrip.utils.Preferences; import java.util.ArrayList; import java.util.Date; import java.util.List;
package com.eveningoutpost.dexdrip; /** * Created by stephenblack on 11/5/14. */ public class NavDrawerBuilder { public List<Calibration> last_two_calibrations = Calibration.latest(2); public List<BgReading> last_two_bgReadings = BgReading.latestUnCalculated(2); public List<BgReading> bGreadings_in_last_30_mins = BgReading.last30Minutes();
public boolean is_active_sensor = Sensor.isActive();
2
AlexisChevalier/CarRental-Android-Application
app/src/main/java/com/vehiclerental/activities/Staff/SearchVehicleActivity.java
[ "public interface CarRentalApiClient {\n /**\n * Return the list of available branches\n *\n * @return list of branches\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<BranchContract> getBranches() throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Return the result of the available vehicles with the given criteria\n *\n * @param contract search criteria\n * @return list of available vehicle results\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<BookingSearchResultContract> searchAvailableVehicles(SearchAvailableVehiclesRequestContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Create an user account with the given parameters\n *\n * @param contract account parameters\n * @return created account\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n UserContract createAccount(CreateAccountRequestContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Returns the current user account details\n *\n * @return user account details\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n UserContract getAccountDetails() throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Returns the bookings for the current user in the current branch\n *\n * @return list of bookings for the user and branch\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<BookingContract> getUserBookingsForBranch() throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Request a vehicle booking with the given criteria\n *\n * @param contract booking criteria\n * @return created booking\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n BookingContract bookVehicle(CreateBookingContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Returns all the bookings for the current branch\n *\n * @return the branch bookings list\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<BookingContract> getBranchBookings() throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Sends a shutdown request to the server\n *\n * @return nothing\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n Void shutdownSystem() throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Create an user account with the given parameters (requires staff level)\n *\n * @param contract the account parameters\n * @return the created account\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n UserContract createUser(CreateAccountRequestContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Create or update a vehicle with the given parameters in the current branch\n *\n * @param contract vehicle parameters\n * @return created or updated vehicle\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n VehicleContract createOrUpdateVehicle(CreateUpdateVehicleContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Search vehicles with the given criteria in the current branch\n *\n * @param contract search criteria\n * @return list of vehicles matching the criteria\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<VehicleContract> searchVehicles(SearchVehicleContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Search users with the given criteria (full text search on email and fullname)\n *\n * @param contract search criteria\n * @return list of users matching the criteria\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<UserContract> searchUser(SearchUserContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Update a booking status with the given parameters\n *\n * @param contract update parameters\n * @return updated booking\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n BookingContract changeBookingStatus(ChangeBookingStatusContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n\n /**\n * Returns the vehicle moves for the current branch matching the filter criteria\n *\n * @param contract filter criteria\n * @return list of bookings requiring moves\n * @throws ApiUnauthorizedException if the request wasn't authenticated or authorized\n * @throws ApiException if there was a general error during the request\n * @throws ApiInvalidParameterException if there was an error with a parameter\n * @throws ApiUnavailableException if the API is unavailable\n */\n List<BookingContract> getVehiclesMove(GetBranchVehicleMovesContract contract) throws ApiUnauthorizedException, ApiException, ApiInvalidParameterException, ApiUnavailableException;\n}", "public class CarRentalApiClientFactory {\n /**\n * Creates a new API client with the default IP and port values\n *\n * @return api client\n */\n public static CarRentalApiClient getApiClient() {\n return new CarRentalApiClientSocketImpl(\n PreferencesManager.getHeadOfficeIpAddress(CarRentalApplication.getAppContext()),\n PreferencesManager.getHeadOfficePort(CarRentalApplication.getAppContext()));\n }\n\n /**\n * Creates a new API client with the given IP and port values\n * @param ipAddress given ip address\n * @param port given port\n * @return api client\n */\n public static CarRentalApiClient getApiClient(String ipAddress, int port) {\n return new CarRentalApiClientSocketImpl(ipAddress, port);\n }\n}", "public class SearchVehicleContract {\n //If this isn't provided, the type id will be used\n public String registrationNumber;\n public int vehicleTypeId;\n}", "public class VehicleContract {\n public int id;\n public BranchContract branch;\n public int type;\n public int status;\n public String registrationNumber;\n public int doors;\n public int seats;\n public boolean automaticTransmission;\n public double poundsPerDay;\n public String name;\n}", "public class ActivityUtils {\n\n /**\n * This method will display an error message depending on which error has been thrown by the API\n *\n * @param context current context\n * @param apiException expression thrown by the API client\n */\n public static void HandleException(Context context, Exception apiException) {\n Toast toast;\n if (apiException instanceof ApiUnauthorizedException) {\n toast = Toast.makeText(context, R.string.error_invalid_account_credentials, Toast.LENGTH_SHORT);\n PreferencesManager.clearSession(context);\n } else if (apiException instanceof ApiInvalidParameterException) {\n toast = Toast.makeText(context, String.format(context.getString(R.string.ends_with_a_dot), apiException.getMessage()), Toast.LENGTH_SHORT);\n } else if (apiException instanceof ApiUnavailableException) {\n toast = Toast.makeText(context, R.string.error_server_not_available, Toast.LENGTH_SHORT);\n } else {\n toast = Toast.makeText(context, R.string.error_server_not_reachable, Toast.LENGTH_SHORT);\n }\n toast.show();\n }\n\n /**\n * This method will build the left drawer on the android application in every activity which calls it\n *\n * The drawer is composed of many different items, each of them executing a specific action when clicked\n *\n * @param activity the current activity\n */\n public static void buildDrawer(final AppCompatActivity activity) {\n BranchContract branchContract = PreferencesManager.getCurrentBranch(activity);\n String branchName = branchContract == null ? activity.getString(R.string.no_branch_selected) : branchContract.name;\n\n /* Login */\n PrimaryDrawerItem loginItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_perm_identity_black_24dp)\n .withName(R.string.login_register_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n PreferencesManager.clearSession(activity);\n Intent intent = new Intent(CarRentalApplication.getAppContext(), LoginActivity.class);\n //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* Change connection settings */\n PrimaryDrawerItem changeIpSettings = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_settings_black_24dp)\n .withName(R.string.change_server_settings_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), ChangeConnectionSettingsActivity.class);\n intent.putExtra(LoginActivity.COMES_FROM_LOGIN, false);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* Logout */\n PrimaryDrawerItem logoutItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_perm_identity_black_24dp)\n .withName(R.string.logout_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n PreferencesManager.clearSession(activity);\n Intent intent = new Intent(CarRentalApplication.getAppContext(), LoginActivity.class);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* Change Branch */\n PrimaryDrawerItem changeBranchItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_room_black_24dp)\n .withName(String.format(activity.getString(R.string.change_branch_menu_item), branchName))\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), ChooseBranchActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* Search Vehicle */\n PrimaryDrawerItem searchBookingItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_search_black_24dp)\n .withName(R.string.search_available_vehicles_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), SearchAvailableVehicleActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* USER: Show user bookings */\n PrimaryDrawerItem userBookings = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_view_list_black_24dp)\n .withName(R.string.user_bookings_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), UserBookingsActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* ADMIN: Search vehicle */\n PrimaryDrawerItem searchVehicleItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_search_black_24dp)\n .withName(R.string.search_vehcile_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), SearchVehicleActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* ADMIN: DO Client booking vehicle */\n PrimaryDrawerItem bookForClientItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_directions_car_black_24dp)\n .withName(R.string.make_client_booking_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), SearchAvailableVehicleActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* ADMIN: AddVehicle */\n PrimaryDrawerItem addVehicleItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_add_black_24dp)\n .withName(R.string.add_vehicle_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), CreateVehicleActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* ADMIN: Show branch bookings */\n PrimaryDrawerItem showBranchBookingsItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_view_list_black_24dp)\n .withName(R.string.view_branch_bookings_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), BranchBookingsActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* ADMIN: Show Moves */\n PrimaryDrawerItem showMovesItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_swap_horiz_black_24dp)\n .withName(R.string.view_branch_moves_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), ShowBranchMovesActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n /* ADMIN: sys admin */\n PrimaryDrawerItem sysAdminItem = new PrimaryDrawerItem()\n .withIcon(R.drawable.ic_power_settings_new_black_24dp)\n .withName(R.string.server_control_menu_item)\n .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {\n @Override\n public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {\n Intent intent = new Intent(CarRentalApplication.getAppContext(), SystemAdministrationActivity.class);\n activity.startActivity(intent);\n return true;\n }\n }\n );\n\n //Instantiate the builder\n DrawerBuilder drawerBuilder = new DrawerBuilder()\n .withActivity(activity)\n .withDisplayBelowStatusBar(false)\n .withTranslucentStatusBar(false)\n .withSelectedItem(-1);\n\n //Instantiate the header builder\n AccountHeaderBuilder headerBuilder = new AccountHeaderBuilder()\n .withActivity(activity)\n .withHeaderBackground(R.drawable.drawer_header)\n .withSelectionListEnabledForSingleProfile(false);\n\n //Finalize configuration, depending on user leverl\n if (PreferencesManager.isLoggedIn(activity)) {\n UserContract user = PreferencesManager.getLoggedUser(activity);\n\n if (PreferencesManager.isStaffUser(activity)) {\n //Staff drawer\n AccountHeader headerResult = headerBuilder\n .addProfiles(new ProfileDrawerItem()\n .withName(String.format(activity.getString(R.string.staff_user_label), user.fullName))\n .withEmail(user.emailAddress)\n .withIcon(R.drawable.icon))\n .build();\n\n drawerBuilder\n .withAccountHeader(headerResult)\n .addDrawerItems(logoutItem, changeBranchItem, searchVehicleItem, addVehicleItem, bookForClientItem, showBranchBookingsItem, showMovesItem, sysAdminItem, changeIpSettings);\n } else {\n //User drawer\n AccountHeader headerResult = headerBuilder\n .addProfiles(new ProfileDrawerItem()\n .withName(user.fullName)\n .withEmail(user.emailAddress)\n .withIcon(R.drawable.icon))\n .build();\n\n drawerBuilder\n .withAccountHeader(headerResult)\n .addDrawerItems(logoutItem, changeBranchItem, searchBookingItem, userBookings, changeIpSettings);\n }\n } else {\n //User drawer\n AccountHeader headerResult = headerBuilder\n .addProfiles(new ProfileDrawerItem()\n .withName(activity.getString(R.string.not_logged_in))\n .withIcon(R.drawable.icon))\n .build();\n\n drawerBuilder\n .withAccountHeader(headerResult)\n .addDrawerItems(loginItem, changeBranchItem, searchBookingItem, changeIpSettings);\n }\n\n //Build the drawer\n Drawer drawer = drawerBuilder.build();\n }\n}", "public class SerializationUtils {\n\n //Static gson object\n private static Gson gsonObject = new Gson();\n\n /**\n * Serialize the provided object to a json string\n *\n * @param object the object to serialize\n * @param <T> the generic object type\n * @return the serialized json string\n */\n public static <T> String serialize(T object) {\n return gsonObject.toJson(object);\n }\n\n /**\n * Deserialize the provided string into the given type\n *\n * @param serialized the serialized json string\n * @param type the expected object type\n * @param <T> the generic object type\n * @return the deserialized object\n */\n public static <T> T deserialize(String serialized, Type type) {\n return gsonObject.fromJson(serialized, type);\n }\n}", "public class StaticDataUtils {\n\n //Data structures to provide an easy access to the static data\n private static ArrayList<String> vehicleTypes;\n private static ArrayList<String> vehicleStatuses;\n private static Map<String, BranchContract> branchContractMap;\n\n /**\n * Registers all the available vehicle types in memory\n */\n private static void initializeVehicleTypes() {\n vehicleTypes = new ArrayList<>();\n vehicleTypes.add(0, CarRentalApplication.getAppContext().getString(R.string.small_car_type));\n vehicleTypes.add(1, CarRentalApplication.getAppContext().getString(R.string.family_car_type));\n vehicleTypes.add(2, CarRentalApplication.getAppContext().getString(R.string.small_van_type));\n vehicleTypes.add(3, CarRentalApplication.getAppContext().getString(R.string.large_van_type));\n }\n\n /**\n * Registers all the available vehicle status in memory\n */\n private static void initializeVehicleStatuses() {\n vehicleStatuses = new ArrayList<>();\n vehicleStatuses.add(0, CarRentalApplication.getAppContext().getString(R.string.available_status));\n vehicleStatuses.add(1, CarRentalApplication.getAppContext().getString(R.string.in_transit_status));\n vehicleStatuses.add(2, CarRentalApplication.getAppContext().getString(R.string.in_client_booking_status));\n vehicleStatuses.add(3, CarRentalApplication.getAppContext().getString(R.string.maintenance_status));\n }\n\n /**\n * Registers the branches in memory\n * We are using a hashmap, because the branches will be mapped through their name\n *\n * @param branches the branch list\n */\n public static void setBranches(List<BranchContract> branches) {\n branchContractMap = new HashMap<>();\n for (BranchContract branch : branches) {\n branchContractMap.put(branch.name, branch);\n }\n }\n\n /**\n * Returns the list of vehicle types, and initialize it if it has not been done yet\n *\n * @return the vehicle types list\n */\n public static ArrayList<String> getVehicleTypesList() {\n if (vehicleTypes == null) {\n initializeVehicleTypes();\n }\n\n return vehicleTypes;\n }\n\n /**\n * Returns the list of vehicle types as an array, and initialize it if it has not been done yet\n *\n * @return the vehicle types array\n */\n public static String[] getVehicleTypesArray() {\n return getVehicleTypesList().toArray(new String[getVehicleTypesList().size()]);\n }\n\n /**\n * Returns the list of vehicle statuses, and initialize it if it has not been done yet\n *\n * @return the vehicle statuses list\n */\n public static ArrayList<String> getVehicleStatusesList() {\n if (vehicleStatuses == null) {\n initializeVehicleStatuses();\n }\n\n return vehicleStatuses;\n }\n\n /**\n * Returns the list of vehicle statuses as an array, and initialize it if it has not been done yet\n *\n * @return the vehicle statuses array\n */\n public static String[] getVehicleStatusesArray() {\n return getVehicleStatusesList().toArray(new String[getVehicleStatusesList().size()]);\n }\n\n /**\n * Returns the array of the branch names\n *\n * @return the branch names arrays\n */\n public static String[] getBranchNamesArray() {\n return branchContractMap.keySet().toArray(new String[branchContractMap.size()]);\n }\n\n /**\n * Return the branch matching the given name\n *\n * @param name given branch name\n * @return the branch if it exists, null otherwise\n */\n public static BranchContract getBranchFromName(String name) {\n return branchContractMap.get(name);\n }\n}" ]
import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.vehiclerental.R; import com.vehiclerental.apiClient.CarRentalApiClient; import com.vehiclerental.apiClient.CarRentalApiClientFactory; import com.vehiclerental.contracts.SearchVehicleContract; import com.vehiclerental.contracts.VehicleContract; import com.vehiclerental.utils.ActivityUtils; import com.vehiclerental.utils.SerializationUtils; import com.vehiclerental.utils.StaticDataUtils; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife;
/** * CarRental * * This activity displays a form to search vehicles in the current branch either by registration number or type */ package com.vehiclerental.activities.Staff; public class SearchVehicleActivity extends AppCompatActivity { //public message passing keys public final static String VEHICLE_SEARCH_RESULTS_LIST_SERIALIZED_KEY = "vehicle_search_results_list_serialized"; public final static String SELECTED_VEHICLE_SERIALIZED_KEY = "selected_serialized"; //Automatic binding with Butterknife (external library) @Bind(R.id.vehicleTypePicker) protected Spinner vehicleTypePicker; @Bind(R.id.registrationNumberField) protected EditText registrationNumberField; @Bind(R.id.searchVehiclesButton) protected Button searchVehiclesButton; //private members private SearchVehicleContract searchVehicleContract;
private CarRentalApiClient apiClient = CarRentalApiClientFactory.getApiClient();
0
komamitsu/fluency
fluency-core/src/main/java/org/komamitsu/fluency/buffer/Buffer.java
[ "public class BufferFullException\n extends IOException\n{\n public BufferFullException(String s)\n {\n super(s);\n }\n}", "@JsonSerialize(using = EventTime.Serializer.class)\npublic class EventTime\n{\n private final long seconds;\n private final long nanoseconds;\n\n /**\n * Constructs an <code>EventTime</code>.\n *\n * @param seconds the epoch seconds. This should be a 32-bit value.\n * @param nanoseconds the nanoseconds. This should be a 32-bit value.\n */\n public EventTime(long seconds, long nanoseconds)\n {\n if (seconds >> 32 != 0) {\n throw new IllegalArgumentException(\"`seconds` should be a 32-bit value\");\n }\n\n if (nanoseconds >> 32 != 0) {\n throw new IllegalArgumentException(\"`nanoseconds` should be a 32-bit value\");\n }\n\n this.seconds = seconds;\n this.nanoseconds = nanoseconds;\n }\n\n /**\n * Constructs an <code>EventTime</code>.\n *\n * @param epochSeconds the epoch seconds. This should be a 32-bit value.\n */\n public static EventTime fromEpoch(long epochSeconds)\n {\n return new EventTime(epochSeconds, 0);\n }\n\n /**\n * Constructs an <code>EventTime</code>.\n *\n * @param epochSeconds the epoch seconds. This should be a 32-bit value.\n * @param nanoseconds the nanoseconds. This should be a 32-bit value.\n */\n public static EventTime fromEpoch(long epochSeconds, long nanoseconds)\n {\n return new EventTime(epochSeconds, nanoseconds);\n }\n\n /**\n * Constructs an <code>EventTime</code>.\n *\n * @param epochMillisecond the epoch milli seconds.\n * This should be a 32-bit value.\n */\n public static EventTime fromEpochMilli(long epochMillisecond)\n {\n return new EventTime(epochMillisecond / 1000, (epochMillisecond % 1000) * 1000000);\n }\n\n public long getSeconds()\n {\n return seconds;\n }\n\n public long getNanoseconds()\n {\n return nanoseconds;\n }\n\n /**\n * @deprecated As of release 1.9, replaced by {@link #getNanoseconds()}\n */\n @Deprecated\n public long getNanoSeconds()\n {\n return nanoseconds;\n }\n\n @Override\n public boolean equals(Object o)\n {\n if (this == o) {\n return true;\n }\n if (!(o instanceof EventTime)) {\n return false;\n }\n\n EventTime eventTime = (EventTime) o;\n\n if (seconds != eventTime.seconds) {\n return false;\n }\n return nanoseconds == eventTime.nanoseconds;\n }\n\n @Override\n public int hashCode()\n {\n int result = (int) (seconds ^ (seconds >>> 32));\n result = 31 * result + (int) (nanoseconds ^ (nanoseconds >>> 32));\n return result;\n }\n\n @Override\n public String toString()\n {\n return \"EventTime{\" +\n \"seconds=\" + seconds +\n \", nanoseconds=\" + nanoseconds +\n '}';\n }\n\n public static class Serializer\n extends StdSerializer<EventTime>\n {\n public Serializer()\n {\n super(EventTime.class);\n }\n\n protected Serializer(Class<EventTime> t)\n {\n super(t);\n }\n\n @Override\n public void serialize(EventTime value, JsonGenerator gen, SerializerProvider provider)\n throws IOException\n {\n if (!(gen instanceof MessagePackGenerator)) {\n throw new IllegalStateException(\"\" +\n \"This class should be serialized by MessagePackGenerator, but `gen` is \" + gen.getClass());\n }\n\n MessagePackGenerator messagePackGenerator = (MessagePackGenerator) gen;\n\n // https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#eventtime-ext-format\n //\n // +-------+----+----+----+----+----+----+----+----+----+\n // | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |\n // +-------+----+----+----+----+----+----+----+----+----+\n // | D7 | 00 | seconds from epoch| nanosecond |\n // +-------+----+----+----+----+----+----+----+----+----+\n // |fixext8|type| 32bits integer BE | 32bits integer BE |\n // +-------+----+----+----+----+----+----+----+----+----+\n ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.putInt((int) value.seconds).putInt((int) value.nanoseconds);\n messagePackGenerator.writeExtensionType(new MessagePackExtensionType((byte) 0x0, buffer.array()));\n }\n }\n}", "public interface Ingester\n extends Closeable\n{\n void ingest(String tag, ByteBuffer dataBuffer)\n throws IOException;\n\n Sender getSender();\n}", "public interface RecordFormatter\n{\n byte[] format(String tag, Object timestamp, Map<String, Object> data);\n\n byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len);\n\n byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue);\n\n String formatName();\n\n class Config\n {\n private List<Module> jacksonModules = Collections.emptyList();\n\n public List<Module> getJacksonModules()\n {\n return jacksonModules;\n }\n\n public void setJacksonModules(List<Module> jacksonModules)\n {\n this.jacksonModules = jacksonModules;\n }\n }\n}", "public interface Validatable\n{\n class ValidationList {\n private static class Validation\n {\n Class<? extends Annotation> annotationClass;\n BiFunction<Annotation, Number, Boolean> isValid;\n String messageTemplate;\n\n Validation(\n Class<? extends Annotation> annotationClass,\n BiFunction<Annotation, Number, Boolean> isValid,\n String messageTemplate)\n {\n this.annotationClass = annotationClass;\n this.isValid = isValid;\n this.messageTemplate = messageTemplate;\n }\n }\n\n private static final Validation VALIDATION_MAX = new Validation(\n Max.class,\n (annotation, actual) -> {\n Max maxAnnotation = (Max) annotation;\n if (maxAnnotation.inclusive()) {\n return maxAnnotation.value() >= actual.longValue();\n }\n else {\n return maxAnnotation.value() > actual.longValue();\n }\n },\n \"This field (%s) is more than (%s)\");\n\n private static final Validation VALIDATION_MIN = new Validation(\n Min.class,\n (annotation, actual) -> {\n Min minAnnotation = (Min) annotation;\n if (minAnnotation.inclusive()) {\n return minAnnotation.value() <= actual.longValue();\n }\n else {\n return minAnnotation.value() < actual.longValue();\n }\n },\n \"This field (%s) is less than (%s)\");\n\n private static final Validation VALIDATION_DECIMAL_MAX = new Validation(\n DecimalMax.class,\n (annotation, actual) -> {\n DecimalMax maxAnnotation = (DecimalMax) annotation;\n BigDecimal limitValue = new BigDecimal(maxAnnotation.value());\n BigDecimal actualValue = new BigDecimal(actual.toString());\n if (maxAnnotation.inclusive()) {\n return limitValue.compareTo(actualValue) >= 0;\n }\n else {\n return limitValue.compareTo(actualValue) > 0;\n }\n },\n \"This field (%s) is more than (%s)\");\n\n private static final Validation VALIDATION_DECIMAL_MIN = new Validation(\n DecimalMin.class,\n (annotation, actual) -> {\n DecimalMin maxAnnotation = (DecimalMin) annotation;\n BigDecimal limitValue = new BigDecimal(maxAnnotation.value());\n BigDecimal actualValue = new BigDecimal(actual.toString());\n if (maxAnnotation.inclusive()) {\n return limitValue.compareTo(actualValue) <= 0;\n }\n else {\n return limitValue.compareTo(actualValue) < 0;\n }\n },\n \"This field (%s) is less than (%s)\");\n\n private static final List<Validation> VALIDATIONS = Arrays.asList(\n VALIDATION_MAX,\n VALIDATION_MIN,\n VALIDATION_DECIMAL_MAX,\n VALIDATION_DECIMAL_MIN);\n }\n\n default void validate()\n {\n Class<? extends Object> klass = getClass();\n while (klass != Object.class) {\n for (Field field : klass.getDeclaredFields()) {\n for (ValidationList.Validation validation : ValidationList.VALIDATIONS) {\n Class<? extends Annotation> annotationClass = validation.annotationClass;\n if (field.isAnnotationPresent(annotationClass)) {\n Annotation annotation = field.getAnnotation(annotationClass);\n Object value;\n try {\n field.setAccessible(true);\n value = field.get(this);\n }\n catch (IllegalAccessException e) {\n throw new RuntimeException(\n String.format(\"Failed to get a value from field (%s)\", field), e);\n }\n\n if (value == null) {\n break;\n }\n\n if (!(value instanceof Number)) {\n throw new IllegalArgumentException(\n String.format(\"This field has (%s), but actual field is (%s)\", annotation, value.getClass()));\n }\n\n if (!validation.isValid.apply(annotation, (Number) value)) {\n throw new IllegalArgumentException(\n String.format(validation.messageTemplate, field, value));\n }\n }\n }\n }\n klass = klass.getSuperclass();\n }\n }\n}" ]
import org.komamitsu.fluency.BufferFullException; import org.komamitsu.fluency.EventTime; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.DecimalMin; import org.komamitsu.fluency.validation.annotation.Min; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicLong;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; public class Buffer implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(Buffer.class); private final FileBackup fileBackup; private final RecordFormatter recordFormatter; private final Config config; private final Map<String, RetentionBuffer> retentionBuffers = new HashMap<>(); private final LinkedBlockingQueue<TaggableBuffer> flushableBuffers = new LinkedBlockingQueue<>(); private final Queue<TaggableBuffer> backupBuffers = new ConcurrentLinkedQueue<>(); private final BufferPool bufferPool; public Buffer(RecordFormatter recordFormatter) { this(new Config(), recordFormatter); } public Buffer(final Config config, RecordFormatter recordFormatter) { config.validateValues(); this.config = config; if (config.getFileBackupDir() != null) { fileBackup = new FileBackup(new File(config.getFileBackupDir()), this, config.getFileBackupPrefix()); } else { fileBackup = null; } this.recordFormatter = recordFormatter; bufferPool = new BufferPool( config.getChunkInitialSize(), config.getMaxBufferSize(), config.jvmHeapBufferMode); init(); } private void init() { if (fileBackup != null) { for (FileBackup.SavedBuffer savedBuffer : fileBackup.getSavedFiles()) { savedBuffer.open((params, channel) -> { try { LOG.info("Loading buffer: params={}, buffer.size={}", params, channel.size()); } catch (IOException e) { LOG.error("Failed to access the backup file: params={}", params, e); } loadBufferFromFile(params, channel); }); } } } protected void saveBuffer(List<String> params, ByteBuffer buffer) { if (fileBackup == null) { return; } LOG.info("Saving buffer: params={}, buffer={}", params, buffer); fileBackup.saveBuffer(params, buffer); }
public void flush(Ingester ingester, boolean force)
2
idega/is.idega.idegaweb.egov.bpm
src/java/is/idega/idegaweb/egov/bpm/cases/board/BoardCasesManagerImpl.java
[ "public class IWBundleStarter implements IWBundleStartable {\n\t\n\tpublic static final String IW_BUNDLE_IDENTIFIER = \"is.idega.idegaweb.egov.bpm\";\n\n\tpublic void start(IWBundle starterBundle) {\n\t\t\n//\t\tEgovBPMViewManager viewManager = EgovBPMViewManager.getInstance(starterBundle.getApplication());\n//\t\tviewManager.initializeStandardNodes(starterBundle);\n\t}\n\n\tpublic void stop(IWBundle starterBundle) {\n\t}\n}", "public interface TaskViewerHelper {\n\n\tpublic String getPageUriForTaskViewer(IWContext iwc);\n\t\n\tpublic String getLinkToTheTaskRedirector(IWContext iwc, String basePage, String caseId, Long processInstanceId, String backPage, String taskName);\n\t\n\tpublic String getLinkToTheTask(IWContext iwc, String caseId, String taskInstanceId, String backPage);\n\t\n\tpublic String getTaskInstanceIdForTask(Long processInstanceId, String taskName);\n\n\t/**\n\t * \n\t * <p>Creates links to views of {@link Case}s.</p>\n\t * @param iwc is current FacesContext, not <code>null</code>;\n\t * @param relations is {@link Map} of {@link Case#getPrimaryKey()} and \n\t * {@link ProcessInstance}, not <code>null</code>;\n\t * @param backPage - <code>true</code> if it is required to get back to\n\t * to page the link was called;\n\t * @param taskName is {@link Task#getName()}, which should be shown. \n\t * Not <code>null</code>;\n\t * @return {@link Map} of {@link Case#getPrimaryKey()} and {@link URL} \n\t * to preview or {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic Map<Long, String> getLinksToTheTaskRedirector(IWContext iwc,\n\t\t\tMap<Long, ProcessInstance> relations, boolean backPage,\n\t\t\tString taskName);\n}", "@Service\n@Scope(BeanDefinition.SCOPE_SINGLETON)\npublic class CaseProcessInstanceRelationImpl {\n\n\t@Autowired\n\tprivate BPMDAO bpmDAO;\n\n\tprotected BPMDAO getBPMDAO() {\n\t\tif (this.bpmDAO == null) {\n\t\t\tELUtil.getInstance().autowire(this);\n\t\t}\n\n\t\treturn this.bpmDAO;\n\t}\n\t\n\t@Autowired\n\tprivate CasesBPMDAO casesBPMDAO;\n\n\tprotected CasesBPMDAO getCasesBPMDAO() {\n\t\tif (this.casesBPMDAO == null) {\n\t\t\tELUtil.getInstance().autowire(this);\n\t\t}\n\t\t\n\t\treturn casesBPMDAO;\n\t}\n\n\tpublic Long getCaseProcessInstanceId(Integer caseId) {\n\t\tCaseProcInstBind cpi = getCasesBPMDAO().getCaseProcInstBindByCaseId(caseId);\n\t\tLong processInstanceId = cpi.getProcInstId();\n\t\t\n\t\treturn processInstanceId;\n\t}\n\n\t\n\n\tpublic Map<Integer, Long> getCasesProcessInstancesIds(Set<Integer> casesIds) {\n\t\tList<CaseProcInstBind> binds = getCasesBPMDAO().getCasesProcInstBindsByCasesIds(new ArrayList<Integer>(casesIds));\n\t\tif (ListUtil.isEmpty(binds))\n\t\t\treturn Collections.emptyMap();\n\t\t\n\t\tMap<Integer, Long> casesIdsMapping = new HashMap<Integer, Long>();\n\t\tfor (CaseProcInstBind bind: binds) {\n\t\t\tInteger caseId = bind.getCaseId();\n\t\t\tLong processInstanceId = bind.getProcInstId();\n\t\t\tif (casesIdsMapping.get(caseId) == null) {\n\t\t\t\tcasesIdsMapping.put(caseId, processInstanceId);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn casesIdsMapping;\n\t}\n\t\n\t/**\n\t * \n\t * @param cases to get {@link ProcessInstance}s for, not <code>null</code>;\n\t * @return values from {@link CaseProcInstBind} table or \n\t * {@link Collections#emptyMap()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic Map<ProcessInstance, Case> getCasesAndProcessInstances(Collection<? extends Case> cases) {\n\t\tif (ListUtil.isEmpty(cases)) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\n\t\t/* Collecting ids of cases */\n\t\tMap<Integer, Case> caseIDs = new HashMap<Integer, Case>(cases.size());\n\t\tfor (Case theCase: cases) {\n\t\t\tcaseIDs.put(Integer.valueOf(theCase.getPrimaryKey().toString()), theCase);\n\t\t}\n\n\t\t/* Collecting relations between cases and process instances */\n\t\tMap<Integer, Long> ids = getCasesProcessInstancesIds(caseIDs.keySet());\n\t\tif (MapUtil.isEmpty(ids)) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\n\t\t/* Collecting process instances */\n\t\tList<ProcessInstance> processInstances = getBPMDAO().getProcessInstancesByIDs(ids.values());\n\t\tMap<Long, ProcessInstance> processInstancesMap = new HashMap<Long, ProcessInstance>(processInstances.size());\n\t\tfor (ProcessInstance pi : processInstances) {\n\t\t\tprocessInstancesMap.put(pi.getId(), pi);\n\t\t}\n\n\t\t/* Creating map of relations */\n\t\tMap<ProcessInstance, Case> casesProcessInstances = new HashMap<ProcessInstance, Case>(ids.size());\n\t\tfor (Integer caseId : ids.keySet()) {\n\t\t\tLong processInstanceId = ids.get(caseId);\n\t\t\tif (processInstanceId == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcasesProcessInstances.put(\n\t\t\t\t\tprocessInstancesMap.get(processInstanceId),\n\t\t\t\t\tcaseIDs.get(caseId));\n\t\t}\n\n\t\treturn casesProcessInstances;\n\t}\n\n\t/**\n\t * \n\t * <p>Helping method, to get {@link GeneralCase} from created {@link Map}.\n\t * No querying is done.</p>\n\t * @param relationMap is {@link Map} from \n\t * {@link CaseProcessInstanceRelationImpl#getCasesAndProcessInstances(Collection)},\n\t * not <code>null</code>;\n\t * @param processInstanceId is {@link ProcessInstance#getId()} to search by,\n\t * not <code>null</code>;\n\t * @return {@link Case} corresponding {@link ProcessInstance} or \n\t * <code>null</code> on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic GeneralCase getCase(\n\t\t\tMap<ProcessInstance, Case> relationMap, \n\t\t\tLong processInstanceId) {\n\t\tif (MapUtil.isEmpty(relationMap) || processInstanceId == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tProcessInstance processInstance = getProcessInstance(relationMap, processInstanceId);\n\t\tif (processInstance == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tCase theCase = relationMap.get(processInstance);\n\t\tif (theCase instanceof GeneralCase) {\n\t\t\treturn (GeneralCase) theCase;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * \n\t * <p>Helping method, to get {@link ProcessInstance} from created {@link Map}.\n\t * No querying is done.</p>\n\t * @param relationMap is {@link Map} from \n\t * {@link CaseProcessInstanceRelationImpl#getCasesAndProcessInstances(Collection)},\n\t * not <code>null</code>;\n\t * @param processInstanceId is {@link ProcessInstance#getId()} to search by,\n\t * not <code>null</code>;\n\t * @return {@link ProcessInstance} exiting on {@link Map} or <code>null</code>\n\t * on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic ProcessInstance getProcessInstance(\n\t\t\tMap<ProcessInstance, Case> relationMap, \n\t\t\tLong processInstanceId) {\n\t\tif (MapUtil.isEmpty(relationMap) || processInstanceId == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfor (ProcessInstance pi : relationMap.keySet()) {\n\t\t\tif (processInstanceId.longValue() == pi.getId()) {\n\t\t\t\treturn pi;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n}", "@Service(\"caseHandlerAssignmentHandler\")\n@Scope(BeanDefinition.SCOPE_PROTOTYPE)\npublic class CaseHandlerAssignmentHandler implements ActionHandler {\n\n\tprivate static final long serialVersionUID = -6642593190563557536L;\n\n\tprivate String caseHandlerRoleExp;\n\tprivate String subjectKey;\n\tprivate String subjectValues;\n\tprivate String messageKey;\n\tprivate String messageValues;\n\tprivate String messagesBundle;\n\tprivate String sendToRoles;\n\n\tprivate Map<String, String> inlineSubject;\n\tprivate Map<String, String> inlineMessage;\n\n\t@Autowired\n\tprivate CasesBPMDAO casesBPMDAO;\n\n\t@Autowired\n\t@ProcessWatchType(\"cases\")\n\tprivate ProcessWatch processWatcher;\n\n\t@Autowired\n\tprivate BPMFactory bpmFactory;\n\n\t@Autowired\n\tprivate SendCaseMessagesHandler sendCaseMessagesHandler;\n\n\tprivate Integer handlerUserId;\n\tprivate Integer recipientId;\n\tprivate Integer performerUserId;\n\n\tpublic static final String assignHandlerEventType = \"handlerAssignedToCase\";\n\tpublic static final String unassignHandlerEventType = \"handlerUnassignedFromCase\";\n\tpublic static final String handlerUserIdVarName = ProcessConstants.HANDLER_IDENTIFIER;\n\tpublic static final String performerUserIdVarName = \"performerUserId\";\n\tpublic static final String recipientUserIdVarName = \"recipientUserId\";\n\n\tprotected ProcessInstance getProcessInstance(ExecutionContext ectx) {\n\t\treturn ectx.getProcessInstance();\n\t}\n\n\t@Override\n\tpublic void execute(ExecutionContext ectx) throws Exception {\n\t\tProcessInstance pi = getProcessInstance(ectx);\n\t\tLong processInstanceId = pi.getId();\n\t\tCaseProcInstBind cpi = getCasesBPMDAO().find(CaseProcInstBind.class, processInstanceId);\n\n\t\tString event = ectx.getEvent().getEventType();\n\n\t\tInteger caseId = cpi.getCaseId();\n\n\t\ttry {\n\t\t\tIWApplicationContext iwac = getIWAC();\n\t\t\tCasesBusiness casesBusiness = getCasesBusiness(iwac);\n\t\t\tGeneralCase genCase = casesBusiness.getGeneralCase(caseId);\n\n\t\t\tfinal Role caseHandlerRole;\n\n\t\t\tif (getCaseHandlerRoleExp() != null) {\n\t\t\t\tcaseHandlerRole = JSONExpHandler.resolveRoleFromJSONExpression(getCaseHandlerRoleExp(), ectx);\n\t\t\t} else {\n\t\t\t\tString defaultCaseHandlerRoleName = \"bpm_caseHandler\";\n\t\t\t\tLogger.getLogger(getClass().getName()).info(\"No caseHandler role expression found, using default=\" + defaultCaseHandlerRoleName);\n\t\t\t\tcaseHandlerRole = new Role(defaultCaseHandlerRoleName);\n\t\t\t}\n\n\t\t\tif (assignHandlerEventType.equals(event) || \"node-enter\".equals(event)) {\n\t\t\t\tunassign(genCase, processInstanceId, casesBusiness, ectx, caseHandlerRole);\n\t\t\t\tassign(genCase, pi, casesBusiness, ectx, iwac, caseHandlerRole);\n\t\t\t} else if (unassignHandlerEventType.equals(event)) {\n\t\t\t\tunassign(genCase, processInstanceId, casesBusiness, ectx, caseHandlerRole);\n\t\t\t} else\n\t\t\t\tthrow new IllegalArgumentException(\"Illegal event type provided=\" + ectx.getEvent().getEventType());\n\n\t\t\tsendMessages(ectx);\n\t\t} catch (RemoteException e) {\n\t\t\tthrow new IBORuntimeException(e);\n\t\t} catch (FinderException e) {\n\t\t\tthrow new IBORuntimeException(e);\n\t\t}\n\t}\n\n\tprotected void unassign(\n\t\t\tGeneralCase genCase,\n\t\t\tLong processInstanceId,\n\t CasesBusiness casesBusiness,\n\t ExecutionContext ectx,\n\t Role caseHandlerRole\n\t) throws Exception {\n\t\tUser currentHandler = genCase.getHandledBy();\n\t\tif (currentHandler != null) {\n\t\t\tgetProcessWatcher().removeWatch(processInstanceId, new Integer(currentHandler.getPrimaryKey().toString()));\n\t\t\tgetBpmFactory().getRolesManager().removeIdentitiesForRoles(\n\t\t\t Arrays.asList(new Role[] { caseHandlerRole }),\n\t\t\t new Identity(currentHandler.getPrimaryKey().toString(), IdentityType.USER),\n\t\t\t processInstanceId\n\t\t\t);\n\t\t}\n\n\t\tcasesBusiness.untakeCase(genCase);\n\t}\n\n\tprotected Integer getHandlerUserId(ExecutionContext ectx) {\n\t\tif (handlerUserId == null)\n\t\t\thandlerUserId = (Integer) ectx.getVariable(handlerUserIdVarName);\n\n\t\tif (handlerUserId == null)\n\t\t\tthrow new IllegalStateException(\"No handler user id set\");\n\n\t\treturn handlerUserId;\n\t}\n\n\tprotected Integer getPerformerUserId(ExecutionContext ectx) {\n\t\tif (performerUserId == null)\n\t\t\tperformerUserId = (Integer) ectx.getVariable(performerUserIdVarName);\n\n\t\tif (performerUserId == null)\n\t\t\tperformerUserId = new Integer(getCurrentUser().getPrimaryKey().toString());\n\n\t\treturn performerUserId;\n\t}\n\n\tprotected Integer getRecipientUserId(ExecutionContext ectx) {\n\t\tif (recipientId == null)\n\t\t\trecipientId = (Integer) ectx.getVariable(recipientUserIdVarName);\n\n\t\treturn recipientId;\n\t}\n\n\tprotected User getCurrentUser() {\n\t\treturn IWContext.getCurrentInstance().getCurrentUser();\n\t}\n\n\tprotected void assign(\n\t\t\tGeneralCase genCase,\n\t\t\tProcessInstance pi,\n\t CasesBusiness casesBusiness,\n\t ExecutionContext ectx,\n\t IWApplicationContext iwac,\n\t Role caseHandlerRole\n\t) throws Exception {\n\t\tfinal Integer handlerUserId = getHandlerUserId(ectx);\n\t\tfinal Integer performerUserId = getPerformerUserId(ectx);\n\n\t\t// assigning handler\n\t\tfinal User currentHandler = genCase.getHandledBy();\n\n\t\tif (currentHandler == null || !String.valueOf(handlerUserId).equals(String.valueOf(currentHandler.getPrimaryKey()))) {\n\t\t\tfinal UserBusiness userBusiness = getUserBusiness(iwac);\n\n\t\t\tfinal IWContext iwc = IWContext.getCurrentInstance();\n\n\t\t\tfinal User handler = userBusiness.getUser(handlerUserId);\n\t\t\tfinal User performer = userBusiness.getUser(performerUserId);\n\n\t\t\t// statistics and status change. also keeping handlerId there\n\t\t\tcasesBusiness.takeCase(genCase, handler, iwc, performer, true, false);\n\n\t\t\t// the case now appears in handler's mycases list\n\t\t\tgetProcessWatcher().assignWatch(pi.getId(), handlerUserId);\n\t\t}\n\n\t\t// creating case handler role and assigning handler user to this, so\n\t\t// that 'ordinary' users could see their contacts etc (they have the\n\t\t// permission to see caseHandler contacts)\n\t\tfinal List<Role> roles = Arrays.asList(new Role[] { caseHandlerRole });\n\t\tgetBpmFactory().getRolesManager().createProcessActors(roles, pi);\n\t\tgetBpmFactory().getRolesManager().createIdentitiesForRoles(roles, new Identity(handlerUserId.toString(), IdentityType.USER), pi.getId());\n\t}\n\n\tprotected void sendMessages(ExecutionContext ectx) throws Exception {\n\t\tSendCaseMessagesHandler msgHan = getSendCaseMessagesHandler();\n\t\tmsgHan.setMessageKey(getMessageKey());\n\t\tmsgHan.setMessagesBundle(getMessagesBundle());\n\t\tmsgHan.setMessageValues(getMessageValues());\n\t\tmsgHan.setSendToRoles(getSendToRoles());\n\t\tmsgHan.setSubjectKey(getSubjectKey());\n\t\tmsgHan.setSubjectValues(getSubjectValues());\n\t\tmsgHan.setInlineSubject(getInlineSubject());\n\t\tmsgHan.setInlineMessage(getInlineMessage());\n\n\t\tif (getRecipientUserId(ectx) != null) {\n\t\t\tmsgHan.setRecipientUserID(getRecipientUserId(ectx));\n\t\t} else if (getHandlerUserId(ectx) != null) {\n\t\t\tmsgHan.setRecipientUserID(getHandlerUserId(ectx));\n\t\t}\n\n\t\tmsgHan.execute(ectx);\n\t}\n\n\tprotected CasesBusiness getCasesBusiness(IWApplicationContext iwac) {\n\t\ttry {\n\t\t\treturn IBOLookup.getServiceInstance(iwac, CasesBusiness.class);\n\t\t} catch (IBOLookupException ile) {\n\t\t\tthrow new IBORuntimeException(ile);\n\t\t}\n\t}\n\n\tprotected UserBusiness getUserBusiness(IWApplicationContext iwac) {\n\t\ttry {\n\t\t\treturn IBOLookup.getServiceInstance(iwac, UserBusiness.class);\n\t\t} catch (IBOLookupException ile) {\n\t\t\tthrow new IBORuntimeException(ile);\n\t\t}\n\t}\n\n\tpublic String getSubjectKey() {\n\t\treturn subjectKey;\n\t}\n\n\tpublic void setSubjectKey(String subjectKey) {\n\t\tthis.subjectKey = subjectKey;\n\t}\n\n\tpublic String getSubjectValues() {\n\t\treturn subjectValues;\n\t}\n\n\tpublic void setSubjectValues(String subjectValues) {\n\t\tthis.subjectValues = subjectValues;\n\t}\n\n\tpublic String getMessageKey() {\n\t\treturn messageKey;\n\t}\n\n\tpublic void setMessageKey(String messageKey) {\n\t\tthis.messageKey = messageKey;\n\t}\n\n\tpublic String getMessageValues() {\n\t\treturn messageValues;\n\t}\n\n\tpublic void setMessageValues(String messageValues) {\n\t\tthis.messageValues = messageValues;\n\t}\n\n\tpublic String getMessagesBundle() {\n\t\treturn messagesBundle;\n\t}\n\n\tpublic void setMessagesBundle(String messagesBundle) {\n\t\tthis.messagesBundle = messagesBundle;\n\t}\n\n\tpublic String getSendToRoles() {\n\t\treturn sendToRoles;\n\t}\n\n\tpublic void setSendToRoles(String sendToRoles) {\n\t\tthis.sendToRoles = sendToRoles;\n\t}\n\n\tpublic CasesBPMDAO getCasesBPMDAO() {\n\t\treturn casesBPMDAO;\n\t}\n\n\tpublic ProcessWatch getProcessWatcher() {\n\t\treturn processWatcher;\n\t}\n\n\tprotected IWApplicationContext getIWAC() {\n\t\tfinal IWContext iwc = IWContext.getCurrentInstance();\n\t\tfinal IWApplicationContext iwac;\n\t\tif (iwc != null) {\n\t\t\tiwac = iwc;\n\t\t} else {\n\t\t\tiwac = IWMainApplication.getDefaultIWApplicationContext();\n\t\t}\n\t\treturn iwac;\n\t}\n\n\tpublic Map<String, String> getInlineSubject() {\n\t\treturn inlineSubject;\n\t}\n\n\tpublic void setInlineSubject(Map<String, String> inlineSubject) {\n\t\tthis.inlineSubject = inlineSubject;\n\t}\n\n\tpublic Map<String, String> getInlineMessage() {\n\t\treturn inlineMessage;\n\t}\n\n\tpublic void setInlineMessage(Map<String, String> inlineMessage) {\n\t\tthis.inlineMessage = inlineMessage;\n\t}\n\n\tpublic BPMFactory getBpmFactory() {\n\t\treturn bpmFactory;\n\t}\n\n\tpublic void setBpmFactory(BPMFactory bpmFactory) {\n\t\tthis.bpmFactory = bpmFactory;\n\t}\n\n\tpublic String getCaseHandlerRoleExp() {\n\t\treturn caseHandlerRoleExp;\n\t}\n\n\tpublic void setCaseHandlerRoleExp(String caseHandlerRoleExp) {\n\t\tthis.caseHandlerRoleExp = caseHandlerRoleExp;\n\t}\n\n\tSendCaseMessagesHandler getSendCaseMessagesHandler() {\n\t\treturn sendCaseMessagesHandler;\n\t}\n\n\tpublic void setHandlerUserId(Integer handlerUserId) {\n\t\tthis.handlerUserId = handlerUserId;\n\t}\n\n\tpublic void setPerformerUserId(Integer performerUserId) {\n\t\tthis.performerUserId = performerUserId;\n\t}\n}", "public interface BPMCasesRetrievalManager extends CasesRetrievalManager, ApplicationListener{\n\t/**\n\t * \n\t * @param processInstances where to search connected {@link User}s,\n\t * not <code>null</code>;\n\t * @return {@link User} connected to process or \n\t * {@link Collections#emptyList()} on failure.\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<User> getConnectedUsers(\n\t\t\tCollection<ProcessInstanceW> processInstances);\n\t\n\t/**\n\t * \n\t * @param theCase where users should be found, not <code>null</code>;\n\t * @return list of {@link User}, who can see or modify {@link Case} or\n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<User> getConnectedUsers(Case theCase);\n\t\n\t/**\n\t * \n\t * @param processInstances where to search {@link BPMEmailDocument},\n\t * not <code>null</code>;\n\t * @param owner is {@link User}, who can see these \n\t * {@link BPMEmailDocument}s, not <code>null</code>;\n\t * @return {@link BPMEmailDocument}s or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<BPMEmailDocument> getBPMEmailDocuments(\n\t\t\tCollection<ProcessInstanceW> processInstances,\n\t\t\tUser owner);\n\t\n\t/**\n\t * \n\t * @param processInstances where to search {@link Task}s, not\n\t * <code>null</code>;\n\t * @param owner who can see {@link Task}s, not <code>null</code>;\n\t * @param locale to which {@link BPMDocument}s should be translated, \n\t * uses current {@link Locale} when <code>null</code>;\n\t * @return {@link BPMDocument}s for {@link User} or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<BPMDocument> getTaskBPMDocuments(\n\t\t\tCollection<ProcessInstanceW> processInstances,\n\t\t\tUser owner, Locale locale);\n\t\n\t/**\n\t * \n\t * @param processInstances where to search for documents, not\n\t * <code>null</code>;\n\t * @param owner is {@link User} who can see submitted \n\t * {@link BPMDocument}s, not <code>null</code>;\n\t * @param locale in which documents should be translated, \n\t * current locale will be used if <code>null</code>;\n\t * @return submitted {@link BPMDocument}s or \n\t * {@link Collections#emptyList()} on failure.\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<BPMDocument> getSubmittedBPMDocuments(\n\t\t\tCollection<ProcessInstanceW> processInstances,\n\t\t\tUser owner, Locale locale);\n\t\n\t/**\n\t * \n\t * @param applicationPrimaryKey is {@link Application#getPrimaryKey()},\n\t * not <code>null</code>;\n\t * @return {@link List} of {@link ProcessInstanceW} or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessInstanceW> getProcessInstancesW(Object applicationPrimaryKey);\n\t\n\t/**\n\t * \n\t * @param application to get {@link ProcessInstanceW}s for, \n\t * not <code>null</code>;\n\t * @return {@link List} of {@link ProcessInstanceW} or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessInstanceW> getProcessInstancesW(Application application);\n\t\n\t/**\n\t * \n\t * @param processDefinitionName is {@link ProcessDefinition#getName()},\n\t * not <code>null</code>;\n\t * @return {@link List} of {@link ProcessInstanceW} or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessInstanceW> getProcessInstancesW(String processDefinitionName);\n\t\n\t/**\n\t * \n\t * @param theCase for which process instance should be found, \n\t * not <code>null</code>;\n\t * @return {@link ProcessInstanceW} of {@link Case} or <code>null</code>\n\t * on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic ProcessInstanceW getProcessInstancesW(Case theCase);\n\t\n\t/**\n\t * \n\t * @param processDefinitionName is {@link ProcessDefinition#getName()},\n\t * not <code>null</code>;\n\t * @return {@link ProcessInstance}s by given {@link ProcessDefinition} \n\t * name or {@link Collections#emptyList()} on failure.\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessInstance> getProcessInstances(String processDefinitionName);\n\t\n\t/**\n\t * \n\t * @param processDefinitionName is {@link ProcessDefinition#getName()},\n\t * not <code>null</code>;\n\t * @return {@link List} of {@link ProcessInstance#getId()} by given \n\t * {@link ProcessDefinition} name or {@link Collections#emptyList()} \n\t * on failure.\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<Long> getProcessInstancesIDs(String processDefinitionName);\n\t\n\t/**\n\t * \n\t * @param processDefinitionName is {@link ProcessDefinition#getName()},\n\t * not <code>null</code>;\n\t * @return all {@link ProcessDefinition}s by given name or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessDefinition> getProcessDefinitions(String processDefinitionName);\n\t\n\t/**\n\t * \n\t * @param processDefinitionName is {@link ProcessDefinition#getName()},\n\t * not <code>null</code>;\n\t * @return all id's of {@link ProcessDefinition}s by given name or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<Long> getProcessDefinitionsIDs(String processDefinitionName);\n\t\n\t/**\n\t * \n\t * @param application is application, which {@link ProcessDefinition}s are\n\t * required, not <code>null</code>;\n\t * not <code>null</code>;\n\t * @return all {@link ProcessDefinition}s by given name or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessDefinition> getProcessDefinitions(Application application);\n\t\n\t/**\n\t * \n\t * @param application of which process definition IDs is required, not\n\t * <code>null</code>;\n\t * @return all id's of {@link ProcessDefinition}s by given name or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<Long> getProcessDefinitionsIDs(Application application);\n\t\n\t/**\n\t * \n\t * @param applicationPrimaryKey is {@link Application#getPrimaryKey()} \n\t * of which {@link ProcessDefinition}s are required, not\n\t * <code>null</code>;\n\t * @return all {@link ProcessDefinition}s by given name or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<ProcessDefinition> getProcessDefinitions(Object applicationPrimaryKey);\n\t\n\t/**\n\t * \n\t * @param applicationPrimaryKey is {@link Application#getPrimaryKey()} \n\t * of which process definition IDs is required, not\n\t * <code>null</code>;\n\t * @return all id's of {@link ProcessDefinition}s by given name or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<Long> getProcessDefinitionsIDs(Object applicationPrimaryKey);\n\n\t/**\n\t * <p>Only PROC_CASE</p>\n\t * @param processDefinitionNames is {@link Collection} of \n\t * {@link ProcessDefinition#getName()} to filter {@link Case}s by. It is\n\t * skipped, if <code>null</code>;\n\t * @param caseStatuses is {@link Collection} of {@link Case#getStatus()}\n\t * to filter {@link Case}s by. It is skipped, if <code>null</code>;\n\t * @return array of {@link Case#getPrimaryKey()} by criteria or \n\t * <code>null</code> on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic String[] getCasesPrimaryKeys(Collection<String> processDefinitionNames, Collection<String> caseStatuses);\n\n\t/**\n\t * <p>Only PROC_CASE</p>\n\t * @param processDefinitionNames is {@link Collection} of \n\t * {@link ProcessDefinition#getName()} to filter {@link Case}s by. It is\n\t * skipped, if <code>null</code>;\n\t * @param caseStatuses is {@link Collection} of {@link Case#getStatus()}\n\t * to filter {@link Case}s by. It is skipped, if <code>null</code>;\n\t * @param subscribers is {@link Collection} of {@link User}, who\n\t * is subscribed \"{@link Case#addSubscriber(User)}\". If <code>null</code>\n\t * then this option will be skipped;\n\t * @return array of {@link Case#getPrimaryKey()} by criteria or \n\t * <code>null</code> on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic String[] getCasesPrimaryKeys(\n\t\t\tCollection<String> processDefinitionNames, \n\t\t\tCollection<String> caseStatuses, \n\t\t\tCollection<User> subscribers);\n\n\t/**\n\t * <p>Only PROC_CASE</p>\n\t * @param processDefinitionNames is {@link Collection} of \n\t * {@link ProcessDefinition#getName()} to filter {@link Case}s by. It is\n\t * skipped, if <code>null</code>;\n\t * @param processInstanceIds is {@link Collection} of {@link ProcessInstance#getId()}\n\t * to search by, skipped if <code>null</code>;\n\t * @param caseStatuses is {@link Collection} of {@link Case#getStatus()}\n\t * to filter {@link Case}s by. It is skipped, if <code>null</code>;\n\t * @param subscribers is {@link Collection} of {@link User}, who\n\t * is subscribed \"{@link Case#addSubscriber(User)}\". If <code>null</code>\n\t * then this option will be skipped;\n\t * @param caseManagerTypes is {@link Collection} of \n\t * {@link Case#getCaseManagerType()}, if <code>null</code> then option\n\t * will be skipped;\n\t * @param dateCreatedFrom is floor of {@link Case#getCreated()}, \n\t * skipped if <code>null</code>;\n\t * @param dateCreatedTo is ceiling of {@link Case#getCreated()},\n\t * skipped if <code>null</code>;\n\t * @return array of {@link Case#getPrimaryKey()} by criteria or \n\t * <code>null</code> on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic String[] getCasesPrimaryKeys(\n\t\t\tCollection<String> processDefinitionNames,\n\t\t\tCollection<? extends Number> processInstanceIds, \n\t\t\tCollection<String> caseStatuses,\n\t\t\tCollection<User> subscribers, Collection<String> caseManagerTypes, Date dateCreatedFrom, Date dateCreatedTo);\n\n\t/**\n\t * <p>Only PROC_CASE</p>\n\t * @param processDefinitionNames is {@link Collection} of \n\t * {@link ProcessDefinition#getName()} to filter {@link Case}s by. It is\n\t * skipped, if <code>null</code>;\n\t * @param caseStatuses is {@link Collection} of {@link Case#getStatus()}\n\t * to filter {@link Case}s by. It is skipped, if <code>null</code>;\n\t * @return {@link List} of {@link Case}s by criteria or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic List<Case> getCases(Collection<String> processDefinitionNames,\n\t\t\tCollection<String> caseStatuses);\n\n\t/**\n\t * <p>Only PROC_CASE</p>\n\t * @param processDefinitionNames is {@link Collection} of \n\t * {@link ProcessDefinition#getName()} to filter {@link Case}s by. It is\n\t * skipped, if <code>null</code>;\n\t * @param caseStatuses is {@link Collection} of {@link Case#getStatus()}\n\t * to filter {@link Case}s by. It is skipped, if <code>null</code>;\n\t * @param subscribers is {@link Collection} of {@link User}, who\n\t * is subscribed \"{@link Case#addSubscriber(User)}\". If <code>null</code>\n\t * then this option will be skipped;\n\t * @return {@link List} of {@link Case}s by criteria or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic List<Case> getCases(Collection<String> processDefinitionNames,\n\t\t\tCollection<String> caseStatuses, Collection<User> subscribers);\n\n\t/**\n\t * <p>Only PROC_CASE</p>\n\t * @param processDefinitionNames is {@link Collection} of \n\t * {@link ProcessDefinition#getName()} to filter {@link Case}s by. It is\n\t * skipped, if <code>null</code>;\n\t * @param processInstanceIds is {@link Collection} of {@link ProcessInstance#getId()}\n\t * to filter {@link Case}s by, skipped if <code>null</code>;\n\t * @param caseStatuses is {@link Collection} of {@link Case#getStatus()}\n\t * to filter {@link Case}s by. It is skipped, if <code>null</code>;\n\t * @param subscribers is {@link Collection} of {@link User}, who\n\t * is subscribed \"{@link Case#addSubscriber(User)}\". If <code>null</code>\n\t * then this option will be skipped;\n\t * @param caseManagerTypes is {@link Collection} of \n\t * {@link Case#getCaseManagerType()}, if <code>null</code> then option\n\t * will be skipped;\n\t * @param dateFrom is floor of {@link Case#getCreated()}, \n\t * skipped if <code>null</code>;\n\t * @param dateTo is ceiling of {@link Case#getCreated()},\n\t * skipped if <code>null</code>;\n\t * @return {@link List} of {@link Case}s by criteria or \n\t * {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic List<Case> getCases(\n\t\t\tCollection<String> processDefinitionNames,\n\t\t\tCollection<Long> processInstanceIds, \n\t\t\tCollection<String> caseStatuses,\n\t\t\tCollection<User> subscribers, \n\t\t\tCollection<String> caseManagerTypes, \n\t\t\tDate dateFrom, \n\t\t\tDate dateTo);\n\n\t/**\n\t * \n\t * @param processInstances to search by, not <code>null</code>;\n\t * @return {@link Case}s by criteria, {@link Collections#emptyList()} on failure;\n\t * @author <a href=\"mailto:martynas@idega.com\">Martynas Stakė</a>\n\t */\n\tpublic List<Case> getCases(Collection<ProcessInstanceW> processInstances);\n\n\t/**\n\t * \n\t * @param caseIdentifiers is {@link Collection} of \n\t * {@link Case#getCaseIdentifier()}, to search role names for, \n\t * not <code>null</code>;\n\t * @return {@link ICRole}s for {@link Case}s, which has managerRoleName\n\t * permissions or <code>null</code> on failure;\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic String[] getManagerRoleNames(Collection<String> caseIdentifiers);\n\n\t/**\n\t * \n\t * <p>Checks if current {@link User} has cases manager access for at least\n\t * one of give {@link Case#getCaseIdentifier()}.</p>\n\t * @param caseIdentifiers is {@link Case#getCaseIdentifier()} to check\n\t * form managing possibility, not <code>null</code>;\n\t * @return <code>true</code> if current {@link User} has cases manager\n\t * access to at least one of {@link Case}s or <code>false</code>\n\t * if all of them are not visible to {@link User};\n\t * @author <a href=\"mailto:martynas@idega.is\">Martynas Stakė</a>\n\t */\n\tpublic boolean hasManagerAccess(Collection<String> caseIdentifiers);\n}", "public interface BPMProcessVariablesBean extends Serializable {\n\n\tpublic static final String SPRING_BEAN_IDENTIFIER = \"bpmProcessVariablesBean\";\n\n\tpublic abstract List<SelectItem> getProcessVariables();\n\n\tpublic abstract Long getProcessDefinitionId();\n\n\tpublic abstract void setProcessDefinitionId(Long processDefinitionId);\n\n\tpublic boolean isDisplayVariables();\n\n\tpublic boolean isDisplayNoVariablesText();\n\n\tpublic String getDeleteImagePath();\n\n\tpublic String getLoadingMessage();\n\n\tpublic String getAddVariableImage();\n\n\tpublic List<AdvancedProperty> getAvailableVariables(Collection<VariableInstanceInfo> variables, Locale locale, boolean isAdmin, boolean useRealValue);\n\n\tpublic String getVariableLocalizedName(String name, Locale locale);\n}" ]
import is.idega.idegaweb.egov.bpm.IWBundleStarter; import is.idega.idegaweb.egov.bpm.business.TaskViewerHelper; import is.idega.idegaweb.egov.bpm.cases.CaseProcessInstanceRelationImpl; import is.idega.idegaweb.egov.bpm.cases.actionhandlers.CaseHandlerAssignmentHandler; import is.idega.idegaweb.egov.bpm.cases.manager.BPMCasesRetrievalManager; import is.idega.idegaweb.egov.bpm.cases.presentation.beans.BPMProcessVariablesBean; import is.idega.idegaweb.egov.cases.business.BoardCasesComparator; import is.idega.idegaweb.egov.cases.business.BoardCasesManager; import is.idega.idegaweb.egov.cases.data.GeneralCase; import is.idega.idegaweb.egov.cases.data.GeneralCaseBMPBean; import is.idega.idegaweb.egov.cases.presentation.CasesBoardViewCustomizer; import is.idega.idegaweb.egov.cases.presentation.CasesBoardViewer; import is.idega.idegaweb.egov.cases.presentation.beans.CaseBoardBean; import is.idega.idegaweb.egov.cases.presentation.beans.CaseBoardTableBean; import is.idega.idegaweb.egov.cases.presentation.beans.CaseBoardTableBodyRowBean; import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.io.Serializable; import java.math.BigDecimal; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import org.jbpm.graph.def.ProcessDefinition; import org.jbpm.graph.exe.ProcessInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.idega.block.process.business.ProcessConstants; import com.idega.block.process.data.Case; import com.idega.block.process.data.CaseBMPBean; import com.idega.block.process.data.CaseHome; import com.idega.bpm.xformsview.converters.ObjectCollectionConverter; import com.idega.builder.bean.AdvancedProperty; import com.idega.business.IBOLookup; import com.idega.core.contact.data.Email; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.idegaweb.IWResourceBundle; import com.idega.jbpm.bean.VariableByteArrayInstance; import com.idega.jbpm.bean.VariableInstanceInfo; import com.idega.jbpm.data.VariableInstanceQuerier; import com.idega.jbpm.data.dao.BPMDAO; import com.idega.jbpm.utils.JBPMConstants; import com.idega.presentation.IWContext; import com.idega.user.business.NoEmailFoundException; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.util.ArrayUtil; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.ListUtil; import com.idega.util.StringHandler; import com.idega.util.StringUtil; import com.idega.util.WebUtil; import com.idega.util.datastructures.map.MapUtil; import com.idega.util.expression.ELUtil;
if (isEqual(column.getId(), ProcessConstants.BOARD_FINANCING_DECISION)) // Calculating board amounts boardAmountTotal = boardAmountTotal.add(caseBoard.getBoardAmount()); else if (isEqual(column.getId(), ProcessConstants.BOARD_FINANCING_SUGGESTION)) // Calculating grant amount suggestions grantAmountSuggestionTotal = grantAmountSuggestionTotal.add(caseBoard.getGrantAmountSuggestion()); } index++; } rowBean.setValues(rowValues); bodyRows.add(rowBean); } data.setBodyBeans(bodyRows); // Footer data.setFooterValues(getFooterValues(data.getBodyBeans().get(0).getValues().keySet().size() + (financingTableAdded ? 3 : 0), grantAmountSuggestionTotal, boardAmountTotal, uuid)); // Everything is OK data.setFilledWithData(Boolean.TRUE); return data; } /* * (non-Javadoc) * @see is.idega.idegaweb.egov.cases.business.BoardCasesManager#getTableData(com.idega.presentation.IWContext, java.util.Collection, java.lang.String, java.lang.String, boolean, boolean, java.lang.String) */ @Override public CaseBoardTableBean getTableData( Collection<String> caseStatuses, String processName, String uuid, boolean isSubscribedOnly, boolean backPage, String taskName) { return getTableData(null, null, caseStatuses, processName, uuid, isSubscribedOnly, backPage, taskName); } @Override public AdvancedProperty getHandlerInfo(IWContext iwc, User handler) { if (handler == null) return null; UserBusiness userBusiness = null; try { userBusiness = IBOLookup.getServiceInstance(iwc, UserBusiness.class); } catch(RemoteException e) { LOGGER.log(Level.WARNING, "Error getting " + UserBusiness.class, e); } if (userBusiness == null) return null; AdvancedProperty info = new AdvancedProperty(handler.getName()); Email email = null; try { email = userBusiness.getUsersMainEmail(handler); } catch (RemoteException e) { LOGGER.log(Level.WARNING, "Error getting email for user: " + handler, e); } catch (NoEmailFoundException e) {} if (email != null) info.setValue(new StringBuilder("mailto:").append(email.getEmailAddress()).toString()); return info; } protected static final String LOCALIZATION_PREFIX = "case_board_viewer."; @Override public List<String> getCustomColumns(String uuid) { if (StringUtil.isEmpty(uuid)) return Collections.emptyList(); IWContext iwc = CoreUtil.getIWContext(); Object customColumns = iwc.getSessionAttribute(CasesBoardViewer.PARAMETER_CUSTOM_COLUMNS + uuid); if (customColumns instanceof List<?>) { @SuppressWarnings("unchecked") List<String> columns = (List<String>) customColumns; return columns; } return null; } @Override public Map<Integer, List<AdvancedProperty>> getColumns(String uuid) { Map<Integer, List<AdvancedProperty>> columns = new TreeMap<Integer, List<AdvancedProperty>>(); int index = 1; List<String> customColumns = getCustomColumns(uuid); if (ListUtil.isEmpty(customColumns)) { for (AdvancedProperty header: CasesBoardViewer.CASE_FIELDS) { if (index == 15) { columns.put(index, Arrays.asList( new AdvancedProperty(CasesBoardViewer.WORK_ITEM, localize(CasesBoardViewer.WORK_ITEM, "Work item")), new AdvancedProperty(CasesBoardViewer.ESTIMATED_COST, localize(CasesBoardViewer.ESTIMATED_COST, "Estimated cost")), new AdvancedProperty(CasesBoardViewer.BOARD_PROPOSAL_FOR_GRANT, localize(CasesBoardViewer.BOARD_PROPOSAL_FOR_GRANT, "Proposed funding")), new AdvancedProperty(CasesBoardViewer.BOARD_SUGGESTION, localize(CasesBoardViewer.BOARD_SUGGESTION.toLowerCase(), "Handler suggestions")), new AdvancedProperty(CasesBoardViewer.BOARD_DECISION, localize(CasesBoardViewer.BOARD_DECISION.toLowerCase(), "Board decision")) )); } else { columns.put(index, Arrays.asList(new AdvancedProperty(header.getId(), localize(new StringBuilder(LOCALIZATION_PREFIX).append(header.getId()).toString(), header.getValue())))); } index++; } columns.put(index, Arrays.asList(new AdvancedProperty(CaseHandlerAssignmentHandler.handlerUserIdVarName, localize(LOCALIZATION_PREFIX + CaseHandlerAssignmentHandler.handlerUserIdVarName, "Case handler")))); } else { String localized = null; IWContext iwc = CoreUtil.getIWContext();
IWResourceBundle bpmIWRB = iwc.getIWMainApplication().getBundle(IWBundleStarter.IW_BUNDLE_IDENTIFIER).getResourceBundle(iwc);
0
cheremin/scalarization
lab/src/main/java/ru/cheremin/scalarization/lab/plain/ReturnTupleScenario.java
[ "public abstract class AllocationScenario implements Scenario{\n\tpublic static final String SIZE_KEY = \"scenario.size\";\n\n\tpublic static final int SIZE = Integer.getInteger( SIZE_KEY, 16 );\n\n\tpublic abstract long run();\n\n\tprotected String additionalInfo() {\n\t\treturn \"\";\n\t}\n\n\n\t@Override\n\tpublic String toString() {\n\t\tfinal String result;\n\t\tif( SIZE < 0 ) {\n\t\t\tresult = getClass().getSimpleName();\n\t\t} else {\n\t\t\tresult = String.format( \"%s[SIZE:%d]\", getClass().getSimpleName(), SIZE );\n\t\t}\n\t\tfinal String additionalInfo = additionalInfo();\n\n\t\tif( additionalInfo.isEmpty() ) {\n\t\t\treturn result;\n\t\t} else {\n\t\t\treturn result + '[' + additionalInfo + ']';\n\t\t}\n\t}\n\n}", "public class ScenarioRun {\n\tprivate final List<JvmArg> jvmArgs;\n\n\tpublic ScenarioRun( final List<JvmArg> jvmArgs ) {\n\t\tthis.jvmArgs = Lists.newArrayList( jvmArgs );\n\t}\n\n\tpublic ScenarioRun( final JvmArg... jvmArgs ) {\n\t\tthis.jvmArgs = Lists.newArrayList( jvmArgs );\n\t}\n\n\tpublic List<JvmArg> getJvmArgs() {\n\t\treturn jvmArgs;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn jvmArgs.toString();\n\t}\n\n\t/* ====================== factory methods ==================================== */\n\n\t//TODO RC: ScenarioRunBuilder?\n\n\tpublic static List<ScenarioRun> withoutSpecificParameters() {\n\t\treturn Arrays.asList(\n\t\t\t\trunWith( AllocationScenario.SIZE_KEY, -1 )\n\t\t);\n\t}\n\n\tpublic static ScenarioRun runWith( final String propertyName,\n\t final Object propertyValue ) {\n\t\treturn new ScenarioRun(\n\t\t\t\tnew JvmArg.SystemProperty( propertyName, propertyValue.toString() )\n\t\t);\n\t}\n\n\tpublic static ScenarioRun runWith( final String propertyName1,\n\t final Object propertyValue1,\n\t final String propertyName2,\n\t final Object propertyValue2 ) {\n\t\treturn new ScenarioRun(\n\t\t\t\tnew JvmArg.SystemProperty( propertyName1, propertyValue1.toString() ),\n\t\t\t\tnew JvmArg.SystemProperty( propertyName2, propertyValue2.toString() )\n\t\t);\n\t}\n\n\tpublic static List<ScenarioRun> runWithAll( final String propertyName,\n\t final Object... propertyValues ) {\n\t\treturn Lists.newArrayList(\n\t\t\t\tLists.transform(\n\t\t\t\t\t\tallOf( propertyName, propertyValues ),\n\t\t\t\t\t\tnew Function<JvmArg, ScenarioRun>() {\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tpublic ScenarioRun apply( final JvmArg jvmArg ) {\n\t\t\t\t\t\t\t\treturn new ScenarioRun( jvmArg );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t)\n\t\t);\n\t}\n\n\tpublic static List<JvmArg> allOf(\n\t\t\tfinal String propertyName,\n\t\t\tfinal Object... values ) {\n\t\tfinal ArrayList<JvmArg> jvmArgs = new ArrayList<>();\n\t\tfor( final Object value : values ) {\n\t\t\tjvmArgs.add( new JvmArg.SystemProperty( propertyName, String.valueOf( value ) ) );\n\t\t}\n\t\treturn jvmArgs;\n\t}\n\n\tpublic static List<ScenarioRun> crossJoin(\n\t\t\tfinal List<? extends JvmArg> jvmArgsList1,\n\t\t\tfinal List<? extends JvmArg> jvmArgsList2 ) {\n\t\tfinal ArrayList<ScenarioRun> runs = new ArrayList<>();\n\n\t\tfor( final JvmArg jvmArg1 : jvmArgsList1 ) {\n\t\t\tfor( final JvmArg jvmArg2 : jvmArgsList2 ) {\n\t\t\t\truns.add( new ScenarioRun( jvmArg1, jvmArg2 ) );\n\t\t\t}\n\t\t}\n\n\t\treturn runs;\n\t}\n\n\tpublic static List<ScenarioRun> crossJoin(\n\t\t\tfinal List<? extends JvmArg> jvmArgsList1,\n\t\t\tfinal List<? extends JvmArg> jvmArgsList2,\n\t\t\tfinal List<? extends JvmArg> jvmArgsList3 ) {\n\t\tfinal ArrayList<ScenarioRun> runs = new ArrayList<>();\n\n\t\tfor( final JvmArg jvmArg1 : jvmArgsList1 ) {\n\t\t\tfor( final JvmArg jvmArg2 : jvmArgsList2 ) {\n\t\t\t\tfor( final JvmArg jvmArg3 : jvmArgsList3 ) {\n\t\t\t\t\truns.add( new ScenarioRun( jvmArg1, jvmArg2, jvmArg3 ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn runs;\n\t}\n\n\tpublic static List<ScenarioRun> crossJoin(\n\t\t\tfinal List<? extends JvmArg> jvmArgsList1,\n\t\t\tfinal List<? extends JvmArg> jvmArgsList2,\n\t\t\tfinal List<? extends JvmArg> jvmArgsList3,\n\t\t\tfinal List<? extends JvmArg> jvmArgsList4 ) {\n\t\tfinal ArrayList<ScenarioRun> runs = new ArrayList<>();\n\n\t\tfor( final JvmArg jvmArg1 : jvmArgsList1 ) {\n\t\t\tfor( final JvmArg jvmArg2 : jvmArgsList2 ) {\n\t\t\t\tfor( final JvmArg jvmArg3 : jvmArgsList3 ) {\n\t\t\t\t\tfor( final JvmArg jvmArg4 : jvmArgsList4 ) {\n\t\t\t\t\t\truns.add( new ScenarioRun( jvmArg1, jvmArg2, jvmArg3, jvmArg4 ) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn runs;\n\t}\n\n\n}", "public static class Pool<T> {\n\tprivate final T[] items;\n\n\tpublic Pool( final T[] items ) {\n\t\tcheckArgument( items != null, \"items can't be null\" );\n\t\tcheckArgument( items.length > 0, \"items can't be empty\" );\n\t\tthis.items = items;\n\t}\n\n\tprivate int index = 0;\n\n\tpublic T next() {\n\t\tindex = ( index + 1 ) % items.length;\n\t\treturn items[index];\n\t}\n}", "public static List<ScenarioRun> runWithAll( final String propertyName,\n final Object... propertyValues ) {\n\treturn Lists.newArrayList(\n\t\t\tLists.transform(\n\t\t\t\t\tallOf( propertyName, propertyValues ),\n\t\t\t\t\tnew Function<JvmArg, ScenarioRun>() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic ScenarioRun apply( final JvmArg jvmArg ) {\n\t\t\t\t\t\t\treturn new ScenarioRun( jvmArg );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t);\n}", "public static Pool<String> randomStringsPool( final int universeSize ) {\n\tfinal String[] strings = generateStringArray( universeSize );\n\treturn poolOf( strings );\n}" ]
import java.util.*; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import ru.cheremin.scalarization.AllocationScenario; import ru.cheremin.scalarization.ScenarioRun; import ru.cheremin.scalarization.infra.ScenarioRunArgs; import ru.cheremin.scalarization.lab.Utils.Pool; import static ru.cheremin.scalarization.ScenarioRun.runWithAll; import static ru.cheremin.scalarization.lab.Utils.randomStringsPool;
package ru.cheremin.scalarization.lab.plain; /** * Check pattern: method with multiple return values wrapped in composite object. * <p/> * For both 1.7 and 1.8: * Simple one-type tuples are successfully scalarized with 1.7/1.8, even being casted * to generic interface. * <p/> * Mixed type tuples are not scalarized. * <p/> * Single or mixed types with nulls are not scalarized * * @author ruslan * created 09/02/16 at 21:41 */ public class ReturnTupleScenario extends AllocationScenario { public static final String TUPLE_TYPE_KEY = "scenario.tuple-type"; private static final TupleType TUPLE_TYPE = TupleType.valueOf( System.getProperty( TUPLE_TYPE_KEY, TupleType.IMMUTABLE_PAIR.name() ) );
private final Pool<String> pool = randomStringsPool( 1024 );
4
oSoc14/Artoria
app/src/main/java/be/artoria/belfortapp/activities/MainActivity.java
[ "public class DescriptionRow {\n public final Drawable imageDescription;\n public final String description;\n\n public DescriptionRow(Drawable imageDescription, String description){\n this.imageDescription = imageDescription;\n this.description = description;\n }\n}", "public class MainAdapter extends ArrayAdapter<DescriptionRow> {\n Context context;\n\n public MainAdapter(Context context, int resourceId,\n List<DescriptionRow> items) {\n super(context, resourceId, items);\n this.context = context;\n }\n\n /*private view holder class*/\n private class ViewHolder {\n ImageView imageView;\n TextView txtDesc;\n }\n\n public View getView(int position, View convertView, ViewGroup parent) {\n final ViewHolder holder;\n final DescriptionRow rowItem = getItem(position);\n\n final LayoutInflater mInflater = (LayoutInflater) context\n .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);\n if (convertView == null) {\n convertView = mInflater.inflate(R.layout.main_list_item, null);\n holder = new ViewHolder();\n holder.txtDesc = (TextView) convertView.findViewById(R.id.main_desc);\n holder.imageView = (ImageView)convertView.findViewById(R.id.main_icon);\n convertView.setTag(holder);\n } else {\n holder = (ViewHolder) convertView.getTag();\n }\n\n holder.txtDesc.setText(rowItem.description);\n holder.imageView.setImageDrawable(rowItem.imageDescription);\n\n return convertView;\n }\n}", "public class MapFragment extends android.support.v4.app.Fragment {\n public static final int DEFAULT_ZOOM = 17;\n private String MAP_QUEST_API_KEY; //TODO request key for Artoria, this key now is 'licensed' to Dieter Beelaert\n public static final String LANG_ENG = \"en_GB\";\n public static final String LANG_NL = \"nl_BE\";\n public static final String LANG_FR = \"fr_FR\";\n private MapView mapView;\n private boolean showsMap = true;\n private boolean firstStart = true; //to check when the mapview is loaded for the first time (this is for the ViewTreeObserver)\n public boolean isFullscreen = true;\n\n // TODO: Rename and change types and number of parameters\n public static MapFragment newInstance() {\n MapFragment fragment = new MapFragment();\n return fragment;\n }\n\n public MapFragment(){\n // Required empty public constructor\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n super.onCreateView(inflater,container,savedInstanceState);\n return inflater.inflate(R.layout.fragment_map, container, false);\n }\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n mapView = (MapView)getView().findViewById(R.id.mapview);\n MAP_QUEST_API_KEY = getResources().getString(R.string.map_quest_api_key);\n initGUI();\n }\n\n private void initGUI(){\n /*Setup map and draw route*/\n mapView.setTileSource(TileSourceFactory.MAPQUESTOSM);\n mapView.setBuiltInZoomControls(true);\n final MapController mapCtrl = (MapController) mapView.getController();\n mapCtrl.setZoom(DEFAULT_ZOOM);\n calculateRoute();\n /*Initially show map*/\n toggleMap(true);\n\n final Button btnTogglemap = (Button)getView().findViewById(R.id.btnRouteDesc);\n btnTogglemap.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n showsMap = !showsMap;\n toggleMap(showsMap);\n if(showsMap){\n btnTogglemap.setText(getResources().getString(R.string.route_desc));\n }else{\n btnTogglemap.setText(getResources().getString(R.string.show_map));\n }\n }\n });\n\n final ImageButton btnFullScreen = (ImageButton)getView().findViewById(R.id.btnFullScreen);\n btnFullScreen.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n Intent i = new Intent(getActivity(),MapActivity.class);\n getActivity().startActivity(i);\n }\n });\n\n if(!isFullscreen){\n btnTogglemap.setVisibility(View.GONE);\n }else{\n btnFullScreen.setVisibility(View.GONE);\n }\n\n /*Set center of map to current location or Belfry*/\n final ViewTreeObserver vto = mapView.getViewTreeObserver();\n vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n @Override\n public void onGlobalLayout() {\n if(firstStart){\n mapView.getController().setCenter(getCurrentLocation());\n firstStart = false;\n }\n\n }\n });\n\n drawMarkers();\n }\n\n private OverlayItem getOverlayItemFromPOI(POI poi,Drawable icon){\n final ArtoriaOverlayItem overlayItem = new ArtoriaOverlayItem(poi);\n if(icon != null) {\n overlayItem.setMarker(icon);\n }\n return overlayItem;\n }\n\n\n /* Transfer the route to an ArrayList of GeoPoint objects */\n private ArrayList<GeoPoint> getGeoPointsFromRoute(){\n final ArrayList<GeoPoint>toReturn = new ArrayList<GeoPoint>();\n toReturn.add(getCurrentLocation());\n for(final POI poi : RouteManager.getInstance().getWaypoints()){\n toReturn.add(new GeoPoint(Double.parseDouble(poi.lat),Double.parseDouble(poi.lon)));\n }\n return toReturn;\n }\n\n /*Gets the route from the web and draws it on the map when done*/\n private class RouteCalcTask extends AsyncTask {\n\n @Override\n protected Road doInBackground(Object[] objects) {\n final RoadManager roadManager = new MapQuestRoadManager(MAP_QUEST_API_KEY);\n //RoadManager roadManager = new OSRMRoadManager();\n roadManager.addRequestOption(\"routeType=pedestrian\");\n final String lang;\n switch(DataManager.getInstance().getCurrentLanguage()){\n case ENGLISH:lang = LANG_ENG; break;\n case FRENCH: lang = LANG_FR; break;\n case DUTCH:\n default: lang = LANG_NL;\n }\n roadManager.addRequestOption(\"locale=\"+lang ); //display the directions in the selected language\n roadManager.addRequestOption(\"unit=k\"); //display the distance in kilometers\n final Road road = roadManager.getRoad(getGeoPointsFromRoute());\n return road;\n }\n\n @Override\n protected void onPostExecute(Object result){\n mapView.getOverlays().clear();\n drawMarkers();\n final Road road = (Road) result;\n final Polyline routeOverlay = RoadManager.buildRoadOverlay(road, getActivity());\n initRouteInstructions(road);\n final TextView lblDistance = (TextView)getView().findViewById(R.id.lblDistance);\n lblDistance.setText(String.format(\"%.2f\", road.mLength) + \"km\");\n final TextView lblTime = (TextView)getView().findViewById(R.id.lblTime);\n lblTime.setText(String.format(\"%.0f\",(road.mDuration / 60)) + \" \" + getResources().getString(R.string.minutes)); //set estimated time in minutes\n mapView.getOverlays().add(routeOverlay);\n mapView.invalidate();\n }\n }\n\n private void initRouteInstructions(Road road){\n if(road != null && road.mNodes != null) {\n final ListView lstRouteDesc = (ListView)getView().findViewById(R.id.lstRouteDesc);\n final List<DescriptionRow> descriptions = new ArrayList<DescriptionRow>();\n int waypoint = 0;\n for(int i = 0; i < road.mNodes.size(); i++){\n final RoadNode node = road.mNodes.get(i);\n String instructions = node.mInstructions;\n if(node.mInstructions.toUpperCase().contains(getResources().getString(R.string.destination).toUpperCase())){\n instructions = RouteManager.getInstance().getWaypoints().get(waypoint).getName();\n waypoint++;\n }\n descriptions.add(new DescriptionRow(getIconForManeuver(node.mManeuverType),instructions));\n }\n lstRouteDesc.setAdapter(new RouteDescAdapter(getActivity(),android.R.layout.simple_list_item_1,descriptions));\n }\n }\n\n /*Get the correct icon for each maneuver*/\n private Drawable getIconForManeuver(int maneuver){\n int toReturn = R.drawable.ic_empty;\n switch(maneuver){\n case ManeuverType.NONE:\n case ManeuverType.TRANSIT_TAKE:\n case ManeuverType.TRANSIT_TRANSFER:\n case ManeuverType.TRANSIT_ENTER:\n case ManeuverType.TRANSIT_EXIT:\n case ManeuverType.TRANSIT_REMAIN_ON:\n case ManeuverType.ENTERING:\n case ManeuverType.BECOMES: toReturn = R.drawable.ic_empty;\n break;\n\n case ManeuverType.STRAIGHT:\n case ManeuverType.MERGE_STRAIGHT:\n case ManeuverType.RAMP_STRAIGHT:\n case ManeuverType.STAY_STRAIGHT: toReturn = R.drawable.ic_continue;\n break;\n\n case ManeuverType.ROUNDABOUT1:\n case ManeuverType.ROUNDABOUT2:\n case ManeuverType.ROUNDABOUT3:\n case ManeuverType.ROUNDABOUT4:\n case ManeuverType.ROUNDABOUT5:\n case ManeuverType.ROUNDABOUT6:\n case ManeuverType.ROUNDABOUT7:\n case ManeuverType.ROUNDABOUT8: toReturn = R.drawable.ic_roundabout;\n break;\n\n case ManeuverType.DESTINATION:\n case ManeuverType.DESTINATION_RIGHT:\n case ManeuverType.DESTINATION_LEFT: toReturn = R.drawable.ic_arrived;\n break;\n\n case ManeuverType.SLIGHT_LEFT:\n case ManeuverType.EXIT_LEFT:\n case ManeuverType.STAY_LEFT:\n case ManeuverType.MERGE_LEFT: toReturn = R.drawable.ic_slight_left;\n break;\n\n case ManeuverType.SLIGHT_RIGHT:\n case ManeuverType.EXIT_RIGHT:\n case ManeuverType.STAY_RIGHT:\n case ManeuverType.MERGE_RIGHT: toReturn = R.drawable.ic_slight_right;\n break;\n\n case ManeuverType.UTURN:\n case ManeuverType.UTURN_LEFT:\n case ManeuverType.UTURN_RIGHT: toReturn = R.drawable.ic_u_turn;\n break;\n\n case ManeuverType.RAMP_LEFT:\n case ManeuverType.LEFT: toReturn = R.drawable.ic_turn_left;\n break;\n\n case ManeuverType.RAMP_RIGHT:\n case ManeuverType.RIGHT: toReturn = R.drawable.ic_turn_right;\n break;\n\n case ManeuverType.SHARP_LEFT: toReturn = R.drawable.ic_sharp_left;\n break;\n\n case ManeuverType.SHARP_RIGHT : toReturn = R.drawable.ic_sharp_right;\n break;\n\n }\n return getResources().getDrawable(toReturn);\n }\n\n private void toggleMap(boolean showMap){\n final RelativeLayout mapview = (RelativeLayout)getView().findViewById(R.id.mapContainer);\n mapview.setVisibility(showMap ? View.VISIBLE : View.GONE);\n final ListView cntDesc = (ListView)getView().findViewById(R.id.lstRouteDesc);\n cntDesc.setVisibility( showMap ? View.GONE : View.VISIBLE);\n }\n\n private GeoPoint getCurrentLocation(){\n // Get the location manager\n final LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);\n // Define the criteria how to select the locatioin provider -> use\n // default\n final Criteria criteria = new Criteria();\n final String provider = locationManager.getBestProvider(criteria, false);\n final Location loc = locationManager.getLastKnownLocation(provider);\n\n if(loc != null){\n return new GeoPoint(loc.getLatitude(),loc.getLongitude());\n }else{\n return new GeoPoint(DataManager.BELFORT_LAT,DataManager.BELFORT_LON);\n }\n }\n\n public void calculateRoute(){\n final ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);\n final NetworkInfo info = cm.getActiveNetworkInfo();\n if (info != null) {\n if (info.isConnected()) {\n new RouteCalcTask().execute();\n }else{\n Toast.makeText(getActivity(), \"Please check your wireless connection and try again.\", Toast.LENGTH_SHORT).show();\n }\n }\n else {\n Toast.makeText(getActivity(), \"Please check your wireless connection and try again.\", Toast.LENGTH_SHORT).show();\n }\n }\n\n private void drawMarkers(){\n /*Add markers on the map*/\n final ItemizedOverlayWithFocus<OverlayItem> overlay;\n final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();\n final POI belfort = new POI();\n belfort.id = -1; //used to disable the clickhandler for this poi\n belfort.ENG_name = \"Belfry\";\n belfort.ENG_description = \"\";\n belfort.NL_name = \"Belfort\";\n belfort.NL_description = \"\";\n belfort.lat = DataManager.BELFORT_LAT +\"\";\n belfort.lon = DataManager.BELFORT_LON +\"\";\n final OverlayItem overlayItem = getOverlayItemFromPOI(belfort,getResources().getDrawable(R.drawable.castle));\n items.add(overlayItem);\n\n for(POI poi : RouteManager.getInstance().getWaypoints()){\n final OverlayItem item = getOverlayItemFromPOI(poi,null);\n items.add(item);\n }\n\n overlay = new ItemizedOverlayWithFocus<OverlayItem>(getActivity().getApplicationContext(), items,\n new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {\n\n @Override\n public boolean onItemSingleTapUp(final int index, final OverlayItem item) {\n final ArtoriaOverlayItem overlayItem = (ArtoriaOverlayItem)item;\n final POI selectedItem = ((ArtoriaOverlayItem) item).poi;\n if(selectedItem.id != -1) {\n Intent i = MonumentDetailActivity.newIntent(getActivity(), selectedItem.id, false);\n startActivity(i);\n }\n return true; // We 'handled' this event.\n }\n\n @Override\n public boolean onItemLongPress(final int index, final OverlayItem item) {\n return false;\n }\n });\n\n mapView.getOverlays().add(overlay);\n mapView.invalidate();\n }\n\n}", "public class MixView extends Activity implements SensorEventListener, OnTouchListener {\n\n\tprivate CameraSurface camScreen;\n\tprivate AugmentedView augScreen;\n\n\tprivate boolean isInited;\n\tprivate static PaintScreen dWindow;\n\tprivate static DataView dataView;\n\tprivate boolean fError;\n\n\t//----------\n private MixViewDataHolder mixViewData ;\n\t\n\t// TAG for logging\n\tpublic static final String TAG = \"Mixare\";\n private static final String GPS_PACKAGE_NAME = \"com.eclipsim.gpsstatus2\";\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\ttry {\n\t\t\t\t\t\t\n\t\t\thandleIntent(getIntent());\n\n\t\t\tfinal PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);\n\n\t\t\tgetMixViewData().setmWakeLock(pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, \"My Tag\"));\n\n\t\t\tkillOnError();\n\t\t\trequestWindowFeature(Window.FEATURE_NO_TITLE);\n\n\t\t\tmaintainCamera();\n\t\t\tmaintainAugmentR();\n\n\t\t\tif (!isInited) {\n\t\t\t\tsetdWindow(new PaintScreen());\n\t\t\t\tsetDataView(new DataView(getMixViewData().getMixContext()));\n\n\t\t\t\t/* set the radius in data view to the last selected by the user */\n\t\t\t\tsetZoomLevel();\n\t\t\t\tisInited = true;\n\t\t\t}\n\n\t\t\t/*check if the application is launched for the first time*/\n\t\t\tif(PrefUtils.isFirstPanoramaTime()){\n PrefUtils.setPanoramaNotFirstTime();\n final AlertDialog.Builder aDBuilder = new AlertDialog.Builder(this);\n aDBuilder.setTitle(R.string.calibrate_title);\n aDBuilder.setMessage(R.string.calibrate);\n aDBuilder.setPositiveButton(\"OK\", null);\n aDBuilder.setNegativeButton(R.string.show_me_how, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n try {\n startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(\"market://details?id=\" + GPS_PACKAGE_NAME)));\n } catch (android.content.ActivityNotFoundException anfe) {\n startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://play.google.com/store/apps/details?id=\" + GPS_PACKAGE_NAME)));\n }\n }\n });\n aDBuilder.show();\n\t\t\t}\n else {\n //Toast.makeText(this,\"Calibrate!\",Toast.LENGTH_SHORT).show();\n }\n /* Who does this?!? */\n\t\t} catch (Exception ex) {\n ex.printStackTrace();\n Log.e(\"bad\",\"time#1\");\n\t\t\tdoError(ex);\n\t\t}\n\t}\n\n\tpublic MixViewDataHolder getMixViewData() {\n\t\tif (mixViewData==null){\n\t\t\tmixViewData = new MixViewDataHolder(new MixContext(this));\n\t\t}\n\t\treturn mixViewData;\n\t}\n\n\t@Override\n\tprotected void onPause() {\n\t\tsuper.onPause();\n\n\t\ttry {\n\t\t\tthis.getMixViewData().getmWakeLock().release();\n\n\t\t\ttry {\n\t\t\t\tgetMixViewData().getSensorMgr().unregisterListener(this,\n\t\t\t\t\t\tgetMixViewData().getSensorGrav());\n\t\t\t\tgetMixViewData().getSensorMgr().unregisterListener(this,\n\t\t\t\t\t\tgetMixViewData().getSensorMag());\n\t\t\t\tgetMixViewData().setSensorMgr(null);\n\t\t\t\t\n\t\t\t\tgetMixViewData().getMixContext().getLocationFinder().switchOff();\n\t\t\t\tgetMixViewData().getMixContext().getDownloadManager().switchOff();\n\n\t\t\t\tif (getDataView() != null) {\n\t\t\t\t\t//getDataView().cancelRefreshTimer();\n\t\t\t\t}\n\t\t\t} catch (Exception ignore) {\n\t\t\t}\n\n\t\t\tif (fError) {\n\t\t\t\tfinish();\n\t\t\t}\n\t\t} catch (Exception ex) {\n\t\t\tdoError(ex);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * Mixare - Receives results from other launched activities\n\t * Base on the result returned, it either refreshes screen or not.\n\t * Default value for refreshing is false\n\t */\n\tprotected void onActivityResult(final int requestCode,\n\t\t\tfinal int resultCode, Intent data) {\n\t\tLog.d(TAG + \" WorkFlow\", \"MixView - onActivityResult Called\");\n\t\t// check if the returned is request to refresh screen (setting might be\n\t\t// changed)\n\t\ttry {\n\t\t\tif (data.getBooleanExtra(\"RefreshScreen\", false)) {\n\t\t\t\tLog.d(TAG + \" WorkFlow\",\n\t\t\t\t\t\t\"MixView - Received Refresh Screen Request .. about to refresh\");\n\t\t\t\trepaint();\n\t\t\t\trefreshDownload();\n\t\t\t}\n\n\t\t} catch (Exception ex) {\n\t\t\t// do nothing do to mix of return results.\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onResume() {\n\t\tsuper.onResume();\n\n\t\ttry {\n\t\t\tthis.getMixViewData().getmWakeLock().acquire();\n\n\t\t\tkillOnError();\n\t\t\tgetMixViewData().getMixContext().doResume(this);\n\n\t\t\trepaint();\n\t\t\tgetDataView().doStart();\n\t\t\tgetDataView().clearEvents();\n\n\t\t\tgetMixViewData().getMixContext().getDataSourceManager().refreshDataSources();\n\n\t\t\tfloat angleX, angleY;\n\n\t\t\tint marker_orientation = -90;\n\n\t\t\tint rotation = Compatibility.getRotation(this);\n\n\t\t\t// display text from left to right and keep it horizontal\n\t\t\tangleX = (float) Math.toRadians(marker_orientation);\n\t\t\tgetMixViewData().getM1().set(1f, 0f, 0f, 0f,\n\t\t\t\t\t(float) FloatMath.cos(angleX),\n\t\t\t\t\t(float) -FloatMath.sin(angleX), 0f,\n\t\t\t\t\t(float) FloatMath.sin(angleX),\n\t\t\t\t\t(float) FloatMath.cos(angleX));\n\t\t\tangleX = (float) Math.toRadians(marker_orientation);\n\t\t\tangleY = (float) Math.toRadians(marker_orientation);\n\t\t\tif (rotation == 1) {\n\t\t\t\tgetMixViewData().getM2().set(1f, 0f, 0f, 0f,\n\t\t\t\t\t\t(float) FloatMath.cos(angleX),\n\t\t\t\t\t\t(float) -FloatMath.sin(angleX), 0f,\n\t\t\t\t\t\t(float) FloatMath.sin(angleX),\n\t\t\t\t\t\t(float) FloatMath.cos(angleX));\n\t\t\t\tgetMixViewData().getM3().set((float) FloatMath.cos(angleY), 0f,\n\t\t\t\t\t\t(float) FloatMath.sin(angleY), 0f, 1f, 0f,\n\t\t\t\t\t\t(float) -FloatMath.sin(angleY), 0f,\n\t\t\t\t\t\t(float) FloatMath.cos(angleY));\n\t\t\t} else {\n\t\t\t\tgetMixViewData().getM2().set((float) FloatMath.cos(angleX), 0f,\n\t\t\t\t\t\t(float) FloatMath.sin(angleX), 0f, 1f, 0f,\n\t\t\t\t\t\t(float) -FloatMath.sin(angleX), 0f,\n\t\t\t\t\t\t(float) FloatMath.cos(angleX));\n\t\t\t\tgetMixViewData().getM3().set(1f, 0f, 0f, 0f,\n\t\t\t\t\t\t(float) FloatMath.cos(angleY),\n\t\t\t\t\t\t(float) -FloatMath.sin(angleY), 0f,\n\t\t\t\t\t\t(float) FloatMath.sin(angleY),\n\t\t\t\t\t\t(float) FloatMath.cos(angleY));\n\n\t\t\t}\n\n\t\t\tgetMixViewData().getM4().toIdentity();\n\n\t\t\tfor (int i = 0; i < getMixViewData().getHistR().length; i++) {\n\t\t\t\tgetMixViewData().getHistR()[i] = new Matrix();\n\t\t\t}\n\n\t\t\tgetMixViewData()\n\t\t\t\t\t.setSensorMgr((SensorManager) getSystemService(SENSOR_SERVICE));\n\n\t\t\tgetMixViewData().setSensors(getMixViewData().getSensorMgr().getSensorList(\n\t\t\t\t\tSensor.TYPE_ACCELEROMETER));\n\t\t\tif (getMixViewData().getSensors().size() > 0) {\n\t\t\t\tgetMixViewData().setSensorGrav(getMixViewData().getSensors().get(0));\n\t\t\t}\n\n\t\t\tgetMixViewData().setSensors(getMixViewData().getSensorMgr().getSensorList(\n\t\t\t\t\tSensor.TYPE_MAGNETIC_FIELD));\n\t\t\tif (getMixViewData().getSensors().size() > 0) {\n\t\t\t\tgetMixViewData().setSensorMag(getMixViewData().getSensors().get(0));\n\t\t\t}\n\n\t\t\tgetMixViewData().getSensorMgr().registerListener(this,\n\t\t\t\t\tgetMixViewData().getSensorGrav(), SENSOR_DELAY_GAME);\n\t\t\tgetMixViewData().getSensorMgr().registerListener(this,\n\t\t\t\t\tgetMixViewData().getSensorMag(), SENSOR_DELAY_GAME);\n\n\t\t\ttry {\n\t\t\t\tGeomagneticField gmf = getMixViewData().getMixContext().getLocationFinder().getGeomagneticField(); \n\t\t\t\tangleY = (float) Math.toRadians(-gmf.getDeclination());\n\t\t\t\tgetMixViewData().getM4().set((float) FloatMath.cos(angleY), 0f,\n\t\t\t\t\t\t(float) FloatMath.sin(angleY), 0f, 1f, 0f,\n\t\t\t\t\t\t(float) -FloatMath.sin(angleY), 0f,\n\t\t\t\t\t\t(float) FloatMath.cos(angleY));\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLog.d(\"org/mixare\", \"GPS Initialize Error\", ex);\n\t\t\t}\n\n\t\t\tgetMixViewData().getMixContext().getDownloadManager().switchOn();\n\t\t\tgetMixViewData().getMixContext().getLocationFinder().switchOn();\n\t\t} catch (Exception ex) {\n\t\t\tdoError(ex);\n\t\t\ttry {\n\t\t\t\tif (getMixViewData().getSensorMgr() != null) {\n\t\t\t\t\tgetMixViewData().getSensorMgr().unregisterListener(this,\n\t\t\t\t\t\t\tgetMixViewData().getSensorGrav());\n\t\t\t\t\tgetMixViewData().getSensorMgr().unregisterListener(this,\n\t\t\t\t\t\t\tgetMixViewData().getSensorMag());\n\t\t\t\t\tgetMixViewData().setSensorMgr(null);\n\t\t\t\t}\n\n\t\t\t\tif (getMixViewData().getMixContext() != null) {\n\t\t\t\t\tgetMixViewData().getMixContext().getLocationFinder().switchOff();\n\t\t\t\t\tgetMixViewData().getMixContext().getDownloadManager().switchOff();\n\t\t\t\t}\n\t\t\t} catch (Exception ignore) {\n\t\t\t}\n\t\t}\n\n\t\tLog.d(\"-------------------------------------------\", \"resume\");\n\t\tif (getDataView().isFrozen()\n && getMixViewData().getSearchNotificationTxt() == null) {\n\t\t\tgetMixViewData().setSearchNotificationTxt(new TextView(this));\n\t\t\tgetMixViewData().getSearchNotificationTxt().setWidth(\n\t\t\t\t\tgetdWindow().getWidth());\n\t\t\tgetMixViewData().getSearchNotificationTxt().setPadding(10, 2, 0, 0);\n\t\t\tgetMixViewData().getSearchNotificationTxt().setText(\"REMOVE ME\");\n\n\t\t\tgetMixViewData().getSearchNotificationTxt().setBackgroundColor(\n\t\t\t\t\tColor.DKGRAY);\n\t\t\tgetMixViewData().getSearchNotificationTxt().setTextColor(Color.WHITE);\n\n\t\t\tgetMixViewData().getSearchNotificationTxt().setOnTouchListener(this);\n\t\t\taddContentView(getMixViewData().getSearchNotificationTxt(),\n\t\t\t\t\tnew LayoutParams(LayoutParams.FILL_PARENT,\n\t\t\t\t\t\t\tLayoutParams.WRAP_CONTENT));\n\t\t} else if (!getDataView().isFrozen()\n\t\t\t\t&& getMixViewData().getSearchNotificationTxt() != null) {\n\t\t\tgetMixViewData().getSearchNotificationTxt().setVisibility(View.GONE);\n\t\t\tgetMixViewData().setSearchNotificationTxt(null);\n\t\t}\n\t}\n\t\n\t/**\n\t * {@inheritDoc}\n\t * Customize Activity after switching back to it.\n\t * Currently it maintain and ensures view creation.\n\t */\n\tprotected void onRestart (){\n\t\tsuper.onRestart();\n\t\tmaintainCamera();\n\t\tmaintainAugmentR();\n\t}\n\t\n\t/* ********* Operators ***********/ \n\n\tpublic void repaint() {\n\t\t//clear stored data\n\t\tgetDataView().clearEvents();\n\t\tsetDataView(null); //It's smelly code, but enforce garbage collector \n\t\t\t\t\t\t\t//to release data.\n\t\tsetDataView(new DataView(mixViewData.getMixContext()));\n\t\tsetdWindow(new PaintScreen());\n\t\t//setZoomLevel(); //@TODO Caller has to set the zoom. This function repaints only.\n\t}\n\t\n\t/**\n\t * Checks camScreen, if it does not exist, it creates one.\n\t */\n\tprivate void maintainCamera() {\n\t\tif (camScreen == null){\n\t\tcamScreen = new CameraSurface(this);\n\t\t}\n\t\tsetContentView(camScreen);\n\t}\n\t\n\t/**\n\t * Checks augScreen, if it does not exist, it creates one.\n\t */\n\tprivate void maintainAugmentR() {\n\t\tif (augScreen == null ){\n\t\taugScreen = new AugmentedView(this);\n\t\t}\n\t\taddContentView(augScreen, new LayoutParams(\n\t\t\t\tLayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\n\t}\n\t\n\n\t/**\n\t * Refreshes Download \n\t * TODO refresh downloads\n\t */\n\tprivate void refreshDownload(){\n DataManager.refresh();\n\t}\n\t\n\tpublic void refresh(){\n\t\t//dataView.refresh();\n\t}\n\n\t/* ******** Operators - Sensors ****** */\n\n\tpublic void onSensorChanged(SensorEvent evt) {\n \n\t\ttry {\n\n\t\t\tif (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {\n\t\t\t\tgetMixViewData().getGrav()[0] = evt.values[0];\n\t\t\t\tgetMixViewData().getGrav()[1] = evt.values[1];\n\t\t\t\tgetMixViewData().getGrav()[2] = evt.values[2];\n\n\t\t\t\taugScreen.postInvalidate();\n\t\t\t} else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {\n\t\t\t\tgetMixViewData().getMag()[0] = evt.values[0];\n\t\t\t\tgetMixViewData().getMag()[1] = evt.values[1];\n\t\t\t\tgetMixViewData().getMag()[2] = evt.values[2];\n\n\t\t\t\taugScreen.postInvalidate();\n\t\t\t}\n\n\t\t\tSensorManager.getRotationMatrix(getMixViewData().getRTmp(),\n\t\t\t\t\tgetMixViewData().getI(), getMixViewData().getGrav(),\n\t\t\t\t\tgetMixViewData().getMag());\n\n\t\t\tint rotation = Compatibility.getRotation(this);\n\n\t\t\tif (rotation == 1) {\n\t\t\t\tSensorManager.remapCoordinateSystem(getMixViewData().getRTmp(),\n\t\t\t\t\t\tSensorManager.AXIS_X, SensorManager.AXIS_MINUS_Z,\n\t\t\t\t\t\tgetMixViewData().getRot());\n\t\t\t} else {\n\t\t\t\tSensorManager.remapCoordinateSystem(getMixViewData().getRTmp(),\n\t\t\t\t\t\tSensorManager.AXIS_Y, SensorManager.AXIS_MINUS_Z,\n\t\t\t\t\t\tgetMixViewData().getRot());\n\t\t\t}\n\t\t\tgetMixViewData().getTempR().set(getMixViewData().getRot()[0],\n\t\t\t\t\tgetMixViewData().getRot()[1], getMixViewData().getRot()[2],\n\t\t\t\t\tgetMixViewData().getRot()[3], getMixViewData().getRot()[4],\n\t\t\t\t\tgetMixViewData().getRot()[5], getMixViewData().getRot()[6],\n\t\t\t\t\tgetMixViewData().getRot()[7], getMixViewData().getRot()[8]);\n\n\t\t\tgetMixViewData().getFinalR().toIdentity();\n\t\t\tgetMixViewData().getFinalR().prod(getMixViewData().getM4());\n\t\t\tgetMixViewData().getFinalR().prod(getMixViewData().getM1());\n\t\t\tgetMixViewData().getFinalR().prod(getMixViewData().getTempR());\n\t\t\tgetMixViewData().getFinalR().prod(getMixViewData().getM3());\n\t\t\tgetMixViewData().getFinalR().prod(getMixViewData().getM2());\n\t\t\tgetMixViewData().getFinalR().invert();\n\n\t\t\tgetMixViewData().getHistR()[getMixViewData().getrHistIdx()].set(getMixViewData()\n\t\t\t\t\t.getFinalR());\n\t\t\tgetMixViewData().setrHistIdx(getMixViewData().getrHistIdx() + 1);\n\t\t\tif (getMixViewData().getrHistIdx() >= getMixViewData().getHistR().length)\n\t\t\t\tgetMixViewData().setrHistIdx(0);\n\n\t\t\tgetMixViewData().getSmoothR().set(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);\n\t\t\tfor (int i = 0; i < getMixViewData().getHistR().length; i++) {\n\t\t\t\tgetMixViewData().getSmoothR().add(getMixViewData().getHistR()[i]);\n\t\t\t}\n\t\t\tgetMixViewData().getSmoothR().mult(\n\t\t\t\t\t1 / (float) getMixViewData().getHistR().length);\n\n\t\t\tgetMixViewData().getMixContext().updateSmoothRotation(getMixViewData().getSmoothR());\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean onTouchEvent(MotionEvent me) {\n \n\t\ttry {\n\t\t\tkillOnError();\n\n\t\t\tfloat xPress = me.getX();\n\t\t\tfloat yPress = me.getY();\n\t\t\tif (me.getAction() == MotionEvent.ACTION_UP) {\n\t\t\t\tgetDataView().clickEvent(xPress, yPress);\n\t\t\t}//TODO add gesture events (low)\n\n\t\t\treturn true;\n\t\t} catch (Exception ex) {\n\t\t\t// doError(ex);\n\t\t\tex.printStackTrace();\n\t\t\treturn super.onTouchEvent(me);\n\t\t}\n\t}\n\n @Override\n public void onBackPressed(){\n super.onBackPressed();\n final Intent intent = new Intent(this, MainActivity.class);\n startActivity(intent);\n }\n\n\t@Override\n\tpublic boolean onKeyDown(int keyCode, KeyEvent event) {\n\n if (keyCode == KeyEvent.KEYCODE_BACK) {\n onBackPressed();\n return true;\n\n }\n return false;\n }\n\n\tpublic void onAccuracyChanged(Sensor sensor, int accuracy) {\n\t\tif (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD\n\t\t\t\t&& accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE\n\t\t\t\t&& getMixViewData().getCompassErrorDisplayed() == 0) {\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tToast.makeText(getMixViewData().getMixContext(),\n\t\t\t\t\t\t\"Compass data unreliable. Please recalibrate compass.\",\n\t\t\t\t\t\tToast.LENGTH_LONG).show();\n\t\t\t}\n\t\t\tgetMixViewData().setCompassErrorDisplayed(getMixViewData()\n\t\t\t\t\t.getCompassErrorDisplayed() + 1);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean onTouch(View v, MotionEvent event) {\n \n\t\tgetDataView().setFrozen(false);\n\t\tif (getMixViewData().getSearchNotificationTxt() != null) {\n\t\t\tgetMixViewData().getSearchNotificationTxt().setVisibility(View.GONE);\n\t\t\tgetMixViewData().setSearchNotificationTxt(null);\n\t\t}\n\t\treturn false;\n\t}\n\n\n\t/* ************ Handlers *************/\n\n\tpublic void doError(Exception ex1) {\n \n ex1.printStackTrace();\n // TODO fix me, We don't want errors in our app!\n\n\t}\n\n\tpublic void killOnError() throws Exception {\n\t\tif (fError)\n\t\t\tthrow new Exception();\n\t}\n\n\tprivate void handleIntent(Intent intent) {\n\t\tif (Intent.ACTION_SEARCH.equals(intent.getAction())) {\n\t\t\tString query = intent.getStringExtra(SearchManager.QUERY);\n\t\t\tdoMixSearch(query);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onNewIntent(Intent intent) {\n\t\tsetIntent(intent);\n\t\thandleIntent(intent);\n\t}\n\n\tprivate void doMixSearch(String query) {\n\t\tDataHandler jLayer = getDataView().getDataHandler();\n \n\t\tif (!getDataView().isFrozen()) {\n\t\t\t//MixListView.originalMarkerList = jLayer.getMarkerList();\n\t\t\t//MixMap.originalMarkerList = jLayer.getMarkerList();\n\t\t}\n\n\t\tArrayList<Marker> searchResults = new ArrayList<Marker>();\n\t\tLog.d(\"SEARCH-------------------0\", \"\" + query);\n\t\tif (jLayer.getMarkerCount() > 0) {\n\t\t\tfor (int i = 0; i < jLayer.getMarkerCount(); i++) {\n\t\t\t\tfinal Marker ma = jLayer.getMarker(i);\n\t\t\t\tif (ma.getTitle().toLowerCase().indexOf(query.toLowerCase()) != -1) {\n\t\t\t\t\tsearchResults.add(ma);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (searchResults.size() > 0) {\n\t\t\tgetDataView().setFrozen(true);\n\t\t\tjLayer.addMarkers(searchResults);\n\t\t}\n\t}\n\n\t/* ******* Getter and Setters ********** */\n\n\tpublic boolean isZoombarVisible() {\n\t\treturn getMixViewData().getMyZoomBar() != null\n\t\t\t\t&& getMixViewData().getMyZoomBar().getVisibility() == View.VISIBLE;\n\t}\n\t\n\tpublic String getZoomLevel() {\n\t\treturn getMixViewData().getZoomLevel();\n\t}\n\t\n\t/**\n\t * @return the dWindow\n\t */\n\tstatic PaintScreen getdWindow() {\n\t\treturn dWindow;\n\t}\n\n\n\t/**\n\t * @param dWindow\n\t * the dWindow to set\n\t */\n\tstatic void setdWindow(PaintScreen dWindow) {\n\t\tMixView.dWindow = dWindow;\n\t}\n\n\n\t/**\n\t * @return the dataView\n\t */\n\tstatic DataView getDataView() {\n\t\treturn dataView;\n\t}\n\n\t/**\n\t * @param dataView\n\t * the dataView to set\n\t */\n\tstatic void setDataView(DataView dataView) {\n\t\tMixView.dataView = dataView;\n\t}\n\n\n\tpublic int getZoomProgress() {\n\t\treturn getMixViewData().getZoomProgress();\n\t}\n\n\tprivate void setZoomLevel() {\n\t\tfinal float myout = 1f;\n\n\t\tgetDataView().setRadius(myout);\n\n\t\tmixViewData.setZoomLevel(String.valueOf(myout));\n\n\t\tgetMixViewData().getMixContext().getDownloadManager().switchOn();\n\n\t}\n\n}", "public class DataManager {\n\n public static int numberOfPOIs = 0;\n\n /* Check if the data should be refreshed after a resume or whatever,\n * make sure the data exists is reasonably fresh.\n */\n public static void refresh() {\n // TODO implement\n }\n\n public enum Language{\n DUTCH,ENGLISH,FRENCH\n }\n public static Language lang = null;\n\n private static final DataManager INSTANCE = new DataManager();\n private static final List<POI> poiList = new ArrayList<POI>();\n public static final POIDAO poidao = new POIDAO(PrefUtils.getContext());\n\n\n /*Route start point (belfort Ghent) needs to be replaced by current location in the future*/\n public static final double BELFORT_LON = 3.724801;//3.724833;\n public static final double BELFORT_LAT = 51.053541;//51.053623;\n\n // Private constructor prevents instantiation from other classes\n private DataManager() { }\n\n public Language getCurrentLanguage(){\n if(lang == null) lang = PrefUtils.getLanguage();\n return lang;\n }\n \n public static List<POI> getAll(){\n /* poiList might very well be empty after resuming the app */\n if(poiList.isEmpty()){\n try {\n poidao.open();\n } catch (SQLException e) {\n // TODO catch exceptions in a sane manner.\n }\n poiList.addAll(poidao.getAllPOIs());\n numberOfPOIs = poiList.size();\n /* Worst case scenario, the local database is empty and we're asked for a poi */\n if(poiList.isEmpty()){\n // TODO worst case!\n }\n }\n poidao.close();\n return poiList;\n }\n\n public static POI getPOIbyID(int id){\n return getAll().get(id);\n }\n\n public static DataManager getInstance() {\n return INSTANCE;\n }\n\n public static void addAll(List<POI> list) {\n numberOfPOIs += list.size() ;\n poiList.addAll(list);\n }\n\n public static void clearpois() {\n numberOfPOIs = 0;\n poiList.clear();\n }\n\n public static int lastViewedPOI = 1;\n\n /*Only show the swipe... msg once*/\n public static boolean shownMonumentDetailLandscapeMsg = false;\n}", "public class POI {\n\n\n private static final int BOAT = 0;\n private static final int CIVIL = 1;\n private static final int RELIGIOUS = 2;\n private static final int TOWER = 3;\n private static final int THEATRE = 4;\n private static final int CASTLE = 5;\n private static final int MONUMENT = 6;\n\n\n public int id;\n public String lat;\n public String lon;\n public String height;\n public String NL_name;\n public String FR_name;\n public String ENG_name;\n public String image_link;\n public String NL_description;\n public String FR_description;\n public String ENG_description;\n public int type;\n\n\n public POI(int id, String lat, String lon,String height, String name, String description, String image_url,int type){\n this.id = id;\n this.image_link = image_url;\n this.lat = lat;\n this.lon = lon;\n this.height = height;\n this.NL_name = name+ \"NL\";\n this.FR_name = name + \"FR\";\n this.ENG_name = name+ \"ENG\";\n this.NL_description = description + \"NL\";\n this.ENG_description = description + \"ENG\";\n this.FR_description = description + \"FR\";\n this.type = type;\n }\n /* Empty constructor needed by gson*/\n public POI(){}\n\n @Override\n public boolean equals(Object o) {\n if( o == null ) return false;\n if(!( o instanceof POI)) return false;\n POI poi = (POI) o;\n return poi.id == this.id;\n }\n\n public String getName() {\n final DataManager.Language lang = DataManager.getInstance().getCurrentLanguage();\n switch(lang){\n case ENGLISH:\n return this.ENG_name;\n case FRENCH:\n return this.FR_name;\n case DUTCH:\n default:\n /*Default is Dutch*/\n return this.NL_name;\n }\n }\n\n public String getDescription() {\n final DataManager.Language lang = DataManager.getInstance().getCurrentLanguage();\n switch(lang){\n case ENGLISH:\n return this.ENG_description;\n case FRENCH:\n return this.FR_description;\n case DUTCH:\n default:\n /*Default is Dutch*/\n return this.NL_description;\n }\n }\n\n @Override\n public String toString(){\n return getName();\n }\n\n\n public static Drawable getTypeImg(int type,Context context){\n return getTypeImage(type,context,DRAG_HANDLE);\n }\n\n public static Drawable getTypePopupImg(int type, Context context){\n return getTypeImage(type,context,POPUP_PORTRAIT);\n }\n\n public static Drawable getTypePopupImgLandscape(int type, Context context){\n return getTypeImage(type,context,POPUP_LANDSCAPE);\n }\n\n private static final int DRAG_HANDLE = 0;\n private static final int POPUP_PORTRAIT = 1;\n private static final int POPUP_LANDSCAPE = 2;\n\n private static Drawable getTypeImage(int type, Context context, int viewType){\n final Resources res = context.getResources();\n switch(type){\n case BOAT: return res.getDrawable(getCorrectImageId(R.drawable.drag_boat,R.drawable.popup_boat,R.drawable.popup_boat_land,viewType));\n case CASTLE: return res.getDrawable(getCorrectImageId(R.drawable.drag_castle,R.drawable.popup_castle,R.drawable.popup_castle_land,viewType));\n case CIVIL: return res.getDrawable(getCorrectImageId(R.drawable.drag_city,R.drawable.popup_city,R.drawable.popup_city_land,viewType));\n case MONUMENT: return res.getDrawable(getCorrectImageId(R.drawable.drag_monument,R.drawable.popup_monument,R.drawable.popup_monument_land,viewType));\n case RELIGIOUS: return res.getDrawable(getCorrectImageId(R.drawable.drag_religion,R.drawable.popup_religion,R.drawable.popup_religion_land,viewType));\n case THEATRE: return res.getDrawable(getCorrectImageId(R.drawable.drag_theater,R.drawable.popup_theater,R.drawable.popup_theater_land,viewType));\n case TOWER: return res.getDrawable(getCorrectImageId(R.drawable.drag_skyscraper,R.drawable.popup_skyscraper,R.drawable.popup_skyscraper_land,viewType));\n default: return res.getDrawable(getCorrectImageId(R.drawable.drag_monument,R.drawable.popup_monument,R.drawable.popup_default_land,viewType));\n }\n }\n\n private static int getCorrectImageId(int drag, int popupPortrait, int popupLandscape,int viewType){\n if(viewType == DRAG_HANDLE){\n return drag;\n }else if(viewType == POPUP_PORTRAIT){\n return popupPortrait;\n }else{\n return popupLandscape;\n }\n }\n}", "public class PrefUtils {\n public static final String TAG = \"Belfort\";\n public static final String DATASET_URL = \"https://raw.githubusercontent.com/oSoc14/ArtoriaData/master/poi.json\";\n\n private static final String ARG_USER_KEY = \"be.artoria.belfort\";\n private static final String ARG_DOWNLOAD = \"be.artoria.belfort.downloadtimes\";\n private static final String ARG_FIRS_TTIME = \"be.artoria.belfort.firstTime\";\n private static final String ARG_ROUTE = \"be.artoria.belfort.route\";\n private static final String ARG_LANG = \"be.artoria.belfort.lang\";\n private static final String ARG_FIRS_PANORAMA_TIME = \"be.artoria.belfort.panorama_firstTime\";\n\n private static Context CONTEXT;\n\n public static Context getContext()\n {\n return CONTEXT;\n }\n\n public static void initialize(Application application)\n {\n CONTEXT = application;\n }\n\n public static void saveTimeStampDownloads()\n {\n getPrefs()\n .edit()\n .putLong(ARG_DOWNLOAD, System.currentTimeMillis())\n .apply();\n }\n\n public static boolean isFirstTime() {\n return getPrefs().getBoolean(ARG_FIRS_TTIME, true);\n }\n\n public static void setNotFirstTime() {\n getPrefs()\n .edit()\n .putBoolean(ARG_FIRS_TTIME, false)\n .apply();\n }\n\n public static long getTimeStampDownloads()\n {\n return getPrefs().getLong(ARG_DOWNLOAD, 0);\n }\n\n public static void removeAll()\n {\n getPrefs().edit().clear().apply();\n }\n\n // get preferences\n @SuppressWarnings(\"NewApi\")\n private static SharedPreferences getPrefs()\n {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_MULTI_PROCESS);\n } else {\n return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_PRIVATE);\n }\n }\n\n public static DataManager.Language getLanguage() {\n final Locale locale = getContext().getResources().getConfiguration().locale;\n final String lang = locale.getLanguage();\n if(\"en\".equals(lang)){ return DataManager.Language.ENGLISH;}\n if(\"fr\".equals(lang)){ return DataManager.Language.FRENCH;}\n /* default choice is dutch */\n return DataManager.Language.DUTCH;\n }\n\n public static void saveLanguage(DataManager.Language lang){\n String lng = \"nl\";//default dutch\n if(lang == DataManager.Language.ENGLISH){lng=\"en\";}\n if(lang == DataManager.Language.FRENCH){lng =\"fr\";}\n getPrefs().edit().putString(ARG_LANG,lng).apply();\n }\n\n public static void loadLanguage(Context context){\n final String lang = getPrefs().getString(ARG_LANG,\"nl\");/*Default dutch*/\n final Locale locale = new Locale(lang);\n LanguageChoiceActivity.setLang(locale,context);\n }\n\n public static List<POI> getSavedRoute(){\n final String poiIds = getPrefs().getString(ARG_ROUTE,\"\");\n final List<POI> toReturn = new ArrayList<POI>();\n if(!poiIds.equals(\"\")){\n final String[] splitted = poiIds.split(\",\");\n for(String s: splitted){\n try {\n final int id = Integer.parseInt(s);\n final POI toAdd = DataManager.getPOIbyID(id);\n toReturn.add(toAdd);\n }catch(Exception ex){\n //can't parse string to int ....\n }\n }\n }\n return toReturn;\n }\n\n public static void saveRoute(List<POI> route){\n final StringBuilder sb = new StringBuilder();\n for(POI poi : route){\n sb.append(poi.id);\n sb.append(\",\");\n }\n if(sb.length() > 0) {\n sb.delete(sb.length() - 1, sb.length());\n }\n getPrefs().edit().putString(ARG_ROUTE,sb.toString()).apply();\n }\n\n public static void setPanoramaNotFirstTime() {\n getPrefs()\n .edit()\n .putBoolean(ARG_FIRS_PANORAMA_TIME, false)\n .apply();\n }\n public static boolean isFirstPanoramaTime() {\n return getPrefs().getBoolean(ARG_FIRS_PANORAMA_TIME, true);\n }\n\n}" ]
import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.hardware.Sensor; import android.hardware.SensorManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import be.artoria.belfortapp.app.adapters.DescriptionRow; import be.artoria.belfortapp.app.adapters.MainAdapter; import be.artoria.belfortapp.fragments.MapFragment; import be.artoria.belfortapp.mixare.MixView; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import be.artoria.belfortapp.R; import be.artoria.belfortapp.app.DataManager; import be.artoria.belfortapp.app.POI; import be.artoria.belfortapp.app.PrefUtils;
package be.artoria.belfortapp.activities; public class MainActivity extends BaseActivity { MainAdapter menuAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initGui(); } private static boolean downloading = false; public static void downloadData() { final long lastDownload = PrefUtils.getTimeStampDownloads(); final long timeSinceLastDownload = System.currentTimeMillis() - lastDownload; /* Either there is no last download ( case == 0) * or it is older than 12 hours, which is 43200000 milliseconds according to google */ // TODO change this back! // if((lastDownload == 0 || timeSinceLastDownload > 5*60*1000) && !downloading){ if((lastDownload == 0 || timeSinceLastDownload > 1000*60*60*6) && !downloading){ downloading = true; Log.i(PrefUtils.TAG,"Started downloading in the background"); new DownloadDataTask().execute(PrefUtils.DATASET_URL); } } @Override protected void onResume() { super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return super.onOptionsItemSelected(item); } /*initialize the GUI content and clickhandlers*/ private void initGui(){ final ListView lstMenu = (ListView)findViewById(R.id.lstMenu); final Button btnSettings = (Button)findViewById(R.id.btnSettings); final Button btnAbout = (Button)findViewById(R.id.btnAbout); final String[] strings = getResources().getStringArray(R.array.lstMenu); final Drawable[] drawables = new Drawable[]{ getResources().getDrawable((R.drawable.panorama)), getResources().getDrawable((R.drawable.menu)), getResources().getDrawable((R.drawable.route)) }; final List<DescriptionRow> list = new ArrayList<DescriptionRow>(); for (int i = 0; i < strings.length; i++) { list.add(new DescriptionRow(drawables[i],strings[i])); } menuAdapter = new MainAdapter(this,R.layout.main_list_item,list); lstMenu.setAdapter(menuAdapter); lstMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { final Intent intent; switch (i) { /* The first item is the be.artoria.belfortapp.mixare panorama */ case 0: if(deviceSupported()) { intent = new Intent(MainActivity.this, MixView.class); startActivity(intent); } else{ Toast.makeText(PrefUtils.getContext(),R.string.unsupported, Toast.LENGTH_LONG).show(); } break; /* The second item are the buildings */ case 1: intent = new Intent(MainActivity.this, MonumentDetailActivity.class); intent.putExtra(MonumentDetailActivity.ARG_ID, 1); startActivity(intent); break; /* The third item is my route */ case 2: intent = new Intent(MainActivity.this,NewRouteActivity.class); startActivity(intent); break; } } }); btnSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /*Go to settings*/ final Intent i = new Intent(MainActivity.this, LanguageChoiceActivity.class); startActivity(i); } }); btnAbout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /*Go to the Artoria website*/ final Uri webpage = Uri.parse(getResources().getString(R.string.artoria_url)); final Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage); startActivity(webIntent); } }); } private boolean deviceSupported() { final SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); return mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null && mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null; } private static class DownloadDataTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { StringBuilder response = new StringBuilder(); for (String url : urls) { final DefaultHttpClient client = new DefaultHttpClient(); final HttpGet httpGet = new HttpGet(url); try { final HttpResponse execute = client.execute(httpGet); final InputStream content = execute.getEntity().getContent(); final BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s; while ((s = buffer.readLine()) != null) { response.append(s); } } catch (final Exception e) { e.printStackTrace(); } } return response.toString(); } @Override protected void onPostExecute(String result) { final Gson gson = new Gson();
final List<POI> list = gson.fromJson(result, new TypeToken<List<POI>>(){}.getType());
5
xda/XDA-One
android/src/main/java/com/xda/one/ui/PostAdapter.java
[ "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class ResponseAttachment implements Parcelable {\n\n public static final Parcelable.Creator<ResponseAttachment> CREATOR\n = new Parcelable.Creator<ResponseAttachment>() {\n @Override\n public ResponseAttachment createFromParcel(Parcel source) {\n return new ResponseAttachment(source);\n }\n\n @Override\n public ResponseAttachment[] newArray(int size) {\n return new ResponseAttachment[size];\n }\n };\n\n @JsonProperty(value = \"dateline\")\n private long mDateLine;\n\n @JsonProperty(value = \"thumbnail_dateline\")\n private long mThumbnailDateLine;\n\n @JsonProperty(value = \"filename\")\n private String mFileName;\n\n @JsonProperty(value = \"filesize\")\n private float mFileSize;\n\n @JsonProperty(value = \"visible\")\n private int mVisible;\n\n @JsonProperty(value = \"attachmentid\")\n private int mAttachmentId;\n\n @JsonProperty(value = \"counter\")\n private int mCounter;\n\n @JsonProperty(value = \"postid\")\n private int mPostId;\n\n @JsonProperty(value = \"hasthumbnail\")\n private int mHasThumbnail;\n\n @JsonProperty(value = \"thumbnail_filesize\")\n private int mThumbnailFileSize;\n\n @JsonProperty(value = \"build_thumbnail\")\n private int mBuildThumbnail;\n\n @JsonProperty(value = \"newwindow\")\n private int mNewWindow;\n\n @JsonProperty(value = \"attachment_url\")\n private String mAttachmentUrl;\n\n public ResponseAttachment() {\n }\n\n private ResponseAttachment(final Parcel in) {\n mDateLine = in.readLong();\n mThumbnailDateLine = in.readLong();\n mFileName = in.readString();\n mFileSize = in.readFloat();\n mVisible = in.readInt();\n mAttachmentId = in.readInt();\n mCounter = in.readInt();\n mPostId = in.readInt();\n mHasThumbnail = in.readInt();\n mThumbnailFileSize = in.readInt();\n mBuildThumbnail = in.readInt();\n mNewWindow = in.readInt();\n mAttachmentUrl = in.readString();\n }\n\n public long getDateLine() {\n return mDateLine;\n }\n\n public long getThumbnailDateLine() {\n return mThumbnailDateLine;\n }\n\n public String getFileName() {\n return mFileName;\n }\n\n public float getFileSize() {\n return mFileSize;\n }\n\n public boolean isVisible() {\n return mVisible != 0;\n }\n\n public int getAttachmentId() {\n return mAttachmentId;\n }\n\n public int getCounter() {\n return mCounter;\n }\n\n public int getPostId() {\n return mPostId;\n }\n\n public boolean hasThumbnail() {\n return mHasThumbnail != 0;\n }\n\n public int getThumbnailFileSize() {\n return mThumbnailFileSize;\n }\n\n public int getBuildThumbnail() {\n return mBuildThumbnail;\n }\n\n public boolean isNewWindow() {\n return mNewWindow != 0;\n }\n\n public String getAttachmentUrl() {\n return mAttachmentUrl;\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.writeLong(mDateLine);\n dest.writeLong(mThumbnailDateLine);\n dest.writeString(mFileName);\n dest.writeFloat(mFileSize);\n dest.writeInt(mVisible);\n dest.writeInt(mAttachmentId);\n dest.writeInt(mCounter);\n dest.writeInt(mPostId);\n dest.writeInt(mHasThumbnail);\n dest.writeInt(mThumbnailFileSize);\n dest.writeInt(mBuildThumbnail);\n dest.writeInt(mNewWindow);\n dest.writeString(mAttachmentUrl);\n }\n}", "public class XDAAccount extends Account {\n\n public static final Creator<XDAAccount> CREATOR = new Creator<XDAAccount>() {\n @Override\n public XDAAccount createFromParcel(Parcel source) {\n return new XDAAccount(source);\n }\n\n @Override\n public XDAAccount[] newArray(int size) {\n return new XDAAccount[size];\n }\n };\n\n private final String mEmail;\n\n private final String mUserId;\n\n private final String mAvatarUrl;\n\n private final int mPmCount;\n\n private final int mQuoteCount;\n\n private final int mMentionCount;\n\n private final String mAuthToken;\n\n public XDAAccount(final String name, final String userId, final String email,\n final String avatarUrl, final int pmCount, final int quoteCount,\n final int mentionCount, final String authToken) {\n super(name, \"com.xda\");\n mEmail = email;\n mUserId = userId;\n mAvatarUrl = avatarUrl;\n mPmCount = pmCount;\n mQuoteCount = quoteCount;\n mMentionCount = mentionCount;\n\n mAuthToken = authToken;\n }\n\n public XDAAccount(final Parcel source) {\n super(source);\n\n mEmail = source.readString();\n mUserId = source.readString();\n mAvatarUrl = source.readString();\n mPmCount = source.readInt();\n mQuoteCount = source.readInt();\n mMentionCount = source.readInt();\n mAuthToken = source.readString();\n }\n\n public static XDAAccount fromProfile(final ResponseUserProfile profile) {\n final ResponseUserProfileNotificationContainer notifications = profile.getNotifications();\n return new XDAAccount(profile.getUserName(), profile.getUserId(), profile.getEmail(),\n profile.getAvatarUrl(), notifications.getPmUnread().getTotal(),\n notifications.getDbTechQuoteCount().getTotal(),\n notifications.getDbTechMetionCount().getTotal(),\n RetrofitClient.getAuthToken());\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n\n dest.writeString(mEmail);\n dest.writeString(mUserId);\n dest.writeString(mAvatarUrl);\n dest.writeInt(mPmCount);\n dest.writeInt(mQuoteCount);\n dest.writeInt(mMentionCount);\n dest.writeString(mAuthToken);\n }\n\n public String getEmail() {\n return mEmail;\n }\n\n public String getUserId() {\n return mUserId;\n }\n\n public String getAvatarUrl() {\n return mAvatarUrl;\n }\n\n public String getUserName() {\n return name;\n }\n\n public int getPmCount() {\n return mPmCount;\n }\n\n public int getQuoteCount() {\n return mQuoteCount;\n }\n\n public int getMentionCount() {\n return mMentionCount;\n }\n\n public String getAuthToken() {\n return mAuthToken;\n }\n}", "public class AugmentedPost implements Post {\n\n public static final ResponsePost.Creator CREATOR = new ResponsePost.Creator() {\n @Override\n public AugmentedPost createFromParcel(final Parcel in) {\n return new AugmentedPost(in);\n }\n\n @Override\n public AugmentedPost[] newArray(final int size) {\n return new AugmentedPost[size];\n }\n };\n\n private final Post mPost;\n\n private String mFormatlessText;\n\n private String mCreatedText;\n\n private TextDataStructure mTextDataStructure;\n\n private boolean mThanked;\n\n private int mThanksCount;\n\n private AugmentedPost(final Parcel parcel) {\n mPost = new ResponsePost(parcel);\n\n mFormatlessText = parcel.readString();\n mCreatedText = parcel.readString();\n mThanked = parcel.readByte() != 0;\n mThanksCount = parcel.readInt();\n }\n\n public AugmentedPost(final Post post, final Context context) {\n mPost = post;\n mThanked = post.isThanked();\n mThanksCount = post.getThanksCount();\n\n final Spannable formattedContent = ContentParser.parseAndSmilifyBBCode(context,\n post.getPageText());\n mTextDataStructure = new TextDataStructure(formattedContent);\n mFormatlessText = formattedContent.toString();\n\n mCreatedText = PostUtils.getCreatedText(mTextDataStructure, Integer.MAX_VALUE);\n }\n\n public String getFormatlessText() {\n return mFormatlessText;\n }\n\n public TextDataStructure getTextDataStructure() {\n return mTextDataStructure;\n }\n\n public String getCreatedText() {\n return mCreatedText;\n }\n\n @Override\n public int getPostId() {\n return mPost.getPostId();\n }\n\n @Override\n public int getVisible() {\n return mPost.getVisible();\n }\n\n @Override\n public String getUserId() {\n return mPost.getUserId();\n }\n\n @Override\n public String getTitle() {\n return mPost.getTitle();\n }\n\n @Override\n public String getPageText() {\n return mPost.getPageText();\n }\n\n @Override\n public String getUserName() {\n return mPost.getUserName();\n }\n\n @Override\n public long getDateline() {\n return mPost.getDateline();\n }\n\n @Override\n public List<ResponseAttachment> getAttachments() {\n return mPost.getAttachments();\n }\n\n @Override\n public String getAvatarUrl() {\n return mPost.getAvatarUrl();\n }\n\n @Override\n public int getThanksCount() {\n return mThanksCount;\n }\n\n @Override\n public void setThanksCount(int newCount) {\n mThanksCount = newCount;\n }\n\n @Override\n public boolean isThanked() {\n return mThanked;\n }\n\n @Override\n public void setThanked(boolean thanked) {\n mThanked = thanked;\n }\n\n @Override\n public int describeContents() {\n return mPost.describeContents();\n }\n\n @Override\n public void writeToParcel(final Parcel dest, final int flags) {\n mPost.writeToParcel(dest, flags);\n\n dest.writeString(mFormatlessText);\n dest.writeString(mCreatedText);\n dest.writeByte(mThanked ? (byte) 1 : (byte) 0);\n dest.writeInt(mThanksCount);\n }\n}", "public class TextDataStructure {\n\n private final ArrayList<Section> mSections;\n\n public TextDataStructure(final Spanned spanned) {\n mSections = new ArrayList<>();\n\n if (TextUtils.isEmpty(spanned)) {\n return;\n }\n setupAllSections(spanned);\n }\n\n private void setupAllSections(final Spanned spanned) {\n final XDATagHandlers.QuoteTagHandler.QuoteSpan[] quoteSpans = spanned.getSpans(0,\n spanned.length(), XDATagHandlers.QuoteTagHandler.QuoteSpan.class);\n int position = 0;\n for (XDATagHandlers.QuoteTagHandler.QuoteSpan span : quoteSpans) {\n int start = spanned.getSpanStart(span);\n if (position < start) {\n setupNormalSection(new SpannableStringBuilder(spanned, position, start));\n } else if (position > start) {\n // In this case this item is the parent of the previous quote span\n final Section previous = mSections.get(mSections.size() - 1);\n previous.setEmbedded(true);\n start = position;\n }\n position = spanned.getSpanEnd(span);\n setupQuoteSection(new SpannableStringBuilder(spanned, start, position),\n span.getUserId());\n }\n if (position < spanned.length()) {\n setupNormalSection(new SpannableStringBuilder(spanned, position, spanned.length()));\n }\n }\n\n private void setupNormalSection(final Spanned spanned) {\n final Section section = new Section(SectionType.NORMAL);\n setupImageSections(section, spanned, new Callback() {\n @Override\n public void setupOther(int start, int end) {\n final Text text = new Text(new SpannableStringBuilder(spanned, start, end));\n section.addItem(text);\n }\n });\n mSections.add(section);\n }\n\n private void setupQuoteSection(final Spanned spanned, final String userId) {\n final Section section = new Section(SectionType.QUOTE);\n section.setUserId(userId);\n setupImageSections(section, spanned, new Callback() {\n @Override\n public void setupOther(int start, int end) {\n final Text text = new Text(new SpannableStringBuilder(spanned, start, end));\n section.addItem(text);\n }\n });\n mSections.add(section);\n }\n\n private void setupImageSections(final Section section, final Spanned spanned,\n final Callback callback) {\n final XDATagHandlers.ImageHandler.ImageSpan[] imageSpans = spanned.getSpans(0,\n spanned.length(), XDATagHandlers.ImageHandler.ImageSpan.class);\n int position = 0;\n for (int i = imageSpans.length - 1; i >= 0; i--) {\n final XDATagHandlers.ImageHandler.ImageSpan span = imageSpans[i];\n final int start = spanned.getSpanStart(span);\n if (position < start) {\n callback.setupOther(position, start);\n }\n final Image image = new Image(span.getSrc());\n section.addItem(image);\n\n position = spanned.getSpanEnd(span);\n }\n if (position < spanned.length()) {\n callback.setupOther(position, spanned.length());\n }\n }\n\n public List<Section> getSections() {\n return Collections.unmodifiableList(mSections);\n }\n\n public enum ItemType {\n TEXT,\n IMAGE\n }\n\n public enum SectionType {\n NORMAL,\n QUOTE\n }\n\n public interface Item {\n\n public ItemType getType();\n\n public CharSequence getId();\n }\n\n private interface Callback {\n\n public void setupOther(int start, int end);\n }\n\n public class Section {\n\n private final SectionType mType;\n\n private final List<Item> mItems;\n\n private boolean mEmbedded;\n\n private String mUserId;\n\n public Section(final SectionType type) {\n mType = type;\n mItems = new ArrayList<>();\n }\n\n public SectionType getType() {\n return mType;\n }\n\n public List<Item> getItems() {\n return mItems;\n }\n\n private void addItem(final Item image) {\n mItems.add(image);\n }\n\n public boolean isEmbedded() {\n return mEmbedded;\n }\n\n public void setEmbedded(boolean embedded) {\n mEmbedded = embedded;\n }\n\n public void setUserId(final String userId) {\n mUserId = userId;\n }\n\n public String getUsernamePostId() {\n return mUserId;\n }\n }\n\n public class Text implements Item {\n\n private final Spanned mText;\n\n public Text(final Spanned text) {\n mText = text;\n }\n\n @Override\n public ItemType getType() {\n return ItemType.TEXT;\n }\n\n @Override\n public CharSequence getId() {\n return mText;\n }\n }\n\n public class Image implements Item {\n\n private final String mSource;\n\n public Image(final String source) {\n mSource = source;\n }\n\n @Override\n public ItemType getType() {\n return ItemType.IMAGE;\n }\n\n @Override\n public CharSequence getId() {\n return mSource;\n }\n }\n}", "public class AccountUtils {\n\n private static final String SELECTED_ACCOUNT_USERNAME = \"selected_account_username\";\n\n private static final String SELECTED_ACCOUNT_USERID = \"selected_account_userid\";\n\n private static final String SELECTED_ACCOUNT_EMAIL = \"selected_account_email\";\n\n private static final String SELECTED_ACCOUNT_AVATAR = \"selected_account_avatar\";\n\n private static final String SELECTED_ACCOUNT_PM_COUNT = \"selected_account_pm_count\";\n\n private static final String SELECTED_ACCOUNT_QUOTE_COUNT = \"selected_account_quote_count\";\n\n private static final String SELECTED_ACCOUNT_MENTION_COUNT = \"selected_accont_mention_count\";\n\n private static final String SELECTED_ACCOUNT_TOKEN = \"selected_account_token\";\n\n public static boolean isAccountAvailable(final Context context) {\n final SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);\n return sharedPreferences.getString(SELECTED_ACCOUNT_USERNAME, null) != null;\n }\n\n public static XDAAccount getAccount(final Context context) {\n final SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);\n final String username = sharedPreferences.getString(SELECTED_ACCOUNT_USERNAME, null);\n final String userId = sharedPreferences.getString(SELECTED_ACCOUNT_USERID, null);\n final String email = sharedPreferences.getString(SELECTED_ACCOUNT_EMAIL, null);\n final String avatar = sharedPreferences.getString(SELECTED_ACCOUNT_AVATAR, null);\n final int pmCount = sharedPreferences.getInt(SELECTED_ACCOUNT_PM_COUNT, 0);\n final int quoteCount = sharedPreferences.getInt(SELECTED_ACCOUNT_QUOTE_COUNT, 0);\n final int mentionCount = sharedPreferences.getInt(SELECTED_ACCOUNT_MENTION_COUNT, 0);\n final String token = sharedPreferences.getString(SELECTED_ACCOUNT_TOKEN, null);\n\n return TextUtils.isEmpty(username) ? null : new XDAAccount(username, userId, email,\n avatar, pmCount, quoteCount, mentionCount, token);\n }\n\n public static void storeAccount(final Context context, final XDAAccount account) {\n final SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);\n final SharedPreferences.Editor editor = sharedPreferences.edit();\n\n if (account == null) {\n editor.remove(SELECTED_ACCOUNT_USERNAME).remove(SELECTED_ACCOUNT_USERID)\n .remove(SELECTED_ACCOUNT_EMAIL).remove(SELECTED_ACCOUNT_AVATAR)\n .remove(SELECTED_ACCOUNT_PM_COUNT).remove(SELECTED_ACCOUNT_QUOTE_COUNT)\n .remove(SELECTED_ACCOUNT_MENTION_COUNT).remove(SELECTED_ACCOUNT_TOKEN);\n } else {\n editor.putString(SELECTED_ACCOUNT_USERNAME, account.getUserName())\n .putString(SELECTED_ACCOUNT_USERID, account.getUserId())\n .putString(SELECTED_ACCOUNT_EMAIL, account.getEmail())\n .putString(SELECTED_ACCOUNT_AVATAR, account.getAvatarUrl())\n .putInt(SELECTED_ACCOUNT_PM_COUNT, account.getPmCount())\n .putInt(SELECTED_ACCOUNT_QUOTE_COUNT, account.getQuoteCount())\n .putInt(SELECTED_ACCOUNT_MENTION_COUNT, account.getMentionCount())\n .putString(SELECTED_ACCOUNT_TOKEN, account.getAuthToken());\n }\n\n editor.apply();\n }\n}", "public class Utils {\n\n public static String handleRetrofitErrorQuietly(final RetrofitError error) {\n error.printStackTrace();\n\n InputStream inputStream = null;\n try {\n if (error.isNetworkError()) {\n Log.e(\"XDA-ONE\", \"Network error happened.\");\n } else {\n final TypedInput body = error.getResponse().getBody();\n if (body == null) {\n Log.e(\"XDA-ONE\", \"Unable to retrieve body\");\n return null;\n }\n inputStream = body.in();\n\n final String result = IOUtils.toString(inputStream);\n Log.e(\"XDA-ONE\", result);\n return result;\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n return null;\n }\n\n public static <T> int getCollectionSize(final Collection<T> collection) {\n return collection == null ? 0 : collection.size();\n }\n\n public static boolean isCollectionEmpty(final Collection collection) {\n return collection == null || collection.isEmpty();\n }\n\n public static CharSequence getRelativeDate(final Context context, final long dateline) {\n return DateUtils.getRelativeDateTimeString(context, dateline,\n DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,\n DateUtils.FORMAT_NUMERIC_DATE);\n }\n}" ]
import com.dd.xda.CircularProgressButton; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import com.xda.one.R; import com.xda.one.api.model.response.ResponseAttachment; import com.xda.one.auth.XDAAccount; import com.xda.one.model.augmented.AugmentedPost; import com.xda.one.parser.TextDataStructure; import com.xda.one.ui.helper.ActionModeHelper; import com.xda.one.util.AccountUtils; import com.xda.one.util.SectionUtils; import com.xda.one.util.Utils; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List;
package com.xda.one.ui; public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> { private final Context mContext; private final GoToQuoteListener mQuoteListener; private final View.OnClickListener mMultiQuoteClickListener; private final ActionModeHelper mModeHelper; private final LayoutInflater mLayoutInflater; private final View.OnClickListener mDownloadClickListener; private final View.OnClickListener mImageClickListener; private final View.OnClickListener mAvatarClickListener; private final View.OnClickListener mThanksClickListener; private final View.OnClickListener mQuoteClickListener; private List<AugmentedPost> mPosts; public PostAdapter(final Context context, final ActionModeHelper modeHelper, final View.OnClickListener downloadClickListener, final View.OnClickListener imageClickListener, final View.OnClickListener avatarClickListener, final View.OnClickListener thanksClickListener, final View.OnClickListener quoteClickListener, final View.OnClickListener multiQuoteClickListener, final GoToQuoteListener quoteListener) { mContext = context; mLayoutInflater = LayoutInflater.from(context); mModeHelper = modeHelper; mDownloadClickListener = downloadClickListener; mImageClickListener = imageClickListener; mAvatarClickListener = avatarClickListener; mThanksClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { final CircularProgressButton button = (CircularProgressButton) v; button.setProgress(50); thanksClickListener.onClick(v); } }; mQuoteClickListener = quoteClickListener; mMultiQuoteClickListener = multiQuoteClickListener; mQuoteListener = quoteListener; mPosts = new ArrayList<>(); } @Override public PostViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { final View view = mLayoutInflater.inflate(R.layout.post_list_item, parent, false); return new PostViewHolder(view); } @Override public void onBindViewHolder(PostViewHolder holder, int position) { final AugmentedPost post = getPost(position); holder.itemView.setOnClickListener(mModeHelper); holder.itemView.setOnLongClickListener(mModeHelper); mModeHelper.updateActivatedState(holder.itemView, position); holder.userNameView.setText(post.getUserName()); // TODO - make this more efficient holder.postLayout.removeAllViews(); final TextDataStructure structure = post.getTextDataStructure(); SectionUtils.setupSections(mContext, mLayoutInflater, holder.postLayout, structure, mQuoteListener); // Load the avatar into the image view Picasso.with(mContext) .load(post.getAvatarUrl()) .placeholder(R.drawable.account_circle) .error(R.drawable.account_circle) .into(holder.avatarView); holder.avatarView.setOnClickListener(mAvatarClickListener); holder.avatarView.setTag(post.getUserId()); holder.attachments.removeAllViews(); if (post.getAttachments() != null) { for (final ResponseAttachment responseAttachment : post.getAttachments()) { if (responseAttachment.hasThumbnail()) { attachImagesThumbnail(holder, responseAttachment); } else { attachFiles(holder, responseAttachment); } } }
holder.dateView.setText(Utils.getRelativeDate(mContext, post.getDateline()));
5
tommai78101/PokemonWalking
levelEditor/src/main/java/script_editor/ScriptToolbar.java
[ "public class EditorFileChooser extends JFileChooser {\n\tprivate static final long serialVersionUID = -649119858083751845L;\n\n\t@Override\n\tpublic void approveSelection() {\n\t\tFile selectedFile = super.getSelectedFile();\n\t\tif (selectedFile.isDirectory()) {\n\t\t\tsuper.setCurrentDirectory(selectedFile);\n\t\t\treturn;\n\t\t}\n\t\tsuper.approveSelection();\n\t}\n}", "public class EditorMouseListener implements MouseListener {\n\tprivate JFileChooser fileChooser;\n\tprivate String currentName = \"Untitled.script\";\n\tprivate String oldName = \"\";\n\n\tpublic EditorMouseListener(JFileChooser fileChooser) {\n\t\tthis.fileChooser = fileChooser;\n\t\tMetalFileChooserUI ui = (MetalFileChooserUI) this.fileChooser.getUI();\n\t\tui.setFileName(this.currentName);\n\t}\n\n\t@Override\n\tpublic void mouseClicked(MouseEvent e) {\n\t\tif (e.getClickCount() == 1) {\n\t\t\tFile file = this.fileChooser.getSelectedFile();\n\t\t\tif (file != null) {\n\t\t\t\tif (!file.isDirectory()) {\n\t\t\t\t\tthis.currentName = file.getName();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.oldName = file.getName();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (e.getClickCount() == 2) {\n\t\t\tFile file = this.fileChooser.getSelectedFile();\n\t\t\tif (file != null) {\n\t\t\t\tif (file.isDirectory()) {\n\t\t\t\t\tthis.fileChooser.setCurrentDirectory(file);\n\t\t\t\t}\n\t\t\t\telse if (file.isFile()) {\n\t\t\t\t\tthis.fileChooser.setSelectedFile(file);\n\t\t\t\t\tthis.currentName = file.getName();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!this.oldName.equals(this.currentName)) {\n\t\t\tMetalFileChooserUI ui = (MetalFileChooserUI) this.fileChooser.getUI();\n\t\t\tui.setFileName(this.currentName);\n\t\t\tthis.oldName = this.currentName;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void mouseEntered(MouseEvent e) {}\n\n\t@Override\n\tpublic void mouseExited(MouseEvent e) {}\n\n\t@Override\n\tpublic void mousePressed(MouseEvent e) {}\n\n\t@Override\n\tpublic void mouseReleased(MouseEvent e) {\n\t\tMouseEvent newEvent = new MouseEvent(\n\t\t\tthis.fileChooser,\n\t\t\te.getID(),\n\t\t\te.getWhen(),\n\t\t\te.getModifiersEx(),\n\t\t\te.getX(),\n\t\t\te.getY(),\n\t\t\t1,\n\t\t\tfalse\n\t\t);\n\t\tthis.mouseClicked(newEvent);\n\t}\n}", "public class FileControl extends JPanel implements ActionListener {\n\tpublic static File lastSavedDirectory = null;\n\tpublic static final String[] TAGS = {\n\t\t\"New\", \"Save\", \"Open\", \"\", \"Tileset\", \"Trigger\", \"NPC\", \"Script\"\n\t};\n\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final String defaultPath = Paths.get(\"\").toAbsolutePath().toString();\n\n\tpublic HashMap<String, JButton> buttonCache = new HashMap<>();\n\tprivate LevelEditor editor;\n\tprivate List<String> cacheDirectories;\n\n\tpublic FileControl(LevelEditor editor) {\n\t\tthis.editor = editor;\n\t\tthis.cacheDirectories = new ArrayList<>();\n\t\tthis.setLayout(new GridLayout(1, FileControl.TAGS.length));\n\n\t\tfor (int i = 0; i < FileControl.TAGS.length; i++) {\n\t\t\tif (FileControl.TAGS[i].isEmpty() || FileControl.TAGS[i].equals(\"\")) {\n\t\t\t\tthis.add(new JSeparator(SwingConstants.VERTICAL));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tJButton button = new JButton(FileControl.TAGS[i]);\n\t\t\tbutton.addActionListener(this);\n\t\t\tString actionCommand = Integer.toString(i);\n\t\t\tbutton.setActionCommand(actionCommand);\n\t\t\tthis.buttonCache.put(actionCommand, button);\n\t\t\tthis.add(button);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent event) {\n\t\tfinal EditorFileChooser chooser = new EditorFileChooser();\n\t\tfinal EditorMouseListener mouseListener = new EditorMouseListener(chooser);\n\t\tJButton button = (JButton) event.getSource();\n\t\tString command = button.getActionCommand();\n\t\ttry {\n\t\t\tint value = Integer.parseInt(command);\n\t\t\tswitch (value) {\n\t\t\t\tcase 0: // New\n\t\t\t\t{\n\t\t\t\t\tthis.editor.drawingBoardPanel.newImage();\n\t\t\t\t\tthis.editor.setMapAreaName(\"Untitled\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 1: { // Save\n\t\t\t\t\tif (!this.editor.drawingBoardPanel.hasBitmap()) {\n\t\t\t\t\t\tJOptionPane.showMessageDialog(null, \"No created maps to save.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry (RandomAccessFile raf = new RandomAccessFile(LevelEditor.SAVED_PATH_DATA, \"r\")) {\n\t\t\t\t\t\tthis.fetchCachedDirectories(raf);\n\t\t\t\t\t\tFileControl.lastSavedDirectory = new File(this.cacheDirectories.get(LevelEditor.FileControlIndex));\n\t\t\t\t\t}\n\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\tFileControl.lastSavedDirectory = new File(FileControl.defaultPath);\n\t\t\t\t\t}\n\n\t\t\t\t\tJList<Class<?>> list = this.findFileList(chooser);\n\t\t\t\t\tLOOP_TEMP:\n\t\t\t\t\tfor (MouseListener l : list.getMouseListeners()) {\n\t\t\t\t\t\t// If the class name do not contain \"FilePane\", we continue iterating.\n\t\t\t\t\t\tif (l.getClass().getName().indexOf(\"FilePane\") < 0)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tlist.removeMouseListener(l);\n\t\t\t\t\t\tlist.addMouseListener(mouseListener);\n\t\t\t\t\t\tbreak LOOP_TEMP;\n\t\t\t\t\t}\n\t\t\t\t\tchooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);\n\t\t\t\t\tchooser.setCurrentDirectory(FileControl.lastSavedDirectory);\n\t\t\t\t\tchooser.setFileFilter(new FileNameExtensionFilter(\"PNG files\", \"png\"));\n\t\t\t\t\tchooser.setVisible(true);\n\t\t\t\t\tint result = chooser.showSaveDialog(null);\n\t\t\t\t\tif (result == JFileChooser.APPROVE_OPTION) {\n\t\t\t\t\t\t// Set the approved current directory to FileControl.\n\t\t\t\t\t\tFileControl.lastSavedDirectory = chooser.getCurrentDirectory();\n\n\t\t\t\t\t\ttry (RandomAccessFile cacheFile = new RandomAccessFile(LevelEditor.SAVED_PATH_DATA, \"rw\")) {\n\t\t\t\t\t\t\tBufferedImage img = this.editor.drawingBoardPanel.getMapImage();\n\t\t\t\t\t\t\tif (img == null)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tFile file = chooser.getSelectedFile();\n\t\t\t\t\t\t\tString filename = file.getName();\n\t\t\t\t\t\t\twhile (filename.endsWith(\".png\"))\n\t\t\t\t\t\t\t\tfilename = filename.substring(0, filename.length() - \".png\".length());\n\t\t\t\t\t\t\tImageIO.write(\n\t\t\t\t\t\t\t\timg, \"png\", new File(\n\t\t\t\t\t\t\t\t\tFileControl.lastSavedDirectory.getAbsolutePath() + \"\\\\\" + filename + \".png\"\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.editor.setMapAreaName(filename);\n\n\t\t\t\t\t\t\t// Storing the last approved current directory into the cache file.\n\t\t\t\t\t\t\tthis.cacheDirectories.set(LevelEditor.FileControlIndex, FileControl.lastSavedDirectory.getAbsolutePath());\n\t\t\t\t\t\t\tthis.storeCachedDirectories(cacheFile);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\t\tDebug.exception(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 2: { // Open\n\t\t\t\t\t// String backupPath = LevelEditor.SAVED_PATH_DATA;\n\t\t\t\t\ttry (RandomAccessFile raf = new RandomAccessFile(LevelEditor.SAVED_PATH_DATA, \"r\")) {\n\t\t\t\t\t\tthis.fetchCachedDirectories(raf);\n\t\t\t\t\t\tFileControl.lastSavedDirectory = new File(this.cacheDirectories.get(LevelEditor.FileControlIndex));\n\t\t\t\t\t}\n\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\tFileControl.lastSavedDirectory = new File(FileControl.defaultPath);\n\t\t\t\t\t}\n\n\t\t\t\t\tJList<Class<?>> list = this.findFileList(chooser);\n\t\t\t\t\tLOOP_TEMP1:\n\t\t\t\t\tfor (MouseListener l : list.getMouseListeners()) {\n\t\t\t\t\t\t// If \"FilePane\" cannot be found in the name of the class object, we continue iterating.\n\t\t\t\t\t\tif (l.getClass().getName().indexOf(\"FilePane\") < 0)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tlist.removeMouseListener(l);\n\t\t\t\t\t\tlist.addMouseListener(mouseListener);\n\t\t\t\t\t\tbreak LOOP_TEMP1;\n\t\t\t\t\t}\n\t\t\t\t\tchooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);\n\t\t\t\t\tchooser.setCurrentDirectory(FileControl.lastSavedDirectory);\n\t\t\t\t\tchooser.setFileFilter(new FileNameExtensionFilter(\"PNG files\", \"png\"));\n\t\t\t\t\tchooser.setVisible(true);\n\t\t\t\t\tint answer = chooser.showOpenDialog(null);\n\t\t\t\t\tif (answer == JFileChooser.APPROVE_OPTION) {\n\t\t\t\t\t\ttry (RandomAccessFile cacheFile = new RandomAccessFile(LevelEditor.SAVED_PATH_DATA, \"rw\")) {\n\t\t\t\t\t\t\tFile f = chooser.getSelectedFile();\n\t\t\t\t\t\t\tFileControl.lastSavedDirectory = f.getParentFile();\n\t\t\t\t\t\t\tEditorConstants.metadata = Metadata.Tilesets;\n\t\t\t\t\t\t\tthis.editor.setTitle(LevelEditor.NAME_TITLE + \" - \" + f);\n\t\t\t\t\t\t\tBufferedImage image = ImageIO.read(f);\n\t\t\t\t\t\t\tthis.editor.drawingBoardPanel.openMapImage(image);\n\t\t\t\t\t\t\tthis.editor.setMapAreaName(f.getName().substring(0, f.getName().length() - \".png\".length()));\n\n\t\t\t\t\t\t\t// Setting Area ID\n\t\t\t\t\t\t\tTilePropertiesPanel panel = this.editor.controlPanel.getPropertiesPanel();\n\t\t\t\t\t\t\tpanel.areaIDInputField.setText(Integer.toString(this.editor.getUniqueAreaID()));\n\n\t\t\t\t\t\t\t// Storing the last approved current directory into the cache file.\n\t\t\t\t\t\t\tthis.cacheDirectories.set(LevelEditor.FileControlIndex, FileControl.lastSavedDirectory.getAbsolutePath());\n\t\t\t\t\t\t\tthis.storeCachedDirectories(cacheFile);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\t\tDebug.exception(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 4: { // Tileset\n\t\t\t\t\tEditorConstants.metadata = Metadata.Tilesets;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 5: { // Trigger\n\t\t\t\t\tEditorConstants.metadata = Metadata.Triggers;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 6: { // Non-Playable Characters (NPC)\n\t\t\t\t\tEditorConstants.metadata = Metadata.NonPlayableCharacters;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 7: {// Script editor\n\t\t\t\t\tif (this.editor.scriptEditor == null) {\n\t\t\t\t\t\tthis.editor.scriptEditor = new ScriptEditor(ScriptEditor.TITLE, this.editor);\n\t\t\t\t\t\tbutton.setEnabled(false);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (NumberFormatException e) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// --------------------------------------------------------------------------------\n\t// Private methods\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate JList<Class<?>> findFileList(Component comp) {\n\t\tif (comp instanceof JList) {\n\t\t\treturn (JList<Class<?>>) comp;\n\t\t}\n\t\tif (comp instanceof Container) {\n\t\t\tfor (Component c : ((Container) comp).getComponents()) {\n\t\t\t\tJList<Class<?>> list = this.findFileList(c);\n\t\t\t\tif (list != null) {\n\t\t\t\t\treturn list;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate void fetchCachedDirectories(RandomAccessFile file) throws IOException {\n\t\tString buffer = null;\n\t\tfile.seek(0);\n\t\tthis.cacheDirectories.clear();\n\t\twhile ((buffer = file.readLine()) != null) {\n\t\t\tthis.cacheDirectories.add(buffer);\n\t\t}\n\t}\n\n\tprivate void storeCachedDirectories(RandomAccessFile file) throws IOException {\n\t\tfile.setLength(0);\n\t\tfile.seek(0);\n\t\tfor (String buffer : this.cacheDirectories) {\n\t\t\tfile.writeBytes(buffer);\n\t\t\tfile.write(System.lineSeparator().getBytes());\n\t\t}\n\t}\n}", "public class LevelEditor extends JFrame {\n\tpublic static final int WIDTH = 160;\n\tpublic static final int HEIGHT = 144;\n\tpublic static final int SIZE = 4;\n\tpublic static final String NAME_TITLE = \"Level Editor (Hobby)\";\n\tpublic static final String SAVED_PATH_DATA = \"cache.ini\";\n\tpublic static final int CHECKSUM_MAX_BYTES_LENGTH = 16;\n\tpublic static final String defaultPath = Paths.get(\"\").toAbsolutePath().toString();\n\n\t// For cache directory path index, fixed index in the array list.\n\tpublic static final int FileControlIndex = 0;\n\n\tprivate static final long serialVersionUID = -8739477187675627751L;\n\n\tpublic ControlPanel controlPanel;\n\tpublic FileControl fileControlPanel;\n\tpublic DrawingBoard drawingBoardPanel;\n\tpublic StatusPanel statusPanel;\n\tpublic SelectionDropdownMenu properties;\n\tpublic ScriptEditor scriptEditor;\n\n\tpublic boolean running;\n\tpublic String message;\n\tpublic EditorInput input;\n\n\tprivate int uniqueAreaID;\n\tprivate String sha2Checksum = \"\";\n\n\t@SuppressWarnings(\"unused\")\n\tprivate String mapAreaName;\n\n\tpublic LevelEditor(String name) {\n\t\tsuper(name);\n\t\tthis.running = true;\n\t\tDimension size = new Dimension(LevelEditor.WIDTH * LevelEditor.SIZE, LevelEditor.HEIGHT * LevelEditor.SIZE);\n\t\tthis.setSize(size);\n\t\tthis.setPreferredSize(size);\n\t\tthis.setMinimumSize(size);\n\t\tthis.setMaximumSize(size);\n\t\tthis.setLayout(new BorderLayout());\n\t\tthis.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n\t\tthis.pack();\n\t\tthis.setSize(size);// Mac issue.\n\t\tthis.setPreferredSize(size); // Mac issue.\n\t\tthis.setMinimumSize(size); // Mac issue.\n\t\tthis.setMaximumSize(size); // Mac issue.\n\t\tthis.setVisible(true);\n\n\t\tthis.addWindowListener(new WindowAdapter() {\n\t\t\t@Override\n\t\t\tpublic void windowClosing(WindowEvent event) {\n\t\t\t\tLevelEditor.this.running = false;\n\t\t\t\tSwingUtilities.invokeLater(() -> Runtime.getRuntime().exit(0));\n\t\t\t}\n\t\t});\n\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tboolean shouldValidate = false;\n\t\t\tif (LevelEditor.this.input == null) {\n\t\t\t\tLevelEditor.this.input = new EditorInput(editor.LevelEditor.this);\n\t\t\t\tLevelEditor.this.addMouseListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.addMouseMotionListener(LevelEditor.this.input);\n\t\t\t}\n\t\t\tif (LevelEditor.this.fileControlPanel == null) {\n\t\t\t\tLevelEditor.this.fileControlPanel = new FileControl(editor.LevelEditor.this);\n\t\t\t\tLevelEditor.this.fileControlPanel.addMouseListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.fileControlPanel.addMouseMotionListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.add(LevelEditor.this.fileControlPanel, BorderLayout.NORTH);\n\t\t\t\tshouldValidate = true;\n\t\t\t}\n\t\t\tif (LevelEditor.this.controlPanel == null) {\n\t\t\t\tLevelEditor.this.controlPanel = new ControlPanel(editor.LevelEditor.this);\n\t\t\t\tLevelEditor.this.controlPanel.addMouseListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.controlPanel.addMouseMotionListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.add(LevelEditor.this.controlPanel, BorderLayout.WEST);\n\t\t\t\tshouldValidate = true;\n\t\t\t}\n\t\t\tif (LevelEditor.this.drawingBoardPanel == null) {\n\t\t\t\tLevelEditor.this.drawingBoardPanel = new DrawingBoard(editor.LevelEditor.this, 20, 20);\n\t\t\t\tLevelEditor.this.drawingBoardPanel.setName(\"DrawingBoardThread\");\n\t\t\t\tLevelEditor.this.drawingBoardPanel.addMouseListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.drawingBoardPanel.addMouseMotionListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.add(LevelEditor.this.drawingBoardPanel, BorderLayout.CENTER);\n\t\t\t\tLevelEditor.this.drawingBoardPanel.start();\n\t\t\t\tshouldValidate = true;\n\t\t\t}\n\n\t\t\t// TODO: Add Trigger properties here.\n\t\t\tif (LevelEditor.this.properties == null) {\n\t\t\t\tLevelEditor.this.properties = new SelectionDropdownMenu(editor.LevelEditor.this);\n\t\t\t\tLevelEditor.this.properties.addMouseListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.properties.addMouseMotionListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.add(LevelEditor.this.properties, BorderLayout.EAST);\n\t\t\t\tshouldValidate = true;\n\t\t\t}\n\n\t\t\tif (LevelEditor.this.statusPanel == null) {\n\t\t\t\tLevelEditor.this.statusPanel = new StatusPanel();\n\t\t\t\tLevelEditor.this.statusPanel.addMouseListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.statusPanel.addMouseMotionListener(LevelEditor.this.input);\n\t\t\t\tLevelEditor.this.add(LevelEditor.this.statusPanel, BorderLayout.SOUTH);\n\t\t\t\tshouldValidate = true;\n\t\t\t}\n\t\t\tLevelEditor.this.initialize();\n\t\t\tif (shouldValidate) {\n\t\t\t\tLevelEditor.this.validate();\n\t\t\t}\n\t\t});\n\t\tthis.createOrReadCache();\n\t}\n\n\t/**\n\t * <p>\n\t * Generates a cache file for saving the last known directory the editor knew of.\n\t * </p>\n\t *\n\t * <p>\n\t * Upon initialization, the default saved directory will be the editor's file location path.\n\t * </p>\n\t *\n\t * @return Nothing.\n\t */\n\tpublic void createOrReadCache() {\n\t\tList<String> cachedDirectoryPaths = new ArrayList<>();\n\t\tFile file = new File(LevelEditor.SAVED_PATH_DATA);\n\t\tif (!file.exists()) {\n\t\t\t// Set the default paths first\n\t\t\tFileControl.lastSavedDirectory = new File(LevelEditor.defaultPath);\n\t\t\tScriptEditor.lastSavedDirectory = FileControl.lastSavedDirectory;\n\n\t\t\tcachedDirectoryPaths.add(FileControl.lastSavedDirectory.getAbsolutePath());\n\n\t\t\ttry (RandomAccessFile raf = new RandomAccessFile(file, \"rw\")) {\n\t\t\t\tthis.storeCachedDirectories(raf, cachedDirectoryPaths);\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tDebug.exception(e);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\ttry (RandomAccessFile raf = new RandomAccessFile(file, \"r\")) {\n\t\t\t\tthis.fetchCachedDirectories(raf, cachedDirectoryPaths);\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tDebug.exception(e);\n\t\t\t}\n\n\t\t\tFileControl.lastSavedDirectory = new File(cachedDirectoryPaths.get(LevelEditor.FileControlIndex));\n\t\t\tScriptEditor.lastSavedDirectory = FileControl.lastSavedDirectory;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void validate() {\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tif (LevelEditor.this.statusPanel != null) {\n\t\t\t\tStringBuilder builder = new StringBuilder();\n\t\t\t\tbuilder.append(\"Picked: \" + editor.LevelEditor.this.controlPanel.getPickedEntityName() + \" \");\n\t\t\t\tif (!LevelEditor.this.input.isDragging()) {\n\t\t\t\t\t// This is how we do the [panning + pixel position] math.\n\t\t\t\t\tint w = 0;\n\t\t\t\t\tint h = 0;\n\t\t\t\t\tint temp = 0;\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttemp = (LevelEditor.this.input.offsetX + LevelEditor.this.input.mouseX);\n\t\t\t\t\t\tif (temp >= 0)\n\t\t\t\t\t\t\tw = temp / Tileable.WIDTH;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tw = (temp / Tileable.WIDTH) - 1;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e1) {\n\t\t\t\t\t\tw = (LevelEditor.this.input.offsetX + LevelEditor.this.input.mouseX) / (LevelEditor.WIDTH * LevelEditor.SIZE);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttemp = (LevelEditor.this.input.offsetY + LevelEditor.this.input.mouseY);\n\t\t\t\t\t\tif (temp >= 0)\n\t\t\t\t\t\t\th = temp / Tileable.HEIGHT;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\th = (temp / Tileable.HEIGHT) - 1;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e2) {\n\t\t\t\t\t\th = (LevelEditor.this.input.offsetY + LevelEditor.this.input.mouseY) / (LevelEditor.WIDTH * LevelEditor.SIZE);\n\t\t\t\t\t}\n\t\t\t\t\tLevelEditor.this.statusPanel.setMousePositionText(w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tLevelEditor.this.statusPanel.setMousePositionText(\n\t\t\t\t\t\t\tLevelEditor.this.input.oldX / LevelEditor.this.drawingBoardPanel.getBitmapWidth(),\n\t\t\t\t\t\t\tLevelEditor.this.input.oldY / LevelEditor.this.drawingBoardPanel.getBitmapHeight()\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e3) {\n\t\t\t\t\t\tLevelEditor.this.statusPanel.setMousePositionText(0, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tLevelEditor.this.statusPanel.setStatusMessageText(builder.toString());\n\t\t\t\tLevelEditor.this.statusPanel.setChecksumLabel(LevelEditor.this.getChecksum());\n\t\t\t}\n\n\t\t\tif (LevelEditor.this.controlPanel != null) {\n\t\t\t\tLevelEditor.this.controlPanel.validate();\n\t\t\t\tif (LevelEditor.this.controlPanel.getPropertiesPanel() != null)\n\t\t\t\t\tLevelEditor.this.controlPanel.getPropertiesPanel().validate();\n\t\t\t}\n\t\t\tif (LevelEditor.this.fileControlPanel != null)\n\t\t\t\tLevelEditor.this.fileControlPanel.validate();\n\t\t\tif (LevelEditor.this.drawingBoardPanel != null)\n\t\t\t\tLevelEditor.this.drawingBoardPanel.validate();\n\t\t\tif (LevelEditor.this.properties != null)\n\t\t\t\tLevelEditor.this.properties.validate();\n\t\t\tif (LevelEditor.this.statusPanel != null)\n\t\t\t\tLevelEditor.this.statusPanel.validate();\n\t\t});\n\t\tsuper.validate();\n\t}\n\n\tpublic final void initialize() {\n\t\tEditorConstants.metadata = Metadata.Tilesets;\n\t\tthis.generateChecksum();\n\t\tthis.drawingBoardPanel.newImage(15, 15);\n\t\tthis.setMapAreaName(\"Untitled\");\n\t}\n\n\tpublic void setMapAreaName(String name) {\n\t\tthis.mapAreaName = name;\n\t}\n\n\tpublic int getUniqueAreaID() {\n\t\treturn this.uniqueAreaID;\n\t}\n\n\tpublic void setUniqueAreaID(int uniqueAreaID) {\n\t\tthis.uniqueAreaID = uniqueAreaID;\n\t}\n\n\tpublic String getChecksum() {\n\t\tif (this.sha2Checksum == null || this.sha2Checksum.trim().isBlank() || this.sha2Checksum.trim().isEmpty()) {\n\t\t\treturn this.generateChecksum();\n\t\t}\n\t\treturn this.sha2Checksum;\n\t}\n\n\tpublic int setChecksum(int[] pixels, int startIndex, int readLength) {\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\tint readIndex = startIndex;\n\t\tfor (int i = 0; i < readLength; i++, readIndex++) {\n\t\t\tint pixel = pixels[readIndex];\n\t\t\tbaos.write((pixel >> 24) & 0xFF);\n\t\t\tbaos.write((pixel >> 16) & 0xFF);\n\t\t\tbaos.write((pixel >> 8) & 0xFF);\n\t\t\tbaos.write(pixel & 0xFF);\n\t\t}\n\t\t// SHA-512 checksum are written using ASCII.\n\t\tString result = baos.toString(StandardCharsets.US_ASCII);\n\t\tthis.sha2Checksum = result;\n\t\treturn readIndex;\n\t}\n\n\tpublic String generateChecksum() {\n\t\tthis.sha2Checksum = Sha2Utils.generateRandom(UUID.randomUUID().toString()).substring(0, LevelEditor.CHECKSUM_MAX_BYTES_LENGTH);\n\t\treturn this.sha2Checksum;\n\t}\n\n\t// --------------------------------------------------------------------------------\n\t// Main method\n\n\tpublic static void main(String[] args) {\n\t\tnew LevelEditor(LevelEditor.NAME_TITLE);\n\t}\n\n\t// --------------------------------------------------------------------------------\n\t// Private methods\n\n\tprivate void fetchCachedDirectories(RandomAccessFile file, List<String> output) throws IOException {\n\t\tString buffer = null;\n\t\tfile.seek(0);\n\t\toutput.clear();\n\t\twhile ((buffer = file.readLine()) != null) {\n\t\t\toutput.add(buffer);\n\t\t}\n\t}\n\n\tprivate void storeCachedDirectories(RandomAccessFile file, List<String> input) throws IOException {\n\t\tfile.setLength(0);\n\t\tfile.seek(0);\n\t\tfor (String buffer : input) {\n\t\t\tfile.writeBytes(buffer);\n\t\t\tfile.write(System.lineSeparator().getBytes());\n\t\t}\n\t}\n}", "public class Trigger {\n\t/**\n\t * This represents the trigger ID is not an NPC trigger.\n\t */\n\tpublic static final short NPC_TRIGGER_ID_NONE = 0;\n\n\tprivate byte x, y; // This occupies the AR value in the pixel color, ARGB space.\n\tprivate short triggerID; // This occupies the GB value in the pixel color, ARGB space.\n\tprivate short npcTriggerID; // This occupies the GB value in the pixel color, ARGB space.\n\tprivate String name;\n\tprivate String script;\n\tprivate String checksum;\n\tprivate boolean isNpcTrigger;\n\n\tprivate boolean[] valuesHasBeenSet;\n\n\tprivate static final int FLAG_PositionX = 0;\n\tprivate static final int FLAG_PositionY = 1;\n\tprivate static final int FLAG_TriggerID = 2;\n\tprivate static final int FLAG_TriggerScript = 3;\n\tprivate static final int FLAG_NpcTriggerID = 4;\n\n\tpublic Trigger() {\n\t\tthis.valuesHasBeenSet = new boolean[Arrays.asList(\n\t\t\tTrigger.FLAG_PositionX,\n\t\t\tTrigger.FLAG_PositionY,\n\t\t\tTrigger.FLAG_TriggerID,\n\t\t\tTrigger.FLAG_TriggerScript,\n\t\t\tTrigger.FLAG_NpcTriggerID\n\t\t).size()];\n\t\tthis.reset();\n\t}\n\n\tpublic void reset() {\n\t\tthis.x = this.y = -1;\n\t\tthis.triggerID = 0;\n\t\tthis.npcTriggerID = Trigger.NPC_TRIGGER_ID_NONE;\n\t\tthis.name = \"<Untitled>\";\n\t\tArrays.fill(this.valuesHasBeenSet, false);\n\t}\n\n\tpublic int getDataValue() {\n\t\treturn (this.x << 24) | (this.y << 16) | (this.triggerID & 0xFFFF);\n\t}\n\n\tpublic int getNpcDataValue() {\n\t\t// The higher 8 bits are to be reserved for something else.\n\t\treturn this.npcTriggerID;\n\t}\n\n\tpublic void setTriggerPositionX(byte x) {\n\t\tthis.valuesHasBeenSet[Trigger.FLAG_PositionX] = true;\n\t\tthis.x = x;\n\t}\n\n\tpublic void setTriggerPositionY(byte y) {\n\t\tthis.valuesHasBeenSet[Trigger.FLAG_PositionY] = true;\n\t\tthis.y = y;\n\t}\n\n\tpublic void setTriggerID(short value) {\n\t\tthis.valuesHasBeenSet[Trigger.FLAG_TriggerID] = true;\n\t\tthis.triggerID = value;\n\t}\n\n\tpublic void setScript(String script) {\n\t\tthis.script = script;\n\t}\n\n\tpublic boolean isPositionXSet() {\n\t\treturn this.valuesHasBeenSet[Trigger.FLAG_PositionX];\n\t}\n\n\tpublic boolean isPositionYSet() {\n\t\treturn this.valuesHasBeenSet[Trigger.FLAG_PositionY];\n\t}\n\n\tpublic boolean isTriggerIDSet() {\n\t\treturn this.valuesHasBeenSet[Trigger.FLAG_TriggerID] || this.valuesHasBeenSet[Trigger.FLAG_NpcTriggerID];\n\t}\n\n\tpublic boolean isTriggerScriptSet() {\n\t\treturn this.valuesHasBeenSet[Trigger.FLAG_TriggerScript];\n\t}\n\n\tpublic boolean isNpcTrigger() {\n\t\treturn this.isNpcTrigger;\n\t}\n\n\tpublic void setNpcTrigger(boolean state) {\n\t\tthis.isNpcTrigger = state;\n\t}\n\n\tpublic void setNpcTriggerID(short npcTriggerId) {\n\t\tthis.npcTriggerID = npcTriggerId;\n\t\tif (!this.isNpcTrigger && npcTriggerId > Trigger.NPC_TRIGGER_ID_NONE) {\n\t\t\tthis.setNpcTrigger(true);\n\t\t\tthis.valuesHasBeenSet[Trigger.FLAG_NpcTriggerID] = true;\n\t\t}\n\t}\n\n\tpublic boolean areRequiredFieldsAllSet() {\n\t\tboolean result = this.isPositionXSet();\n\t\tresult = result && this.isPositionYSet();\n\t\treturn result && this.isTriggerIDSet();\n\t}\n\n\tpublic byte getPositionX() {\n\t\treturn this.x;\n\t}\n\n\tpublic byte getPositionY() {\n\t\treturn this.y;\n\t}\n\n\tpublic boolean hasValidPosition() {\n\t\treturn !(this.x == -1 || this.y == -1);\n\t}\n\n\tpublic short getTriggerID() {\n\t\treturn this.triggerID;\n\t}\n\n\tpublic short getNpcTriggerID() {\n\t\treturn this.npcTriggerID;\n\t}\n\n\tpublic boolean checkTriggerID(short triggerId) {\n\t\treturn this.triggerID == triggerId;\n\t}\n\n\tpublic boolean checkTriggerID(int triggerId) {\n\t\treturn this.checkTriggerID((short) triggerId);\n\t}\n\n\tpublic boolean checkNpcTriggerID(short npcTriggerId) {\n\t\treturn this.npcTriggerID == npcTriggerId;\n\t}\n\n\tpublic boolean checkNpcTriggerID(int npcTriggerId) {\n\t\treturn this.checkNpcTriggerID((short) npcTriggerId);\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\tpublic String getScript() {\n\t\treturn this.script;\n\t}\n\n\tpublic String getChecksum() {\n\t\treturn this.checksum;\n\t}\n\n\tpublic void setChecksum(String checksum) {\n\t\tthis.checksum = checksum;\n\t}\n\n\tpublic boolean equalsTriggerId(short otherTriggerId) {\n\t\treturn this.triggerID == otherTriggerId;\n\t}\n\n\tpublic boolean equalsTriggerId(int otherTriggerId) {\n\t\treturn this.equalsTriggerId((short) (otherTriggerId & 0xFFFF));\n\t}\n\n\tpublic boolean isEraser() {\n\t\treturn (this.triggerID == 0 && this.npcTriggerID == 0);\n\t}\n\n\tpublic static Trigger createEraser() {\n\t\tTrigger trigger = new Trigger();\n\t\ttrigger.setTriggerID((short) 0);\n\t\ttrigger.setName(\"Eraser\");\n\t\treturn trigger;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((this.name == null) ? 0 : this.name.hashCode());\n\t\tresult = prime * result + this.triggerID;\n\t\tresult = prime * result + this.x;\n\t\treturn prime * result + this.y;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif ((obj == null) || (this.getClass() != obj.getClass())) {\n\t\t\treturn false;\n\t\t}\n\t\tTrigger other = (Trigger) obj;\n\t\tif (this.name == null) {\n\t\t\tif (other.name != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.name.equals(other.name)) {\n\t\t\treturn false;\n\t\t}\n\t\tif ((this.triggerID != other.triggerID) || (this.x != other.x) || (this.y != other.y)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n}" ]
import java.awt.Component; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.HashMap; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.SwingConstants; import javax.swing.filechooser.FileNameExtensionFilter; import editor.EditorFileChooser; import editor.EditorMouseListener; import editor.FileControl; import editor.LevelEditor; import editor.Trigger;
package script_editor; //TODO (6/25/2015): Save the already-opened file without needing to open up a JFileChooser. public class ScriptToolbar extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; private final ScriptEditor editor; private final String[] tags = { "New Script", "Save Script", "Open Script", "" }; private final HashMap<String, JButton> buttonCache = new HashMap<>(); public ScriptToolbar(ScriptEditor editor) { super(); this.editor = editor; this.setLayout(new GridLayout(1, this.tags.length)); this.createButtons(); } @Override public void actionPerformed(ActionEvent event) { final EditorFileChooser chooser = new EditorFileChooser(); final EditorMouseListener mouseListener = new EditorMouseListener(chooser); switch (Integer.valueOf(event.getActionCommand())) { case 0: { // New script this.editor.scriptChanger.clearTextFields(); JList<Trigger> triggerList = this.editor.scriptViewer.getTriggerList(); DefaultListModel<Trigger> model = (DefaultListModel<Trigger>) triggerList.getModel(); model.clear(); JComboBox<Trigger> triggerComboBox = this.editor.parent.properties.getTriggerList(); DefaultComboBoxModel<Trigger> triggerComboModel = (DefaultComboBoxModel<Trigger>) triggerComboBox .getModel(); triggerComboModel.removeAllElements(); Trigger trigger = new Trigger(); trigger.setTriggerID((short) 0); trigger.setName("Eraser"); triggerComboModel.addElement(trigger); triggerComboBox.setSelectedIndex(0); triggerList.clearSelection(); this.editor.setModifiedFlag(false); this.editor.setTitle("Script Editor (Hobby) - Untitled.script"); this.editor.setScriptName("Untitled"); this.editor.scriptChanger.disableComponent(); this.editor.parent.revalidate(); break; } case 1: { // Save script try (RandomAccessFile raf = new RandomAccessFile(LevelEditor.SAVED_PATH_DATA, "rw")) { raf.readLine(); // The second line in the cache is for the Script Editor. ScriptEditor.lastSavedDirectory = new File(raf.readLine()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) {
ScriptEditor.lastSavedDirectory = FileControl.lastSavedDirectory;
2
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/compression/DefaultCompressionCodecResolver.java
[ "public interface CompressionCodec {\n\n /**\n * The compression algorithm name to use as the JWT's {@code zip} header value.\n *\n * @return the compression algorithm name to use as the JWT's {@code zip} header value.\n */\n String getAlgorithmName();\n\n /**\n * Compresses the specified byte array according to the compression {@link #getAlgorithmName() algorithm}.\n *\n * @param payload bytes to compress\n * @return compressed bytes\n * @throws CompressionException if the specified byte array cannot be compressed according to the compression\n * {@link #getAlgorithmName() algorithm}.\n */\n byte[] compress(byte[] payload) throws CompressionException;\n\n /**\n * Decompresses the specified compressed byte array according to the compression\n * {@link #getAlgorithmName() algorithm}. The specified byte array must already be in compressed form\n * according to the {@link #getAlgorithmName() algorithm}.\n *\n * @param compressed compressed bytes\n * @return decompressed bytes\n * @throws CompressionException if the specified byte array cannot be decompressed according to the compression\n * {@link #getAlgorithmName() algorithm}.\n */\n byte[] decompress(byte[] compressed) throws CompressionException;\n}", "public interface CompressionCodecResolver {\n\n /**\n * Looks for a JWT {@code zip} header, and if found, returns the corresponding {@link CompressionCodec} the parser\n * can use to decompress the JWT body.\n *\n * @param header of the JWT\n * @return CompressionCodec matching the {@code zip} header, or null if there is no {@code zip} header.\n * @throws CompressionException if a {@code zip} header value is found and not supported.\n */\n CompressionCodec resolveCompressionCodec(Header header) throws CompressionException;\n\n}", "public final class CompressionCodecs {\n\n private CompressionCodecs() {\n } //prevent external instantiation\n\n /**\n * Codec implementing the <a href=\"https://tools.ietf.org/html/rfc7518\">JWA</a> standard\n * <a href=\"https://en.wikipedia.org/wiki/DEFLATE\">deflate</a> compression algorithm\n */\n public static final CompressionCodec DEFLATE =\n Classes.newInstance(\"io.jsonwebtoken.impl.compression.DeflateCompressionCodec\");\n\n /**\n * Codec implementing the <a href=\"https://en.wikipedia.org/wiki/Gzip\">gzip</a> compression algorithm.\n * <h3>Compatibility Warning</h3>\n * <p><b>This is not a standard JWA compression algorithm</b>. Be sure to use this only when you are confident\n * that all parties accessing the token support the gzip algorithm.</p>\n * <p>If you're concerned about compatibility, the {@link #DEFLATE DEFLATE} code is JWA standards-compliant.</p>\n */\n public static final CompressionCodec GZIP =\n Classes.newInstance(\"io.jsonwebtoken.impl.compression.GzipCompressionCodec\");\n\n}", "public interface Header<T extends Header<T>> extends Map<String,Object> {\n\n /** JWT {@code Type} (typ) value: <code>\"JWT\"</code> */\n public static final String JWT_TYPE = \"JWT\";\n\n /** JWT {@code Type} header parameter name: <code>\"typ\"</code> */\n public static final String TYPE = \"typ\";\n\n /** JWT {@code Content Type} header parameter name: <code>\"cty\"</code> */\n public static final String CONTENT_TYPE = \"cty\";\n\n /** JWT {@code Compression Algorithm} header parameter name: <code>\"zip\"</code> */\n public static final String COMPRESSION_ALGORITHM = \"zip\";\n\n /** JJWT legacy/deprecated compression algorithm header parameter name: <code>\"calg\"</code>\n * @deprecated use {@link #COMPRESSION_ALGORITHM} instead. */\n @Deprecated\n public static final String DEPRECATED_COMPRESSION_ALGORITHM = \"calg\";\n\n /**\n * Returns the <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-5.1\">\n * <code>typ</code></a> (type) header value or {@code null} if not present.\n *\n * @return the {@code typ} header value or {@code null} if not present.\n */\n String getType();\n\n /**\n * Sets the JWT <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-5.1\">\n * <code>typ</code></a> (Type) header value. A {@code null} value will remove the property from the JSON map.\n *\n * @param typ the JWT JOSE {@code typ} header value or {@code null} to remove the property from the JSON map.\n * @return the {@code Header} instance for method chaining.\n */\n T setType(String typ);\n\n /**\n * Returns the <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-5.2\">\n * <code>cty</code></a> (Content Type) header value or {@code null} if not present.\n *\n * <p>In the normal case where nested signing or encryption operations are not employed (i.e. a compact\n * serialization JWT), the use of this header parameter is NOT RECOMMENDED. In the case that nested\n * signing or encryption is employed, this Header Parameter MUST be present; in this case, the value MUST be\n * {@code JWT}, to indicate that a Nested JWT is carried in this JWT. While media type names are not\n * case-sensitive, it is RECOMMENDED that {@code JWT} always be spelled using uppercase characters for\n * compatibility with legacy implementations. See\n * <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#appendix-A.2\">JWT Appendix A.2</a> for\n * an example of a Nested JWT.</p>\n *\n * @return the {@code typ} header parameter value or {@code null} if not present.\n */\n String getContentType();\n\n /**\n * Sets the JWT <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-5.2\">\n * <code>cty</code></a> (Content Type) header parameter value. A {@code null} value will remove the property from\n * the JSON map.\n *\n * <p>In the normal case where nested signing or encryption operations are not employed (i.e. a compact\n * serialization JWT), the use of this header parameter is NOT RECOMMENDED. In the case that nested\n * signing or encryption is employed, this Header Parameter MUST be present; in this case, the value MUST be\n * {@code JWT}, to indicate that a Nested JWT is carried in this JWT. While media type names are not\n * case-sensitive, it is RECOMMENDED that {@code JWT} always be spelled using uppercase characters for\n * compatibility with legacy implementations. See\n * <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#appendix-A.2\">JWT Appendix A.2</a> for\n * an example of a Nested JWT.</p>\n *\n * @param cty the JWT JOSE {@code cty} header value or {@code null} to remove the property from the JSON map.\n * @return the {@code Header} instance for method chaining.\n */\n T setContentType(String cty);\n\n /**\n * Returns the JWT <code>zip</code> (Compression Algorithm) header value or {@code null} if not present.\n *\n * @return the {@code zip} header parameter value or {@code null} if not present.\n * @since 0.6.0\n */\n String getCompressionAlgorithm();\n\n /**\n * Sets the JWT <code>zip</code> (Compression Algorithm) header parameter value. A {@code null} value will remove\n * the property from the JSON map.\n *\n * <p>The compression algorithm is NOT part of the <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25\">JWT specification</a>\n * and must be used carefully since, is not expected that other libraries (including previous versions of this one)\n * be able to deserialize a compressed JTW body correctly. </p>\n *\n * @param zip the JWT compression algorithm {@code zip} value or {@code null} to remove the property from the JSON map.\n * @return the {@code Header} instance for method chaining.\n * @since 0.6.0\n */\n T setCompressionAlgorithm(String zip);\n\n}", "public final class Assert {\n\n private Assert(){} //prevent instantiation\n\n /**\n * Assert a boolean expression, throwing <code>IllegalArgumentException</code>\n * if the test result is <code>false</code>.\n * <pre class=\"code\">Assert.isTrue(i &gt; 0, \"The value must be greater than zero\");</pre>\n * @param expression a boolean expression\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if expression is <code>false</code>\n */\n public static void isTrue(boolean expression, String message) {\n if (!expression) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert a boolean expression, throwing <code>IllegalArgumentException</code>\n * if the test result is <code>false</code>.\n * <pre class=\"code\">Assert.isTrue(i &gt; 0);</pre>\n * @param expression a boolean expression\n * @throws IllegalArgumentException if expression is <code>false</code>\n */\n public static void isTrue(boolean expression) {\n isTrue(expression, \"[Assertion failed] - this expression must be true\");\n }\n\n /**\n * Assert that an object is <code>null</code> .\n * <pre class=\"code\">Assert.isNull(value, \"The value must be null\");</pre>\n * @param object the object to check\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if the object is not <code>null</code>\n */\n public static void isNull(Object object, String message) {\n if (object != null) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that an object is <code>null</code> .\n * <pre class=\"code\">Assert.isNull(value);</pre>\n * @param object the object to check\n * @throws IllegalArgumentException if the object is not <code>null</code>\n */\n public static void isNull(Object object) {\n isNull(object, \"[Assertion failed] - the object argument must be null\");\n }\n\n /**\n * Assert that an object is not <code>null</code> .\n * <pre class=\"code\">Assert.notNull(clazz, \"The class must not be null\");</pre>\n * @param object the object to check\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if the object is <code>null</code>\n */\n public static void notNull(Object object, String message) {\n if (object == null) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that an object is not <code>null</code> .\n * <pre class=\"code\">Assert.notNull(clazz);</pre>\n * @param object the object to check\n * @throws IllegalArgumentException if the object is <code>null</code>\n */\n public static void notNull(Object object) {\n notNull(object, \"[Assertion failed] - this argument is required; it must not be null\");\n }\n\n /**\n * Assert that the given String is not empty; that is,\n * it must not be <code>null</code> and not the empty String.\n * <pre class=\"code\">Assert.hasLength(name, \"Name must not be empty\");</pre>\n * @param text the String to check\n * @param message the exception message to use if the assertion fails\n * @see Strings#hasLength\n */\n public static void hasLength(String text, String message) {\n if (!Strings.hasLength(text)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that the given String is not empty; that is,\n * it must not be <code>null</code> and not the empty String.\n * <pre class=\"code\">Assert.hasLength(name);</pre>\n * @param text the String to check\n * @see Strings#hasLength\n */\n public static void hasLength(String text) {\n hasLength(text,\n \"[Assertion failed] - this String argument must have length; it must not be null or empty\");\n }\n\n /**\n * Assert that the given String has valid text content; that is, it must not\n * be <code>null</code> and must contain at least one non-whitespace character.\n * <pre class=\"code\">Assert.hasText(name, \"'name' must not be empty\");</pre>\n * @param text the String to check\n * @param message the exception message to use if the assertion fails\n * @see Strings#hasText\n */\n public static void hasText(String text, String message) {\n if (!Strings.hasText(text)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that the given String has valid text content; that is, it must not\n * be <code>null</code> and must contain at least one non-whitespace character.\n * <pre class=\"code\">Assert.hasText(name, \"'name' must not be empty\");</pre>\n * @param text the String to check\n * @see Strings#hasText\n */\n public static void hasText(String text) {\n hasText(text,\n \"[Assertion failed] - this String argument must have text; it must not be null, empty, or blank\");\n }\n\n /**\n * Assert that the given text does not contain the given substring.\n * <pre class=\"code\">Assert.doesNotContain(name, \"rod\", \"Name must not contain 'rod'\");</pre>\n * @param textToSearch the text to search\n * @param substring the substring to find within the text\n * @param message the exception message to use if the assertion fails\n */\n public static void doesNotContain(String textToSearch, String substring, String message) {\n if (Strings.hasLength(textToSearch) && Strings.hasLength(substring) &&\n textToSearch.indexOf(substring) != -1) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that the given text does not contain the given substring.\n * <pre class=\"code\">Assert.doesNotContain(name, \"rod\");</pre>\n * @param textToSearch the text to search\n * @param substring the substring to find within the text\n */\n public static void doesNotContain(String textToSearch, String substring) {\n doesNotContain(textToSearch, substring,\n \"[Assertion failed] - this String argument must not contain the substring [\" + substring + \"]\");\n }\n\n\n /**\n * Assert that an array has elements; that is, it must not be\n * <code>null</code> and must have at least one element.\n * <pre class=\"code\">Assert.notEmpty(array, \"The array must have elements\");</pre>\n * @param array the array to check\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if the object array is <code>null</code> or has no elements\n */\n public static void notEmpty(Object[] array, String message) {\n if (Objects.isEmpty(array)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that an array has elements; that is, it must not be\n * <code>null</code> and must have at least one element.\n * <pre class=\"code\">Assert.notEmpty(array);</pre>\n * @param array the array to check\n * @throws IllegalArgumentException if the object array is <code>null</code> or has no elements\n */\n public static void notEmpty(Object[] array) {\n notEmpty(array, \"[Assertion failed] - this array must not be empty: it must contain at least 1 element\");\n }\n\n public static void notEmpty(byte[] array, String msg) {\n if (Objects.isEmpty(array)) {\n throw new IllegalArgumentException(msg);\n }\n }\n\n /**\n * Assert that an array has no null elements.\n * Note: Does not complain if the array is empty!\n * <pre class=\"code\">Assert.noNullElements(array, \"The array must have non-null elements\");</pre>\n * @param array the array to check\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if the object array contains a <code>null</code> element\n */\n public static void noNullElements(Object[] array, String message) {\n if (array != null) {\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) {\n throw new IllegalArgumentException(message);\n }\n }\n }\n }\n\n /**\n * Assert that an array has no null elements.\n * Note: Does not complain if the array is empty!\n * <pre class=\"code\">Assert.noNullElements(array);</pre>\n * @param array the array to check\n * @throws IllegalArgumentException if the object array contains a <code>null</code> element\n */\n public static void noNullElements(Object[] array) {\n noNullElements(array, \"[Assertion failed] - this array must not contain any null elements\");\n }\n\n /**\n * Assert that a collection has elements; that is, it must not be\n * <code>null</code> and must have at least one element.\n * <pre class=\"code\">Assert.notEmpty(collection, \"Collection must have elements\");</pre>\n * @param collection the collection to check\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if the collection is <code>null</code> or has no elements\n */\n public static void notEmpty(Collection collection, String message) {\n if (Collections.isEmpty(collection)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that a collection has elements; that is, it must not be\n * <code>null</code> and must have at least one element.\n * <pre class=\"code\">Assert.notEmpty(collection, \"Collection must have elements\");</pre>\n * @param collection the collection to check\n * @throws IllegalArgumentException if the collection is <code>null</code> or has no elements\n */\n public static void notEmpty(Collection collection) {\n notEmpty(collection,\n \"[Assertion failed] - this collection must not be empty: it must contain at least 1 element\");\n }\n\n /**\n * Assert that a Map has entries; that is, it must not be <code>null</code>\n * and must have at least one entry.\n * <pre class=\"code\">Assert.notEmpty(map, \"Map must have entries\");</pre>\n * @param map the map to check\n * @param message the exception message to use if the assertion fails\n * @throws IllegalArgumentException if the map is <code>null</code> or has no entries\n */\n public static void notEmpty(Map map, String message) {\n if (Collections.isEmpty(map)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n /**\n * Assert that a Map has entries; that is, it must not be <code>null</code>\n * and must have at least one entry.\n * <pre class=\"code\">Assert.notEmpty(map);</pre>\n * @param map the map to check\n * @throws IllegalArgumentException if the map is <code>null</code> or has no entries\n */\n public static void notEmpty(Map map) {\n notEmpty(map, \"[Assertion failed] - this map must not be empty; it must contain at least one entry\");\n }\n\n\n /**\n * Assert that the provided object is an instance of the provided class.\n * <pre class=\"code\">Assert.instanceOf(Foo.class, foo);</pre>\n * @param clazz the required class\n * @param obj the object to check\n * @throws IllegalArgumentException if the object is not an instance of clazz\n * @see Class#isInstance\n */\n public static void isInstanceOf(Class clazz, Object obj) {\n isInstanceOf(clazz, obj, \"\");\n }\n\n /**\n * Assert that the provided object is an instance of the provided class.\n * <pre class=\"code\">Assert.instanceOf(Foo.class, foo);</pre>\n * @param type the type to check against\n * @param obj the object to check\n * @param message a message which will be prepended to the message produced by\n * the function itself, and which may be used to provide context. It should\n * normally end in a \": \" or \". \" so that the function generate message looks\n * ok when prepended to it.\n * @throws IllegalArgumentException if the object is not an instance of clazz\n * @see Class#isInstance\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 /**\n * Assert that <code>superType.isAssignableFrom(subType)</code> is <code>true</code>.\n * <pre class=\"code\">Assert.isAssignable(Number.class, myClass);</pre>\n * @param superType the super type to check\n * @param subType the sub type to check\n * @throws IllegalArgumentException if the classes are not assignable\n */\n public static void isAssignable(Class superType, Class subType) {\n isAssignable(superType, subType, \"\");\n }\n\n /**\n * Assert that <code>superType.isAssignableFrom(subType)</code> is <code>true</code>.\n * <pre class=\"code\">Assert.isAssignable(Number.class, myClass);</pre>\n * @param superType the super type to check against\n * @param subType the sub type to check\n * @param message a message which will be prepended to the message produced by\n * the function itself, and which may be used to provide context. It should\n * normally end in a \": \" or \". \" so that the function generate message looks\n * ok when prepended to it.\n * @throws IllegalArgumentException if the classes are not assignable\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 /**\n * Assert a boolean expression, throwing <code>IllegalStateException</code>\n * if the test result is <code>false</code>. Call isTrue if you wish to\n * throw IllegalArgumentException on an assertion failure.\n * <pre class=\"code\">Assert.state(id == null, \"The id property must not already be initialized\");</pre>\n * @param expression a boolean expression\n * @param message the exception message to use if the assertion fails\n * @throws IllegalStateException if expression is <code>false</code>\n */\n public static void state(boolean expression, String message) {\n if (!expression) {\n throw new IllegalStateException(message);\n }\n }\n\n /**\n * Assert a boolean expression, throwing {@link IllegalStateException}\n * if the test result is <code>false</code>.\n * <p>Call {@link #isTrue(boolean)} if you wish to\n * throw {@link IllegalArgumentException} on an assertion failure.\n * <pre class=\"code\">Assert.state(id == null);</pre>\n * @param expression a boolean expression\n * @throws IllegalStateException if the supplied expression is <code>false</code>\n */\n public static void state(boolean expression) {\n state(expression, \"[Assertion failed] - this state invariant must be true\");\n }\n\n}", "public final class Services {\n\n private static final List<ClassLoaderAccessor> CLASS_LOADER_ACCESSORS = arrayToList(new ClassLoaderAccessor[] {\n new ClassLoaderAccessor() {\n @Override\n public ClassLoader getClassLoader() {\n return Thread.currentThread().getContextClassLoader();\n }\n },\n new ClassLoaderAccessor() {\n @Override\n public ClassLoader getClassLoader() {\n return Services.class.getClassLoader();\n }\n },\n new ClassLoaderAccessor() {\n @Override\n public ClassLoader getClassLoader() {\n return ClassLoader.getSystemClassLoader();\n }\n }\n });\n\n private Services() {}\n\n /**\n * Loads and instantiates all service implementation of the given SPI class and returns them as a List.\n *\n * @param spi The class of the Service Provider Interface\n * @param <T> The type of the SPI\n * @return An unmodifiable list with an instance of all available implementations of the SPI. No guarantee is given\n * on the order of implementations, if more than one.\n */\n public static <T> List<T> loadAll(Class<T> spi) {\n Assert.notNull(spi, \"Parameter 'spi' must not be null.\");\n\n for (ClassLoaderAccessor classLoaderAccessor : CLASS_LOADER_ACCESSORS) {\n List<T> implementations = loadAll(spi, classLoaderAccessor.getClassLoader());\n if (!implementations.isEmpty()) {\n return Collections.unmodifiableList(implementations);\n }\n }\n\n throw new UnavailableImplementationException(spi);\n }\n\n private static <T> List<T> loadAll(Class<T> spi, ClassLoader classLoader) {\n ServiceLoader<T> serviceLoader = ServiceLoader.load(spi, classLoader);\n List<T> implementations = new ArrayList<>();\n for (T implementation : serviceLoader) {\n implementations.add(implementation);\n }\n return implementations;\n }\n\n /**\n * Loads the first available implementation the given SPI class from the classpath. Uses the {@link ServiceLoader}\n * to find implementations. When multiple implementations are available it will return the first one that it\n * encounters. There is no guarantee with regard to ordering.\n *\n * @param spi The class of the Service Provider Interface\n * @param <T> The type of the SPI\n * @return A new instance of the service.\n * @throws UnavailableImplementationException When no implementation the SPI is available on the classpath.\n */\n public static <T> T loadFirst(Class<T> spi) {\n Assert.notNull(spi, \"Parameter 'spi' must not be null.\");\n\n for (ClassLoaderAccessor classLoaderAccessor : CLASS_LOADER_ACCESSORS) {\n T result = loadFirst(spi, classLoaderAccessor.getClassLoader());\n if (result != null) {\n return result;\n }\n }\n throw new UnavailableImplementationException(spi);\n }\n\n private static <T> T loadFirst(Class<T> spi, ClassLoader classLoader) {\n ServiceLoader<T> serviceLoader = ServiceLoader.load(spi, classLoader);\n if (serviceLoader.iterator().hasNext()) {\n return serviceLoader.iterator().next();\n }\n return null;\n }\n\n private interface ClassLoaderAccessor {\n ClassLoader getClassLoader();\n }\n}", "public final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither <code>null</code> nor of length 0.\n * Note: Will return <code>true</code> for a CharSequence that purely consists of whitespace.\n * <p><pre>\n * Strings.hasLength(null) = false\n * Strings.hasLength(\"\") = false\n * Strings.hasLength(\" \") = true\n * Strings.hasLength(\"Hello\") = true\n * </pre>\n * @param str the CharSequence to check (may be <code>null</code>)\n * @return <code>true</code> if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither <code>null</code> nor of length 0.\n * Note: Will return <code>true</code> for a String that purely consists of whitespace.\n * @param str the String to check (may be <code>null</code>)\n * @return <code>true</code> if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns <code>true</code> if the string not <code>null</code>,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * <p><pre>\n * Strings.hasText(null) = false\n * Strings.hasText(\"\") = false\n * Strings.hasText(\" \") = false\n * Strings.hasText(\"12345\") = true\n * Strings.hasText(\" 12345 \") = true\n * </pre>\n * @param str the CharSequence to check (may be <code>null</code>)\n * @return <code>true</code> if the CharSequence is not <code>null</code>,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns <code>true</code> if the string not <code>null</code>,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be <code>null</code>)\n * @return <code>true</code> if the String is not <code>null</code>, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be <code>null</code>)\n * @return <code>true</code> if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be <code>null</code>)\n * @return <code>true</code> if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim <i>all</i> whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Test if the given String starts with the specified prefix,\n * ignoring upper/lower case.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Test if the given String ends with the specified suffix,\n * ignoring upper/lower case.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Test whether the given string matches the given substring\n * at the given index.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Count the occurrences of the substring in string s.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or <code>null</code> if the input was <code>null</code>\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a <code>String</code>, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be <code>null</code>\n * @return the capitalized String, <code>null</code> if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a <code>String</code>, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be <code>null</code>\n * @return the uncapitalized String, <code>null</code> if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -&gt; \"myfile.txt\".\n * @param path the file path (may be <code>null</code>)\n * @return the extracted filename, or <code>null</code> if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -&gt; \"txt\".\n * @param path the file path (may be <code>null</code>)\n * @return the extracted filename extension, or <code>null</code> if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -&gt; \"mypath/myfile\".\n * @param path the file path (may be <code>null</code>)\n * @return the path with stripped filename extension,\n * or <code>null</code> if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n * <p>The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List<String> pathElements = new LinkedList<String>();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given <code>localeString</code> value into a {@link java.util.Locale}.\n * <p>This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following <code>Locale's</code>\n * <code>toString()</code> format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding <code>Locale</code> instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be <code>null</code>)\n * @param str the String to append\n * @return the new array (never <code>null</code>)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n * <p>The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be <code>null</code>)\n * @param array2 the second array (can be <code>null</code>)\n * @return the new array (<code>null</code> if both given arrays were <code>null</code>)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n * <p>The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be <code>null</code>)\n * @param array2 the second array (can be <code>null</code>)\n * @return the new array (<code>null</code> if both given arrays were <code>null</code>)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List<String> result = new ArrayList<String>();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never <code>null</code>)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (<code>null</code> if the passed-in\n * Collection was <code>null</code>)\n */\n public static String[] toStringArray(Collection<String> collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (<code>null</code> if the passed-in\n * Enumeration was <code>null</code>)\n */\n public static String[] toStringArray(Enumeration<String> enumeration) {\n if (enumeration == null) {\n return null;\n }\n List<String> list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling <code>String.trim()</code> on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or <code>null</code> if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A <code>Properties</code> instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n * <p>Will trim both the key and value before adding them to the\n * <code>Properties</code> instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a <code>Properties</code> instance representing the array contents,\n * or <code>null</code> if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A <code>Properties</code> instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n * <p>Will trim both the key and value before adding them to the\n * <code>Properties</code> instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or <code>null</code> if no removal should occur\n * @return a <code>Properties</code> instance representing the array contents,\n * or <code>null</code> if the array to process was <code>null</code> or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n * <p>The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using <code>delimitedListToStringArray</code>\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * <p>The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using <code>delimitedListToStringArray</code>\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's <code>trim</code>\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (<code>null</code> if the input String\n * was <code>null</code>)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List<String> tokens = new ArrayList<String>();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n * <p>A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n * <p>A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List<String> result = new ArrayList<String>();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for <code>toString()</code> implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator<?> it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for <code>toString()</code> implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection<?> coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for <code>toString()</code> implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection<?> coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for <code>toString()</code> implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for <code>toString()</code> implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}" ]
import io.jsonwebtoken.CompressionCodec; import io.jsonwebtoken.CompressionCodecResolver; import io.jsonwebtoken.CompressionCodecs; import io.jsonwebtoken.CompressionException; import io.jsonwebtoken.Header; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.impl.lang.Services; import io.jsonwebtoken.lang.Strings; import java.util.Collections; import java.util.HashMap; import java.util.Map;
/* * Copyright (C) 2015 jsonwebtoken.io * * 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 io.jsonwebtoken.impl.compression; /** * Default implementation of {@link CompressionCodecResolver} that supports the following: * <p> * <ul> * <li>If the specified JWT {@link Header} does not have a {@code zip} header, this implementation does * nothing and returns {@code null} to the caller, indicating no compression was used.</li> * <li>If the header has a {@code zip} value of {@code DEF}, a {@link DeflateCompressionCodec} will be returned.</li> * <li>If the header has a {@code zip} value of {@code GZIP}, a {@link GzipCompressionCodec} will be returned.</li> * <li>If the header has any other {@code zip} value, a {@link CompressionException} is thrown to reflect an * unrecognized algorithm.</li> * </ul> * * <p>If you want to use a compression algorithm other than {@code DEF} or {@code GZIP}, you must implement your own * {@link CompressionCodecResolver} and specify that when * {@link io.jsonwebtoken.JwtBuilder#compressWith(CompressionCodec) building} and * {@link io.jsonwebtoken.JwtParser#setCompressionCodecResolver(CompressionCodecResolver) parsing} JWTs.</p> * * @see DeflateCompressionCodec * @see GzipCompressionCodec * @since 0.6.0 */ public class DefaultCompressionCodecResolver implements CompressionCodecResolver { private static final String MISSING_COMPRESSION_MESSAGE = "Unable to find an implementation for compression algorithm [%s] using java.util.ServiceLoader. Ensure you include a backing implementation .jar in the classpath, for example jjwt-impl.jar, or your own .jar for custom implementations."; private final Map<String, CompressionCodec> codecs; public DefaultCompressionCodecResolver() { Map<String, CompressionCodec> codecMap = new HashMap<>(); for (CompressionCodec codec : Services.loadAll(CompressionCodec.class)) { codecMap.put(codec.getAlgorithmName().toUpperCase(), codec); } codecMap.put(CompressionCodecs.DEFLATE.getAlgorithmName().toUpperCase(), CompressionCodecs.DEFLATE); codecMap.put(CompressionCodecs.GZIP.getAlgorithmName().toUpperCase(), CompressionCodecs.GZIP); codecs = Collections.unmodifiableMap(codecMap); } @Override
public CompressionCodec resolveCompressionCodec(Header header) {
3
kkrugler/yalder
core/src/main/java/org/krugler/yalder/hash/HashLanguageDetector.java
[ "public abstract class BaseLanguageDetector {\n\n public static final double DEFAULT_ALPHA = 0.000002;\n public static final double DEFAULT_DAMPENING = 0.001;\n\n protected static final double MIN_LANG_PROBABILITY = 0.1;\n protected static final double MIN_GOOD_LANG_PROBABILITY = 0.99;\n \n protected int _maxNGramLength;\n \n // The probability we use for an ngram when we have no data for it for a given language.\n protected double _alpha;\n \n // Used to increase an ngram's probability, to reduce rapid swings in short text\n // snippets. The probability is increased by (1 - prob) * dampening.\n protected double _dampening = DEFAULT_DAMPENING;\n\n protected Collection<? extends BaseLanguageModel> _models;\n \n protected static int getMaxNGramLengthFromModels(Collection<? extends BaseLanguageModel> models) {\n int maxNGramLength = 0;\n Iterator<? extends BaseLanguageModel> iter = models.iterator();\n while (iter.hasNext()) {\n maxNGramLength = Math.max(maxNGramLength, iter.next().getMaxNGramLength());\n }\n \n return maxNGramLength;\n }\n\n public BaseLanguageDetector(Collection<? extends BaseLanguageModel> models, int maxNGramLength) {\n _models = models;\n _maxNGramLength = maxNGramLength;\n _alpha = DEFAULT_ALPHA;\n }\n \n public BaseLanguageDetector setAlpha(double alpha) {\n _alpha = alpha;\n return this;\n }\n \n public double getAlpha() {\n return _alpha;\n }\n \n public BaseLanguageDetector setDampening(double dampening) {\n _dampening = dampening;\n return this;\n }\n \n public double getDampening() {\n return _dampening;\n }\n \n /**\n * Return true if at least one of the loaded models is for a language that\n * is weakly equal to <target>. This means that (in theory) we could get a\n * detection result that would also be weakly equal to <target>.\n * \n * @param target Language of interest\n * @return true if it's supported by the loaded set of models.\n */\n \n public boolean supportsLanguage(LanguageLocale target) {\n for (BaseLanguageModel model : _models) {\n if (model.getLanguage().weaklyEqual(target)) {\n return true;\n }\n }\n \n return false;\n }\n \n public BaseLanguageModel getModel(LanguageLocale language) {\n for (BaseLanguageModel model : _models) {\n \n if (model.getLanguage().equals(language)) {\n return model;\n }\n \n // TODO if weakly equal, and no other set to weak, save it\n }\n \n throw new IllegalArgumentException(\"Unknown language: \" + language);\n }\n\n public abstract void reset();\n \n public abstract void addText(char[] text, int offset, int length);\n \n public void addText(String text) {\n addText(text.toCharArray(), 0, text.length());\n }\n \n public abstract Collection<DetectionResult> detect();\n \n public boolean hasEnoughText() {\n return false;\n }\n \n}", "public abstract class BaseLanguageModel {\n\n // Version of model, for de-serialization\n public static final int MODEL_VERSION = 1;\n \n // The normalized counts are relative to this count, so that we\n // can combine languages built with different amounts of data.\n public static final int NORMALIZED_COUNT = 1000000;\n\n protected LanguageLocale _modelLanguage;\n \n protected int _maxNGramLength;\n \n public BaseLanguageModel() {\n }\n \n public BaseLanguageModel(LanguageLocale modelLanguage, int maxNGramLength) {\n _modelLanguage = modelLanguage;\n _maxNGramLength = maxNGramLength;\n }\n \n public LanguageLocale getLanguage() {\n return _modelLanguage;\n }\n \n public int getMaxNGramLength() {\n return _maxNGramLength;\n }\n \n @Override\n public String toString() {\n return String.format(\"'%s': %d ngrams\", _modelLanguage, size());\n }\n\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + _maxNGramLength;\n result = prime * result + ((_modelLanguage == null) ? 0 : _modelLanguage.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 BaseLanguageModel other = (BaseLanguageModel) obj;\n if (_maxNGramLength != other._maxNGramLength)\n return false;\n if (_modelLanguage == null) {\n if (other._modelLanguage != null)\n return false;\n } else if (!_modelLanguage.equals(other._modelLanguage))\n return false;\n return true;\n }\n\n public abstract int size();\n public abstract int prune(int minNormalizedCount);\n}", "public class DetectionResult implements Comparable<DetectionResult> {\n\n private LanguageLocale _language;\n private double _score;\n private double _confidence;\n private String _details;\n \n public DetectionResult(LanguageLocale language, double score) {\n _language = language;\n _score = score;\n _confidence = 0.0;\n _details = \"\";\n }\n\n public LanguageLocale getLanguage() {\n return _language;\n }\n\n public void setLanguage(LanguageLocale language) {\n _language = language;\n }\n \n public double getScore() {\n return _score;\n }\n\n public void setScore(double score) {\n _score = score;\n }\n\n public double getConfidence() {\n return _confidence;\n }\n\n public void setConfidence(double confidence) {\n _confidence = confidence;\n }\n\n public void setDetails(String details) {\n _details = details;\n }\n \n public String getDetails() {\n return _details;\n }\n \n /* Do reverse sorting.\n * (non-Javadoc)\n * @see java.lang.Comparable#compareTo(java.lang.Object)\n */\n @Override\n public int compareTo(DetectionResult o) {\n if (_score > o._score) {\n return -1;\n } else if (_score < o._score) {\n return 1;\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n return String.format(\"Language '%s' with score %f and confidence %f\", _language, _score, _confidence);\n }\n \n}", "public class LanguageLocale {\n\n private static Map<String, LanguageLocale> LOCALES = new HashMap<String, LanguageLocale>();\n \n // Java Locale support uses ISO 639-2 bibliographic codes, versus the terminological codes\n // (which is what we use). So we have a table to normalize from bib to term, and we need\n // a second table to get the names for terminological codes.\n \n // From http://www.loc.gov/standards/iso639-2/php/English_list.php\n private static Map<String, String> BIB_TO_TERM_MAPPING = new HashMap<String, String>();\n \n static {\n BIB_TO_TERM_MAPPING.put(\"alb\", \"sqi\");\n BIB_TO_TERM_MAPPING.put(\"arm\", \"hye\");\n BIB_TO_TERM_MAPPING.put(\"baq\", \"eus\");\n BIB_TO_TERM_MAPPING.put(\"bur\", \"mya\");\n BIB_TO_TERM_MAPPING.put(\"chi\", \"zho\");\n BIB_TO_TERM_MAPPING.put(\"cze\", \"ces\");\n BIB_TO_TERM_MAPPING.put(\"dut\", \"nld\");\n BIB_TO_TERM_MAPPING.put(\"geo\", \"kat\");\n BIB_TO_TERM_MAPPING.put(\"ger\", \"deu\");\n BIB_TO_TERM_MAPPING.put(\"gre\", \"ell\");\n BIB_TO_TERM_MAPPING.put(\"ice\", \"isl\");\n BIB_TO_TERM_MAPPING.put(\"mac\", \"mkd\");\n BIB_TO_TERM_MAPPING.put(\"may\", \"msa\");\n BIB_TO_TERM_MAPPING.put(\"mao\", \"mri\");\n BIB_TO_TERM_MAPPING.put(\"rum\", \"ron\");\n BIB_TO_TERM_MAPPING.put(\"per\", \"fas\");\n BIB_TO_TERM_MAPPING.put(\"slo\", \"slk\");\n BIB_TO_TERM_MAPPING.put(\"tib\", \"bod\");\n BIB_TO_TERM_MAPPING.put(\"wel\", \"cym\");\n BIB_TO_TERM_MAPPING.put(\"fre\", \"fra\");\n }\n\n // Java Locale support uses \n private static Map<String, String> TERM_CODE_TO_NAME = new HashMap<String, String>();\n static {\n TERM_CODE_TO_NAME.put(\"sqi\", \"Albanian\");\n TERM_CODE_TO_NAME.put(\"hye\", \"Armenian\");\n TERM_CODE_TO_NAME.put(\"eus\", \"Basque\");\n TERM_CODE_TO_NAME.put(\"zho\", \"Chinese\");\n TERM_CODE_TO_NAME.put(\"ces\", \"Czech\");\n TERM_CODE_TO_NAME.put(\"nld\", \"Dutch\");\n TERM_CODE_TO_NAME.put(\"kat\", \"Georgian\");\n TERM_CODE_TO_NAME.put(\"deu\", \"German\");\n TERM_CODE_TO_NAME.put(\"ell\", \"Greek\");\n TERM_CODE_TO_NAME.put(\"isl\", \"Icelandic\");\n TERM_CODE_TO_NAME.put(\"mkd\", \"Macedonian\");\n TERM_CODE_TO_NAME.put(\"msa\", \"Malay\");\n TERM_CODE_TO_NAME.put(\"mri\", \"Maori\");\n TERM_CODE_TO_NAME.put(\"ron\", \"Romanian\");\n TERM_CODE_TO_NAME.put(\"fas\", \"Persian\");\n TERM_CODE_TO_NAME.put(\"slk\", \"Slovak\");\n TERM_CODE_TO_NAME.put(\"bod\", \"Tibetan\");\n TERM_CODE_TO_NAME.put(\"cym\", \"Welsh\");\n TERM_CODE_TO_NAME.put(\"fra\", \"French\");\n }\n \n private static Map<String, String> IMPLICIT_SCRIPT = new HashMap<String, String>();\n static {\n // TODO add full set of these.\n IMPLICIT_SCRIPT.put(\"aze\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"bos\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"uzb\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"tuk\", \"Latn\");\n IMPLICIT_SCRIPT.put(\"msa\", \"Latn\");\n \n IMPLICIT_SCRIPT.put(\"mon\", \"Cyrl\");\n IMPLICIT_SCRIPT.put(\"srp\", \"Cyrl\");\n \n IMPLICIT_SCRIPT.put(\"pan\", \"Guru\");\n }\n \n private static Map<String, String> IMPLICIT_COUNTRY_SCRIPT = new HashMap<String, String>();\n static {\n // TODO add full set of these.\n IMPLICIT_COUNTRY_SCRIPT.put(\"zhoTW\", \"Hant\");\n IMPLICIT_COUNTRY_SCRIPT.put(\"zhoCN\", \"Hans\");\n }\n \n \n \n private static Map<String, String> SPECIFIC_TO_MACRO = new HashMap<String, String>();\n static {\n // TODO add full set of these.\n SPECIFIC_TO_MACRO.put(\"nno\", \"nor\");\n SPECIFIC_TO_MACRO.put(\"nob\", \"nor\");\n }\n\n private String _language; // ISO 639-2/T language code (3 letters)\n private String _script; // ISO 15924 script name (4 letters) or empty\n \n public static LanguageLocale fromString(String languageName) {\n if (!LOCALES.containsKey(languageName)) {\n\n synchronized (LOCALES) {\n // Make sure nobody added it after we did our check.\n if (!LOCALES.containsKey(languageName)) {\n LOCALES.put(languageName, new LanguageLocale(languageName));\n }\n }\n }\n \n return LOCALES.get(languageName);\n }\n \n /**\n * Return a language name (suitable for passing into the fromString method) from\n * a language (2 or 3 character) and script (always four character, e.g. \"Latn\").\n * \n * @param language\n * @param script\n * @return standard format for language name\n */\n public static String makeLanguageName(String language, String script) {\n return String.format(\"%s-%s\", language, script);\n }\n \n private LanguageLocale(String languageTag) {\n Locale locale = Locale.forLanguageTag(languageTag);\n \n // First convert the language code to ISO 639-2/T\n _language = locale.getISO3Language();\n if (_language.isEmpty()) {\n throw new IllegalArgumentException(\"A valid language code must be provided\");\n }\n \n // See if we need to convert from 639-2/B to 639-2/T\n if (BIB_TO_TERM_MAPPING.containsKey(_language)) {\n _language = BIB_TO_TERM_MAPPING.get(_language);\n }\n \n // Now see if we have a script.\n _script = locale.getScript();\n // TODO - do we want to verify it's a valid script? What happens if you pass\n // in something like en-latin?\n \n // If the script is empty, and we have a country, then we might want to\n // explicitly set the script as that's how it was done previously (e.g. zh-TW\n // to set the Hant script, versus zh-CN for Hans script)\n if (_script.isEmpty()) {\n String country = locale.getCountry();\n // TODO convert UN M.39 code into two letter country \n if (!country.isEmpty()) {\n // TODO look up language + country\n String languagePlusCountry = _language + country;\n if (IMPLICIT_COUNTRY_SCRIPT.containsKey(languagePlusCountry)) {\n _script = IMPLICIT_COUNTRY_SCRIPT.get(languagePlusCountry);\n }\n }\n }\n \n // If the script isn't empty, and it's the default script for the language,\n // then remove it so we don't include it in comparisons.\n if (!_script.isEmpty() && _script.equals(IMPLICIT_SCRIPT.get(_language))) {\n _script = \"\";\n }\n }\n\n // We add a special \"weakly equal\" method that's used to\n // decide if the target locale matches us. The \"target\" in\n // this case is what we're looking for (what we want it to be)\n // versus what we got from detection\n // versus what we expect it to be. In this case,\n // target result match?\n // zho zho yes\n // zho-Hant zho-Hant yes\n // zho zho-Hant yes\n // zho-Hant zho no (want explicitly trad chinese, got unspecified)\n // zho-Hant zho-Hans no\n \n // FUTURE support country code for dialects?\n // target result match?\n // en en-GB yes\n // en-GB en-US no\n // en-GB en no\n \n public boolean weaklyEqual(LanguageLocale target) {\n if (!_language.equals(target._language)) {\n // But wait - maybe target is a macro language, and we've got\n // a more specific result...if so then they're still (maybe)\n // equal.\n if (!SPECIFIC_TO_MACRO.containsKey(_language) || !SPECIFIC_TO_MACRO.get(_language).equals(target._language)) {\n return false;\n }\n }\n \n if (target._script.isEmpty()) {\n // Target says we don't care about script, so always matches.\n return true;\n } else {\n return _script.equals(target._script);\n }\n }\n \n public String getName() {\n if (!_script.isEmpty()) {\n return String.format(\"%s-%s\", _language, _script);\n } else {\n return _language;\n }\n }\n \n public String getISO3LetterName() {\n return _language;\n }\n\n public final String toString() {\n String languageTag;\n if (!_script.isEmpty()) {\n languageTag = String.format(\"%s-%s\", _language, _script);\n } else {\n languageTag = _language;\n }\n \n String displayLanguage = Locale.forLanguageTag(languageTag).getDisplayLanguage();\n if (TERM_CODE_TO_NAME.containsKey(_language)) {\n // It's a terminological code, so we have to provide the name ourselves.\n displayLanguage = TERM_CODE_TO_NAME.get(_language);\n }\n \n return String.format(\"%s (%s)\", languageTag, displayLanguage);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((_language == null) ? 0 : _language.hashCode());\n result = prime * result + ((_script == null) ? 0 : _script.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 LanguageLocale other = (LanguageLocale) obj;\n if (_language == null) {\n if (other._language != null)\n return false;\n } else if (!_language.equals(other._language))\n return false;\n if (_script == null) {\n if (other._script != null)\n return false;\n } else if (!_script.equals(other._script))\n return false;\n return true;\n }\n\n\n \n}", "public interface Int2IntMap extends Int2IntFunction , Map<Integer,Integer> {\n /** An entry set providing fast iteration. \n\t *\n\t * <p>In some cases (e.g., hash-based classes) iteration over an entry set requires the creation\n\t * of a large number of {@link java.util.Map.Entry} objects. Some <code>fastutil</code>\n\t * maps might return {@linkplain #entrySet() entry set} objects of type <code>FastEntrySet</code>: in this case, {@link #fastIterator() fastIterator()}\n\t * will return an iterator that is guaranteed not to create a large number of objects, <em>possibly\n\t * by returning always the same entry</em> (of course, mutated).\n\t */\n public interface FastEntrySet extends ObjectSet<Int2IntMap.Entry > {\n /** Returns a fast iterator over this entry set; the iterator might return always the same entry object, suitably mutated.\n\t\t *\n\t\t * @return a fast iterator over this entry set; the iterator might return always the same {@link java.util.Map.Entry} object, suitably mutated.\n\t\t */\n public ObjectIterator<Int2IntMap.Entry > fastIterator();\n }\n /** Returns a set view of the mappings contained in this map.\n\t * <P>Note that this specification strengthens the one given in {@link Map#entrySet()}.\n\t *\n\t * @return a set view of the mappings contained in this map.\n\t * @see Map#entrySet()\n\t */\n ObjectSet<Map.Entry<Integer, Integer>> entrySet();\n /** Returns a type-specific set view of the mappings contained in this map.\n\t *\n\t * <p>This method is necessary because there is no inheritance along\n\t * type parameters: it is thus impossible to strengthen {@link #entrySet()}\n\t * so that it returns an {@link it.unimi.dsi.fastutil.objects.ObjectSet}\n\t * of objects of type {@link java.util.Map.Entry} (the latter makes it possible to\n\t * access keys and values with type-specific methods).\n\t *\n\t * @return a type-specific set view of the mappings contained in this map.\n\t * @see #entrySet()\n\t */\n ObjectSet<Int2IntMap.Entry > int2IntEntrySet();\n /** Returns a set view of the keys contained in this map.\n\t * <P>Note that this specification strengthens the one given in {@link Map#keySet()}.\n\t *\n\t * @return a set view of the keys contained in this map.\n\t * @see Map#keySet()\n\t */\n IntSet keySet();\n /** Returns a set view of the values contained in this map.\n\t * <P>Note that this specification strengthens the one given in {@link Map#values()}.\n\t *\n\t * @return a set view of the values contained in this map.\n\t * @see Map#values()\n\t */\n IntCollection values();\n /**\n\t * @see Map#containsValue(Object)\n\t */\n boolean containsValue( int value );\n /** A type-specific {@link java.util.Map.Entry}; provides some additional methods\n\t * that use polymorphism to avoid (un)boxing.\n\t *\n\t * @see java.util.Map.Entry\n\t */\n interface Entry extends Map.Entry <Integer,Integer> {\n /**\n\t\t * @see java.util.Map.Entry#getKey()\n\t\t */\n int getIntKey();\n /**\n\t\t * @see java.util.Map.Entry#setValue(Object)\n\t\t */\n int setValue(int value);\n /**\n\t\t * @see java.util.Map.Entry#getValue()\n\t\t */\n int getIntValue();\n }\n}", "public class Int2IntOpenHashMap extends AbstractInt2IntMap implements java.io.Serializable, Cloneable, Hash {\n private static final long serialVersionUID = 0L;\n private static final boolean ASSERTS = false;\n /** The array of keys. */\n protected transient int key[];\n /** The array of values. */\n protected transient int value[];\n /** The array telling whether a position is used. */\n protected transient boolean used[];\n /** The acceptable load factor. */\n protected final float f;\n /** The current table size. */\n protected transient int n;\n /** Threshold after which we rehash. It must be the table size times {@link #f}. */\n protected transient int maxFill;\n /** The mask for wrapping a position counter. */\n protected transient int mask;\n /** Number of entries in the set. */\n protected int size;\n /** Cached set of entries. */\n protected transient volatile FastEntrySet entries;\n /** Cached set of keys. */\n protected transient volatile IntSet keys;\n /** Cached collection of values. */\n protected transient volatile IntCollection values;\n /** Creates a new hash map.\n\t *\n\t * <p>The actual table size will be the least power of two greater than <code>expected</code>/<code>f</code>.\n\t *\n\t * @param expected the expected number of elements in the hash set. \n\t * @param f the load factor.\n\t */\n @SuppressWarnings(\"unchecked\")\n public Int2IntOpenHashMap( final int expected, final float f ) {\n if ( f <= 0 || f > 1 ) throw new IllegalArgumentException( \"Load factor must be greater than 0 and smaller than or equal to 1\" );\n if ( expected < 0 ) throw new IllegalArgumentException( \"The expected number of elements must be nonnegative\" );\n this.f = f;\n n = arraySize( expected, f );\n mask = n - 1;\n maxFill = maxFill( n, f );\n key = new int[ n ];\n value = new int[ n ];\n used = new boolean[ n ];\n }\n /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor.\n\t *\n\t * @param expected the expected number of elements in the hash map.\n\t */\n public Int2IntOpenHashMap( final int expected ) {\n this( expected, DEFAULT_LOAD_FACTOR );\n }\n /** Creates a new hash map with initial expected {@link Hash#DEFAULT_INITIAL_SIZE} entries\n\t * and {@link Hash#DEFAULT_LOAD_FACTOR} as load factor.\n\t */\n public Int2IntOpenHashMap() {\n this( DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR );\n }\n /** Creates a new hash map copying a given one.\n\t *\n\t * @param m a {@link Map} to be copied into the new hash map. \n\t * @param f the load factor.\n\t */\n public Int2IntOpenHashMap( final Map<? extends Integer, ? extends Integer> m, final float f ) {\n this( m.size(), f );\n putAll( m );\n }\n /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given one.\n\t *\n\t * @param m a {@link Map} to be copied into the new hash map. \n\t */\n public Int2IntOpenHashMap( final Map<? extends Integer, ? extends Integer> m ) {\n this( m, DEFAULT_LOAD_FACTOR );\n }\n /** Creates a new hash map copying a given type-specific one.\n\t *\n\t * @param m a type-specific map to be copied into the new hash map. \n\t * @param f the load factor.\n\t */\n public Int2IntOpenHashMap( final Int2IntMap m, final float f ) {\n this( m.size(), f );\n putAll( m );\n }\n /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given type-specific one.\n\t *\n\t * @param m a type-specific map to be copied into the new hash map. \n\t */\n public Int2IntOpenHashMap( final Int2IntMap m ) {\n this( m, DEFAULT_LOAD_FACTOR );\n }\n /** Creates a new hash map using the elements of two parallel arrays.\n\t *\n\t * @param k the array of keys of the new hash map.\n\t * @param v the array of corresponding values in the new hash map.\n\t * @param f the load factor.\n\t * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths.\n\t */\n public Int2IntOpenHashMap( final int[] k, final int v[], final float f ) {\n this( k.length, f );\n if ( k.length != v.length ) throw new IllegalArgumentException( \"The key array and the value array have different lengths (\" + k.length + \" and \" + v.length + \")\" );\n for( int i = 0; i < k.length; i++ ) this.put( k[ i ], v[ i ] );\n }\n /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor using the elements of two parallel arrays.\n\t *\n\t * @param k the array of keys of the new hash map.\n\t * @param v the array of corresponding values in the new hash map.\n\t * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths.\n\t */\n public Int2IntOpenHashMap( final int[] k, final int v[] ) {\n this( k, v, DEFAULT_LOAD_FACTOR );\n }\n /*\n\t * The following methods implements some basic building blocks used by\n\t * all accessors. They are (and should be maintained) identical to those used in OpenHashSet.drv.\n\t */\n public int put(final int k, final int v) {\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) {\n final int oldValue = value[ pos ];\n value[ pos ] = v;\n return oldValue;\n }\n pos = ( pos + 1 ) & mask;\n }\n used[ pos ] = true;\n key[ pos ] = k;\n value[ pos ] = v;\n if ( size++ >= maxFill ) rehash( arraySize( size + 1, f ) );\n if ( ASSERTS ) checkTable();\n return defRetValue;\n }\n public Integer put( final Integer ok, final Integer ov ) {\n final int v = ((ov).intValue());\n final int k = ((ok).intValue());\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) {\n final Integer oldValue = (Integer.valueOf(value[ pos ]));\n value[ pos ] = v;\n return oldValue;\n }\n pos = ( pos + 1 ) & mask;\n }\n used[ pos ] = true;\n key[ pos ] = k;\n value[ pos ] = v;\n if ( size++ >= maxFill ) rehash( arraySize( size + 1, f ) );\n if ( ASSERTS ) checkTable();\n return (null);\n }\n /** Adds an increment to value currently associated with a key.\n\t *\n\t * @param k the key.\n\t * @param incr the increment.\n\t * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key.\n\t * @deprecated use <code>addTo()</code> instead; having the same name of a {@link java.util.Set} method turned out to be a recipe for disaster.\n\t */\n @Deprecated\n public int add(final int k, final int incr) {\n return addTo( k, incr );\n }\n /** Adds an increment to value currently associated with a key.\n\t *\n\t * <P>Note that this method respects the {@linkplain #defaultReturnValue() default return value} semantics: when\n\t * called with a key that does not currently appears in the map, the key\n\t * will be associated with the default return value plus\n\t * the given increment.\n\t *\n\t * @param k the key.\n\t * @param incr the increment.\n\t * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key.\n\t */\n public int addTo(final int k, final int incr) {\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) {\n final int oldValue = value[ pos ];\n value[ pos ] += incr;\n return oldValue;\n }\n pos = ( pos + 1 ) & mask;\n }\n used[ pos ] = true;\n key[ pos ] = k;\n value[ pos ] = defRetValue + incr;\n if ( size++ >= maxFill ) rehash( arraySize( size + 1, f ) );\n if ( ASSERTS ) checkTable();\n return defRetValue;\n }\n /** Shifts left entries with the specified hash code, starting at the specified position,\n\t * and empties the resulting free entry.\n\t *\n\t * @param pos a starting position.\n\t * @return the position cleared by the shifting process.\n\t */\n protected final int shiftKeys( int pos ) {\n // Shift entries with the same hash.\n int last, slot;\n for(;;) {\n pos = ( ( last = pos ) + 1 ) & mask;\n while( used[ pos ] ) {\n slot = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (key[ pos ]) ^ mask ) ) & mask;\n if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break;\n pos = ( pos + 1 ) & mask;\n }\n if ( ! used[ pos ] ) break;\n key[ last ] = key[ pos ];\n value[ last ] = value[ pos ];\n }\n used[ last ] = false;\n return last;\n }\n @SuppressWarnings(\"unchecked\")\n public int remove( final int k ) {\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) {\n size--;\n final int v = value[ pos ];\n shiftKeys( pos );\n return v;\n }\n pos = ( pos + 1 ) & mask;\n }\n return defRetValue;\n }\n @SuppressWarnings(\"unchecked\")\n public Integer remove( final Object ok ) {\n final int k = ((((Integer)(ok)).intValue()));\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) {\n size--;\n final int v = value[ pos ];\n shiftKeys( pos );\n return (Integer.valueOf(v));\n }\n pos = ( pos + 1 ) & mask;\n }\n return (null);\n }\n public Integer get( final Integer ok ) {\n final int k = ((ok).intValue());\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( ( k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == ( k) ) ) return (Integer.valueOf(value[ pos ]));\n pos = ( pos + 1 ) & mask;\n }\n return (null);\n }\n @SuppressWarnings(\"unchecked\")\n public int get( final int k ) {\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) return value[ pos ];\n pos = ( pos + 1 ) & mask;\n }\n return defRetValue;\n }\n @SuppressWarnings(\"unchecked\")\n public boolean containsKey( final int k ) {\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) return true;\n pos = ( pos + 1 ) & mask;\n }\n return false;\n }\n public boolean containsValue( final int v ) {\n final int value[] = this.value;\n final boolean used[] = this.used;\n for( int i = n; i-- != 0; ) if ( used[ i ] && ( (value[ i ]) == (v) ) ) return true;\n return false;\n }\n /* Removes all elements from this map.\n\t *\n\t * <P>To increase object reuse, this method does not change the table size.\n\t * If you want to reduce the table size, you must use {@link #trim()}.\n\t *\n\t */\n public void clear() {\n if ( size == 0 ) return;\n size = 0;\n BooleanArrays.fill( used, false );\n // We null all object entries so that the garbage collector can do its work.\n }\n public int size() {\n return size;\n }\n public boolean isEmpty() {\n return size == 0;\n }\n /** A no-op for backward compatibility.\n\t * \n\t * @param growthFactor unused.\n\t * @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full.\n\t */\n @Deprecated\n public void growthFactor( int growthFactor ) {}\n /** Gets the growth factor (2).\n\t *\n\t * @return the growth factor of this set, which is fixed (2).\n\t * @see #growthFactor(int)\n\t * @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full.\n\t */\n @Deprecated\n public int growthFactor() {\n return 16;\n }\n /** The entry class for a hash map does not record key and value, but\n\t * rather the position in the hash table of the corresponding entry. This\n\t * is necessary so that calls to {@link java.util.Map.Entry#setValue(Object)} are reflected in\n\t * the map */\n private final class MapEntry implements Int2IntMap.Entry , Map.Entry<Integer, Integer> {\n // The table index this entry refers to, or -1 if this entry has been deleted.\n private int index;\n MapEntry( final int index ) {\n this.index = index;\n }\n public Integer getKey() {\n return (Integer.valueOf(key[ index ]));\n }\n public int getIntKey() {\n return key[ index ];\n }\n public Integer getValue() {\n return (Integer.valueOf(value[ index ]));\n }\n public int getIntValue() {\n return value[ index ];\n }\n public int setValue( final int v ) {\n final int oldValue = value[ index ];\n value[ index ] = v;\n return oldValue;\n }\n public Integer setValue( final Integer v ) {\n return (Integer.valueOf(setValue( ((v).intValue()) )));\n }\n @SuppressWarnings(\"unchecked\")\n public boolean equals( final Object o ) {\n if (!(o instanceof Map.Entry)) return false;\n Map.Entry<Integer, Integer> e = (Map.Entry<Integer, Integer>)o;\n return ( (key[ index ]) == (((e.getKey()).intValue())) ) && ( (value[ index ]) == (((e.getValue()).intValue())) );\n }\n public int hashCode() {\n return (key[ index ]) ^ (value[ index ]);\n }\n public String toString() {\n return key[ index ] + \"=>\" + value[ index ];\n }\n }\n /** An iterator over a hash map. */\n private class MapIterator {\n /** The index of the next entry to be returned, if positive or zero. If negative, the next entry to be\n\t\t\treturned, if any, is that of index -pos -2 from the {@link #wrapped} list. */\n int pos = Int2IntOpenHashMap.this.n;\n /** The index of the last entry that has been returned. It is -1 if either\n\t\t\twe did not return an entry yet, or the last returned entry has been removed. */\n int last = -1;\n /** A downward counter measuring how many entries must still be returned. */\n int c = size;\n /** A lazily allocated list containing the keys of elements that have wrapped around the table because of removals; such elements\n\t\t\twould not be enumerated (other elements would be usually enumerated twice in their place). */\n IntArrayList wrapped;\n {\n final boolean used[] = Int2IntOpenHashMap.this.used;\n if ( c != 0 ) while( ! used[ --pos ] );\n }\n public boolean hasNext() {\n return c != 0;\n }\n public int nextEntry() {\n if ( ! hasNext() ) throw new NoSuchElementException();\n c--;\n // We are just enumerating elements from the wrapped list.\n if ( pos < 0 ) {\n final int k = wrapped.getInt( - ( last = --pos ) - 2 );\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) return pos;\n pos = ( pos + 1 ) & mask;\n }\n }\n last = pos;\n //System.err.println( \"Count: \" + c );\n if ( c != 0 ) {\n final boolean used[] = Int2IntOpenHashMap.this.used;\n while ( pos-- != 0 && !used[ pos ] );\n // When here pos < 0 there are no more elements to be enumerated by scanning, but wrapped might be nonempty.\n }\n return last;\n }\n /** Shifts left entries with the specified hash code, starting at the specified position,\n\t\t * and empties the resulting free entry. If any entry wraps around the table, instantiates\n\t\t * lazily {@link #wrapped} and stores the entry key.\n\t\t *\n\t\t * @param pos a starting position.\n\t\t * @return the position cleared by the shifting process.\n\t\t */\n protected final int shiftKeys( int pos ) {\n // Shift entries with the same hash.\n int last, slot;\n for(;;) {\n pos = ( ( last = pos ) + 1 ) & mask;\n while( used[ pos ] ) {\n slot = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (key[ pos ]) ^ mask ) ) & mask;\n if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break;\n pos = ( pos + 1 ) & mask;\n }\n if ( ! used[ pos ] ) break;\n if ( pos < last ) {\n // Wrapped entry.\n if ( wrapped == null ) wrapped = new IntArrayList ();\n wrapped.add( key[ pos ] );\n }\n key[ last ] = key[ pos ];\n value[ last ] = value[ pos ];\n }\n used[ last ] = false;\n return last;\n }\n @SuppressWarnings(\"unchecked\")\n public void remove() {\n if ( last == -1 ) throw new IllegalStateException();\n if ( pos < -1 ) {\n // We're removing wrapped entries.\n Int2IntOpenHashMap.this.remove( wrapped.getInt( - pos - 2 ) );\n last = -1;\n return;\n }\n size--;\n if ( shiftKeys( last ) == pos && c > 0 ) {\n c++;\n nextEntry();\n }\n last = -1; // You can no longer remove this entry.\n if ( ASSERTS ) checkTable();\n }\n public int skip( final int n ) {\n int i = n;\n while( i-- != 0 && hasNext() ) nextEntry();\n return n - i - 1;\n }\n }\n private class EntryIterator extends MapIterator implements ObjectIterator<Int2IntMap.Entry > {\n private MapEntry entry;\n public Int2IntMap.Entry next() {\n return entry = new MapEntry( nextEntry() );\n }\n @Override\n public void remove() {\n super.remove();\n entry.index = -1; // You cannot use a deleted entry.\n }\n }\n private class FastEntryIterator extends MapIterator implements ObjectIterator<Int2IntMap.Entry > {\n final BasicEntry entry = new BasicEntry ( ((int)0), (0) );\n public BasicEntry next() {\n final int e = nextEntry();\n entry.key = key[ e ];\n entry.value = value[ e ];\n return entry;\n }\n }\n private final class MapEntrySet extends AbstractObjectSet<Int2IntMap.Entry > implements FastEntrySet {\n public ObjectIterator<Int2IntMap.Entry > iterator() {\n return new EntryIterator();\n }\n public ObjectIterator<Int2IntMap.Entry > fastIterator() {\n return new FastEntryIterator();\n }\n @SuppressWarnings(\"unchecked\")\n public boolean contains( final Object o ) {\n if ( !( o instanceof Map.Entry ) ) return false;\n final Map.Entry<Integer, Integer> e = (Map.Entry<Integer, Integer>)o;\n final int k = ((e.getKey()).intValue());\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) return ( (value[ pos ]) == (((e.getValue()).intValue())) );\n pos = ( pos + 1 ) & mask;\n }\n return false;\n }\n @SuppressWarnings(\"unchecked\")\n public boolean remove( final Object o ) {\n if ( !( o instanceof Map.Entry ) ) return false;\n final Map.Entry<Integer, Integer> e = (Map.Entry<Integer, Integer>)o;\n final int k = ((e.getKey()).intValue());\n // The starting point.\n int pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n // There's always an unused entry.\n while( used[ pos ] ) {\n if ( ( (key[ pos ]) == (k) ) ) {\n Int2IntOpenHashMap.this.remove( e.getKey() );\n return true;\n }\n pos = ( pos + 1 ) & mask;\n }\n return false;\n }\n public int size() {\n return size;\n }\n public void clear() {\n Int2IntOpenHashMap.this.clear();\n }\n }\n public FastEntrySet int2IntEntrySet() {\n if ( entries == null ) entries = new MapEntrySet();\n return entries;\n }\n /** An iterator on keys.\n\t *\n\t * <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods\n\t * (and possibly their type-specific counterparts) so that they return keys\n\t * instead of entries.\n\t */\n private final class KeyIterator extends MapIterator implements IntIterator {\n public KeyIterator() { super(); }\n public int nextInt() { return key[ nextEntry() ]; }\n public Integer next() { return (Integer.valueOf(key[ nextEntry() ])); }\n }\n private final class KeySet extends AbstractIntSet {\n public IntIterator iterator() {\n return new KeyIterator();\n }\n public int size() {\n return size;\n }\n public boolean contains( int k ) {\n return containsKey( k );\n }\n public boolean remove( int k ) {\n final int oldSize = size;\n Int2IntOpenHashMap.this.remove( k );\n return size != oldSize;\n }\n public void clear() {\n Int2IntOpenHashMap.this.clear();\n }\n }\n public IntSet keySet() {\n if ( keys == null ) keys = new KeySet();\n return keys;\n }\n /** An iterator on values.\n\t *\n\t * <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods\n\t * (and possibly their type-specific counterparts) so that they return values\n\t * instead of entries.\n\t */\n private final class ValueIterator extends MapIterator implements IntIterator {\n public ValueIterator() { super(); }\n public int nextInt() { return value[ nextEntry() ]; }\n public Integer next() { return (Integer.valueOf(value[ nextEntry() ])); }\n }\n public IntCollection values() {\n if ( values == null ) values = new AbstractIntCollection () {\n public IntIterator iterator() {\n return new ValueIterator();\n }\n public int size() {\n return size;\n }\n public boolean contains( int v ) {\n return containsValue( v );\n }\n public void clear() {\n Int2IntOpenHashMap.this.clear();\n }\n };\n return values;\n }\n /** A no-op for backward compatibility. The kind of tables implemented by\n\t * this class never need rehashing.\n\t *\n\t * <P>If you need to reduce the table size to fit exactly\n\t * this set, use {@link #trim()}.\n\t *\n\t * @return true.\n\t * @see #trim()\n\t * @deprecated A no-op.\n\t */\n @Deprecated\n public boolean rehash() {\n return true;\n }\n /** Rehashes the map, making the table as small as possible.\n\t * \n\t * <P>This method rehashes the table to the smallest size satisfying the\n\t * load factor. It can be used when the set will not be changed anymore, so\n\t * to optimize access speed and size.\n\t *\n\t * <P>If the table size is already the minimum possible, this method\n\t * does nothing. \n\t *\n\t * @return true if there was enough memory to trim the map.\n\t * @see #trim(int)\n\t */\n public boolean trim() {\n final int l = arraySize( size, f );\n if ( l >= n ) return true;\n try {\n rehash( l );\n }\n catch(OutOfMemoryError cantDoIt) { return false; }\n return true;\n }\n /** Rehashes this map if the table is too large.\n\t * \n\t * <P>Let <var>N</var> be the smallest table size that can hold\n\t * <code>max(n,{@link #size()})</code> entries, still satisfying the load factor. If the current\n\t * table size is smaller than or equal to <var>N</var>, this method does\n\t * nothing. Otherwise, it rehashes this map in a table of size\n\t * <var>N</var>.\n\t *\n\t * <P>This method is useful when reusing maps. {@linkplain #clear() Clearing a\n\t * map} leaves the table size untouched. If you are reusing a map\n\t * many times, you can call this method with a typical\n\t * size to avoid keeping around a very large table just\n\t * because of a few large transient maps.\n\t *\n\t * @param n the threshold for the trimming.\n\t * @return true if there was enough memory to trim the map.\n\t * @see #trim()\n\t */\n public boolean trim( final int n ) {\n final int l = HashCommon.nextPowerOfTwo( (int)Math.ceil( n / f ) );\n if ( this.n <= l ) return true;\n try {\n rehash( l );\n }\n catch( OutOfMemoryError cantDoIt ) { return false; }\n return true;\n }\n /** Rehashes the map.\n\t *\n\t * <P>This method implements the basic rehashing strategy, and may be\n\t * overriden by subclasses implementing different rehashing strategies (e.g.,\n\t * disk-based rehashing). However, you should not override this method\n\t * unless you understand the internal workings of this class.\n\t *\n\t * @param newN the new size\n\t */\n @SuppressWarnings(\"unchecked\")\n protected void rehash( final int newN ) {\n int i = 0, pos;\n final boolean used[] = this.used;\n int k;\n final int key[] = this.key;\n final int value[] = this.value;\n final int mask = newN - 1; // Note that this is used by the hashing macro\n final int newKey[] = new int[ newN ];\n final int newValue[] = new int[newN];\n final boolean newUsed[] = new boolean[ newN ];\n for( int j = size; j-- != 0; ) {\n while( ! used[ i ] ) i++;\n k = key[ i ];\n pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n while ( newUsed[ pos ] ) pos = ( pos + 1 ) & mask;\n newUsed[ pos ] = true;\n newKey[ pos ] = k;\n newValue[ pos ] = value[ i ];\n i++;\n }\n n = newN;\n this.mask = mask;\n maxFill = maxFill( n, f );\n this.key = newKey;\n this.value = newValue;\n this.used = newUsed;\n }\n /** Returns a deep copy of this map. \n\t *\n\t * <P>This method performs a deep copy of this hash map; the data stored in the\n\t * map, however, is not cloned. Note that this makes a difference only for object keys.\n\t *\n\t * @return a deep copy of this map.\n\t */\n @SuppressWarnings(\"unchecked\")\n public Int2IntOpenHashMap clone() {\n Int2IntOpenHashMap c;\n try {\n c = (Int2IntOpenHashMap )super.clone();\n }\n catch(CloneNotSupportedException cantHappen) {\n throw new InternalError();\n }\n c.keys = null;\n c.values = null;\n c.entries = null;\n c.key = key.clone();\n c.value = value.clone();\n c.used = used.clone();\n return c;\n }\n /** Returns a hash code for this map.\n\t *\n\t * This method overrides the generic method provided by the superclass. \n\t * Since <code>equals()</code> is not overriden, it is important\n\t * that the value returned by this method is the same value as\n\t * the one returned by the overriden method.\n\t *\n\t * @return a hash code for this map.\n\t */\n public int hashCode() {\n int h = 0;\n for( int j = size, i = 0, t = 0; j-- != 0; ) {\n while( ! used[ i ] ) i++;\n t = (key[ i ]);\n t ^= (value[ i ]);\n h += t;\n i++;\n }\n return h;\n }\n private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {\n final int key[] = this.key;\n final int value[] = this.value;\n final MapIterator i = new MapIterator();\n s.defaultWriteObject();\n for( int j = size, e; j-- != 0; ) {\n e = i.nextEntry();\n s.writeInt( key[ e ] );\n s.writeInt( value[ e ] );\n }\n }\n @SuppressWarnings(\"unchecked\")\n private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {\n s.defaultReadObject();\n n = arraySize( size, f );\n maxFill = maxFill( n, f );\n mask = n - 1;\n final int key[] = this.key = new int[ n ];\n final int value[] = this.value = new int[ n ];\n final boolean used[] = this.used = new boolean[ n ];\n int k;\n int v;\n for( int i = size, pos = 0; i-- != 0; ) {\n k = s.readInt();\n v = s.readInt();\n pos = ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (k) ^ mask ) ) & mask;\n while ( used[ pos ] ) pos = ( pos + 1 ) & mask;\n used[ pos ] = true;\n key[ pos ] = k;\n value[ pos ] = v;\n }\n if ( ASSERTS ) checkTable();\n }\n private void checkTable() {}\n}" ]
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.krugler.yalder.BaseLanguageDetector; import org.krugler.yalder.BaseLanguageModel; import org.krugler.yalder.DetectionResult; import org.krugler.yalder.LanguageLocale; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
package org.krugler.yalder.hash; /** * Language detector that works with ngram hashes (versus text), for * efficiency. * */ public class HashLanguageDetector extends BaseLanguageDetector { private static final int RENORMALIZE_INTERVAL = 10; private static final int EARLY_TERMINATION_INTERVAL = RENORMALIZE_INTERVAL * 11; // Map from language of model to index used for accessing arrays.
private Map<LanguageLocale, Integer> _langToIndex;
3
SPIRIT-21/javadoc2swagger
src/main/java/com/spirit21/swagger/converter/parsers/ResourceParser.java
[ "public class Regex {\n\n public final static String PACKAGE = \"package [^;]*;\";\n public final static String JAVADOC = \"\\\\/\\\\*\\\\*((?!\\\\*\\\\/).)*\\\\*\\\\/\";\n public final static String ANNOTATION = \"@[a-zA-Z]+(\\\\([^@)]*\\\\))?\";\n public final static String METHOD = \"(public|protected|private|static|\\\\s) +[\\\\w\\\\<\\\\>\\\\[\\\\]]+\\\\s+(\\\\w+) *\\\\([^{]*\\\\{\";\n public final static String IMPORT = \"import [^;]*;\";\n public final static String API_JAVADOC = \"\\\\/\\\\*\\\\*(?=.*@apiTitle).+\\\\*\\\\/\";\n public final static String CLASS = \"public class \\\\w+\";\n public final static String PATH = \"@path [^\\\\n ]*\";\n public final static String DESCRIPTION = \"([^@{]|\\\\{@|\\\\{)*\";\n public final static String HTTP_METHOD = \"(@GET|@POST|@PUT|@DELETE|@PUT)\";\n public final static String IGNORE_JAVAFILE = \"@swagger:ignore_javafile\";\n\n}", "public class ClassLoader {\n private URLClassLoader loader;\n\n /**\n * Initializes the ClassLoader\n * \n * @param project\n * Maven Project\n * @throws ClassLoaderException\n * Failed to initialize the ClassLoader\n */\n public ClassLoader(MavenProject project) throws ClassLoaderException {\n try {\n List<?> runtimeClasspathElements = project.getRuntimeClasspathElements();\n URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];\n for (int i = 0; i < runtimeClasspathElements.size(); i++) {\n String element = (String) runtimeClasspathElements.get(i);\n runtimeUrls[i] = new File(element).toURI().toURL();\n }\n loader = new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader());\n } catch (MalformedURLException | DependencyResolutionRequiredException e) {\n throw new ClassLoaderException(\"Error initializing the ClassLoader!\", e);\n }\n }\n\n /**\n * Loads a class with the {@link URLClassLoader}\n * \n * @param name\n * Name of the class\n * @return loaded class\n * @throws ClassNotFoundException\n * Class was not found\n */\n public Class<?> loadClass(String name) throws ClassNotFoundException {\n return loader.loadClass(name);\n }\n}", "public class Definition {\n private String type;\n private String className;\n private List<Property> properties;\n private List<String> required;\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 getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public List<Property> getProperties() {\n return properties;\n }\n\n public void setProperties(List<Property> properties) {\n this.properties = properties;\n }\n\n public List<String> getRequired() {\n return required;\n }\n\n public void setRequired(List<String> required) {\n this.required = required;\n }\n}", "public class JavaFile {\n private String fileName;\n private String packageName;\n private List<String> imports;\n private List<Method> functions;\n private String apiJavadoc;\n private List<String> classAnnotations;\n private String classJavadoc;\n\n public List<String> getImports() {\n return imports;\n }\n\n public void setImports(List<String> imports) {\n this.imports = imports;\n }\n\n public List<Method> getFunctions() {\n return functions;\n }\n\n public void setFunctions(List<Method> functions) {\n this.functions = functions;\n }\n\n public String getApiJavadoc() {\n return apiJavadoc;\n }\n\n public void setApiJavadoc(String apiJavadoc) {\n this.apiJavadoc = apiJavadoc;\n }\n\n public List<String> getClassAnnotations() {\n return classAnnotations;\n }\n\n public void setClassAnnotations(List<String> classAnnotations) {\n this.classAnnotations = classAnnotations;\n }\n\n public String getClassJavadoc() {\n return classJavadoc;\n }\n\n public void setClassJavadoc(String classJavadoc) {\n this.classJavadoc = classJavadoc;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public void setFileName(String fileName) {\n this.fileName = fileName;\n }\n\n public String getPackageName() {\n return packageName;\n }\n\n public void setPackageName(String packageName) {\n this.packageName = packageName;\n }\n}", "public class Parameter {\n\n private String name;\n private String type;\n private String format;\n private String location;\n private String description;\n private Boolean required;\n private Definition definition;\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 getLocation() {\n return location;\n }\n\n public void setLocation(String location) {\n this.location = location;\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 Boolean getRequired() {\n return required;\n }\n\n public void setRequired(Boolean required) {\n this.required = required;\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 getFormat() {\n return format;\n }\n\n public void setFormat(String format) {\n this.format = format;\n }\n\n public Definition getDefinition() {\n return definition;\n }\n\n public void setDefinition(Definition definition) {\n this.definition = definition;\n }\n}", "public class Resource implements SwaggerModel {\n\n private String path;\n private List<Parameter> pathParameters;\n private List<Operation> operations;\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public List<Operation> getOperations() {\n return operations;\n }\n\n public void setOperations(List<Operation> operations) {\n this.operations = operations;\n }\n\n public List<Parameter> getPathParameters() {\n return pathParameters;\n }\n\n public void setPathParameters(List<Parameter> pathParameters) {\n this.pathParameters = pathParameters;\n }\n}", "public interface SwaggerModel {\n\n}", "public class Tag {\n private String name;\n private String description;\n\n public Tag(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public Tag(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n}" ]
import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.plugin.logging.Log; import com.spirit21.swagger.converter.Regex; import com.spirit21.swagger.converter.loader.ClassLoader; import com.spirit21.swagger.converter.models.Definition; import com.spirit21.swagger.converter.models.JavaFile; import com.spirit21.swagger.converter.models.Parameter; import com.spirit21.swagger.converter.models.Resource; import com.spirit21.swagger.converter.models.SwaggerModel; import com.spirit21.swagger.converter.models.Tag;
package com.spirit21.swagger.converter.parsers; /** * * @author dsimon * */ public class ResourceParser extends AbstractParser implements SwaggerParser { public ResourceParser(Log log, ClassLoader loader, List<Tag> tags, List<Definition> definitions) { super(log, loader, tags, definitions); } @Override public List<SwaggerModel> parse(List<JavaFile> javaFiles) throws ParserException, ClassNotFoundException { List<SwaggerModel> resources = new ArrayList<>(); for (JavaFile file : javaFiles) { Class<?> cls = loader.loadClass( file.getPackageName() + "." + file.getFileName().substring(0, file.getFileName().length() - 5));
Resource newResource = findResourceInJavaFile(file, cls);
5
KostyaSha/github-integration-plugin
github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRBuildStatusPublisher.java
[ "public class GitHubPRCause extends GitHubCause<GitHubPRCause> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRCause.class);\n\n private String headSha;\n private int number;\n private boolean mergeable;\n private String targetBranch;\n private String sourceBranch;\n private String prAuthorEmail;\n private String body;\n\n private String sourceRepoOwner;\n private String triggerSenderName = \"\";\n private String triggerSenderEmail = \"\";\n private Set<String> labels;\n /**\n * In case triggered because of commit. See\n * {@link org.jenkinsci.plugins.github.pullrequest.events.impl.GitHubPROpenEvent}\n */\n private String commitAuthorName;\n private String commitAuthorEmail;\n\n private String condRef;\n private String state;\n private String commentAuthorName;\n private String commentAuthorEmail;\n private String commentBody;\n private String commentBodyMatch;\n\n public GitHubPRCause() {\n }\n\n public GitHubPRCause(GHPullRequest remotePr,\n GitHubPRRepository localRepo,\n String reason,\n boolean skip) {\n this(new GitHubPRPullRequest(remotePr), remotePr.getUser(), localRepo, skip, reason);\n withRemoteData(remotePr);\n if (localRepo != null) {\n withLocalRepo(localRepo);\n }\n }\n\n @Deprecated\n public GitHubPRCause(GHPullRequest remotePr,\n String reason,\n boolean skip) {\n this(remotePr, null, reason, skip);\n }\n\n public GitHubPRCause(GitHubPRPullRequest pr,\n GHUser triggerSender,\n GitHubPRRepository localRepo,\n boolean skip,\n String reason) {\n this(pr.getHeadSha(), pr.getNumber(),\n pr.isMergeable(), pr.getBaseRef(), pr.getHeadRef(),\n pr.getUserEmail(), pr.getTitle(), pr.getHtmlUrl(), pr.getSourceRepoOwner(),\n pr.getLabels(),\n triggerSender, skip, reason, \"\", \"\", pr.getState());\n this.body = pr.getBody();\n if (localRepo != null) {\n withLocalRepo(localRepo);\n }\n }\n\n @Deprecated\n public GitHubPRCause(GitHubPRPullRequest pr,\n GHUser triggerSender,\n boolean skip,\n String reason) {\n this(pr, triggerSender, null, skip, reason);\n }\n\n // FIXME (sizes) ParameterNumber: More than 7 parameters (found 15).\n // CHECKSTYLE:OFF\n public GitHubPRCause(String headSha, int number, boolean mergeable,\n String targetBranch, String sourceBranch, String prAuthorEmail,\n String title, URL htmlUrl, String sourceRepoOwner, Set<String> labels,\n GHUser triggerSender, boolean skip, String reason,\n String commitAuthorName, String commitAuthorEmail,\n String state) {\n // CHECKSTYLE:ON\n this.headSha = headSha;\n this.number = number;\n this.mergeable = mergeable;\n this.targetBranch = targetBranch;\n this.sourceBranch = sourceBranch;\n this.prAuthorEmail = prAuthorEmail;\n withTitle(title);\n withHtmlUrl(htmlUrl);\n this.sourceRepoOwner = sourceRepoOwner;\n this.labels = labels;\n withSkip(skip);\n withReason(reason);\n this.commitAuthorName = commitAuthorName;\n this.commitAuthorEmail = commitAuthorEmail;\n\n if (nonNull(triggerSender)) {\n try {\n this.triggerSenderName = triggerSender.getName();\n } catch (IOException e) {\n LOGGER.error(\"Can't get trigger sender name from remote PR\");\n }\n\n try {\n this.triggerSenderEmail = triggerSender.getEmail();\n } catch (IOException e) {\n LOGGER.error(\"Can't get trigger sender email from remote PR\");\n }\n }\n\n this.condRef = mergeable ? \"merge\" : \"head\";\n\n this.state = state;\n }\n\n @Override\n public GitHubPRCause withLocalRepo(@NonNull GitHubRepository localRepo) {\n withGitUrl(localRepo.getGitUrl());\n withSshUrl(localRepo.getSshUrl());\n // html url is set from constructor and points to pr\n // withHtmlUrl(localRepo.getGithubUrl());\n return this;\n }\n\n /**\n * Copy constructor\n */\n public GitHubPRCause(GitHubPRCause orig) {\n this(orig.getHeadSha(), orig.getNumber(), orig.isMergeable(),\n orig.getTargetBranch(), orig.getSourceBranch(),\n orig.getPRAuthorEmail(), orig.getTitle(),\n orig.getHtmlUrl(), orig.getSourceRepoOwner(), orig.getLabels(), null,\n orig.isSkip(), orig.getReason(), orig.getCommitAuthorName(), orig.getCommitAuthorEmail(), orig.getState());\n withTriggerSenderName(orig.getTriggerSenderEmail());\n withTriggerSenderEmail(orig.getTriggerSenderEmail());\n withBody(orig.getBody());\n withCommentAuthorName(orig.getCommentAuthorName());\n withCommentAuthorEmail(orig.getCommentAuthorEmail());\n withCommentBody(orig.getCommentBody());\n withCommentBodyMatch(orig.getCommentBodyMatch());\n withCommitAuthorName(orig.getCommitAuthorName());\n withCommitAuthorEmail(orig.getCommitAuthorEmail());\n withCondRef(orig.getCondRef());\n withGitUrl(orig.getGitUrl());\n withSshUrl(orig.getSshUrl());\n withPollingLog(orig.getPollingLog());\n }\n\n public static GitHubPRCause newGitHubPRCause() {\n return new GitHubPRCause();\n }\n\n /**\n * @see #headSha\n */\n public GitHubPRCause withHeadSha(String headSha) {\n this.headSha = headSha;\n return this;\n }\n\n /**\n * @see #number\n */\n public GitHubPRCause withNumber(int number) {\n this.number = number;\n return this;\n }\n\n /**\n * @see #mergeable\n */\n public GitHubPRCause withMergeable(boolean mergeable) {\n this.mergeable = mergeable;\n return this;\n }\n\n /**\n * @see #targetBranch\n */\n public GitHubPRCause withTargetBranch(String targetBranch) {\n this.targetBranch = targetBranch;\n return this;\n }\n\n /**\n * @see #sourceBranch\n */\n public GitHubPRCause withSourceBranch(String sourceBranch) {\n this.sourceBranch = sourceBranch;\n return this;\n }\n\n /**\n * @see #prAuthorEmail\n */\n public GitHubPRCause withPrAuthorEmail(String prAuthorEmail) {\n this.prAuthorEmail = prAuthorEmail;\n return this;\n }\n\n /**\n * @see #sourceRepoOwner\n */\n public GitHubPRCause withSourceRepoOwner(String sourceRepoOwner) {\n this.sourceRepoOwner = sourceRepoOwner;\n return this;\n }\n\n /**\n * @see #triggerSenderName\n */\n public GitHubPRCause withTriggerSenderName(String triggerSenderName) {\n this.triggerSenderName = triggerSenderName;\n return this;\n }\n\n /**\n * @see #triggerSenderEmail\n */\n public GitHubPRCause withTriggerSenderEmail(String triggerSenderEmail) {\n this.triggerSenderEmail = triggerSenderEmail;\n return this;\n }\n\n /**\n * @see #labels\n */\n public GitHubPRCause withLabels(Set<String> labels) {\n this.labels = labels;\n return this;\n }\n\n /**\n * @see #commitAuthorName\n */\n public GitHubPRCause withCommitAuthorName(String commitAuthorName) {\n this.commitAuthorName = commitAuthorName;\n return this;\n }\n\n /**\n * @see #commitAuthorEmail\n */\n public GitHubPRCause withCommitAuthorEmail(String commitAuthorEmail) {\n this.commitAuthorEmail = commitAuthorEmail;\n return this;\n }\n\n /**\n * @see #condRef\n */\n public GitHubPRCause withCondRef(String condRef) {\n this.condRef = condRef;\n return this;\n }\n\n public GitHubPRCause withCommentAuthorName(String commentAuthorName) {\n this.commentAuthorName = commentAuthorName;\n return this;\n }\n\n public GitHubPRCause withCommentAuthorEmail(String commentAuthorEmail) {\n this.commentAuthorEmail = commentAuthorEmail;\n return this;\n }\n\n public GitHubPRCause withCommentBody(String commentBody) {\n this.commentBody = commentBody;\n return this;\n }\n\n public GitHubPRCause withCommentBodyMatch(String commentBodyMatch) {\n this.commentBodyMatch = commentBodyMatch;\n return this;\n }\n\n public String getBody() {\n return body;\n }\n\n public GitHubPRCause withBody(String body) {\n this.body = body;\n return this;\n }\n\n @Override\n public String getShortDescription() {\n return \"GitHub PR #\" + number + \": \" + getReason();\n }\n\n public String getHeadSha() {\n return headSha;\n }\n\n public boolean isMergeable() {\n return mergeable;\n }\n\n public int getNumber() {\n return number;\n }\n\n public String getTargetBranch() {\n return targetBranch;\n }\n\n public String getSourceBranch() {\n return sourceBranch;\n }\n\n public String getPRAuthorEmail() {\n return prAuthorEmail;\n }\n\n public String getSourceRepoOwner() {\n return sourceRepoOwner;\n }\n\n @NonNull\n public Set<String> getLabels() {\n return isNull(labels) ? Collections.emptySet() : labels;\n }\n\n public String getTriggerSenderName() {\n return triggerSenderName;\n }\n\n public String getTriggerSenderEmail() {\n return triggerSenderEmail;\n }\n\n public String getPrAuthorEmail() {\n return prAuthorEmail;\n }\n\n public String getCommitAuthorName() {\n return commitAuthorName;\n }\n\n public String getCommitAuthorEmail() {\n return commitAuthorEmail;\n }\n\n public String getState() {\n return state;\n }\n\n @NonNull\n public String getCondRef() {\n return condRef;\n }\n\n /**\n * When trigger by comment, author of comment.\n */\n public String getCommentAuthorName() {\n return commentAuthorName;\n }\n\n /**\n * When trigger by comment, author email of comment.\n */\n public String getCommentAuthorEmail() {\n return commentAuthorEmail;\n }\n\n /**\n * When trigger by comment, body of comment.\n */\n public String getCommentBody() {\n return commentBody;\n }\n\n /**\n * When trigger by comment, string matched to pattern.\n */\n public String getCommentBodyMatch() {\n return commentBodyMatch;\n }\n\n @Override\n public void fillParameters(List<ParameterValue> params) {\n GitHubPREnv.getParams(this, params);\n }\n\n @Override\n public GitHubSCMHead<GitHubPRCause> createSCMHead(String sourceId) {\n return new GitHubPRSCMHead(number, targetBranch, sourceId);\n }\n\n @Override\n public void onAddedTo(@NonNull Run run) {\n if (run.getParent().getParent() instanceof SCMSourceOwner) {\n // skip multibranch\n return;\n }\n\n // move polling log from cause to action\n try {\n GitHubPRPollingLogAction action = new GitHubPRPollingLogAction(run);\n FileUtils.writeStringToFile(action.getPollingLogFile(), getPollingLog());\n run.replaceAction(action);\n } catch (IOException e) {\n LOGGER.warn(\"Failed to persist the polling log\", e);\n }\n setPollingLog(null);\n }\n\n @Override\n public boolean equals(Object o) {\n return EqualsBuilder.reflectionEquals(this, o);\n }\n\n @Override\n public int hashCode() {\n return HashCodeBuilder.reflectionHashCode(this);\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);\n }\n\n}", "public class GitHubPRMessage extends AbstractDescribableImpl<GitHubPRMessage> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRMessage.class);\n\n private String content;\n\n @DataBoundConstructor\n public GitHubPRMessage(String content) {\n this.content = content;\n }\n\n /**\n * Expand all what we can from given run\n */\n @Restricted(NoExternalUse.class)\n @CheckForNull\n public String expandAll(Run<?, ?> run, TaskListener listener) throws IOException, InterruptedException {\n return expandAll(getContent(), run, listener);\n }\n\n /**\n * Expand all what we can from given run\n */\n @Restricted(NoExternalUse.class)\n @CheckForNull\n public static String expandAll(String content, Run<?, ?> run, TaskListener listener)\n throws IOException, InterruptedException {\n if (isEmpty(content)) {\n return content; // Do nothing for an empty String\n }\n\n // Expand environment variables\n String body = run.getEnvironment(listener).expand(content);\n\n // Expand build variables + token macro if they available\n if (run instanceof AbstractBuild<?, ?>) {\n final AbstractBuild<?, ?> build = (AbstractBuild<?, ?>) run;\n body = Util.replaceMacro(body, build.getBuildVariableResolver());\n\n try {\n Jenkins jenkins = Jenkins.getActiveInstance();\n ClassLoader uberClassLoader = jenkins.pluginManager.uberClassLoader;\n List macros = null;\n if (nonNull(jenkins.getPlugin(\"token-macro\"))) {\n // get private macroses like groovy template ${SCRIPT} if available\n if (nonNull(jenkins.getPlugin(\"email-ext\"))) {\n Class<?> contentBuilderClazz = uberClassLoader.loadClass(\"hudson.plugins.emailext.plugins.ContentBuilder\");\n Method getPrivateMacrosMethod = contentBuilderClazz.getDeclaredMethod(\"getPrivateMacros\");\n macros = new ArrayList((Collection) getPrivateMacrosMethod.invoke(null));\n }\n\n // call TokenMacro.expand(build, listener, content, false, macros)\n Class<?> tokenMacroClazz = uberClassLoader.loadClass(\"org.jenkinsci.plugins.tokenmacro.TokenMacro\");\n Method tokenMacroExpand = tokenMacroClazz.getDeclaredMethod(\"expand\", AbstractBuild.class,\n TaskListener.class, String.class, boolean.class, List.class);\n\n body = (String) tokenMacroExpand.invoke(null, build, listener, body, false, macros);\n }\n } catch (ClassNotFoundException e) {\n LOGGER.error(\"Can't find class\", e);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {\n LOGGER.error(\"Can't evaluate macro\", e);\n }\n }\n\n return body;\n }\n\n public String getContent() {\n return content;\n }\n\n @Override\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) super.getDescriptor();\n }\n\n @Symbol(\"githubPRMessage\")\n @Extension\n public static class DescriptorImpl extends Descriptor<GitHubPRMessage> {\n @Override\n public String getDisplayName() {\n return \"Expandable comment field\";\n }\n }\n}", "public class GitHubPRTrigger extends GitHubTrigger<GitHubPRTrigger> {\n private static final Logger LOG = LoggerFactory.getLogger(GitHubPRTrigger.class);\n public static final String FINISH_MSG = \"Finished GitHub Pull Request trigger check\";\n\n @CheckForNull\n private List<GitHubPREvent> events = new ArrayList<>();\n /**\n * Set PR(commit) status before build. No configurable message for it.\n */\n private boolean preStatus = false;\n\n @CheckForNull\n private GitHubPRUserRestriction userRestriction;\n @CheckForNull\n private GitHubPRBranchRestriction branchRestriction;\n\n @CheckForNull\n private transient GitHubPRPollingLogAction pollingLogAction;\n\n /**\n * For groovy UI\n */\n @Restricted(value = NoExternalUse.class)\n public GitHubPRTrigger() throws ANTLRException {\n super(\"\");\n }\n\n @DataBoundConstructor\n public GitHubPRTrigger(String spec,\n GitHubPRTriggerMode triggerMode,\n List<GitHubPREvent> events) throws ANTLRException {\n super(spec);\n setTriggerMode(triggerMode);\n this.events = Util.fixNull(events);\n }\n\n @DataBoundSetter\n public void setPreStatus(boolean preStatus) {\n this.preStatus = preStatus;\n }\n\n @DataBoundSetter\n public void setUserRestriction(GitHubPRUserRestriction userRestriction) {\n this.userRestriction = userRestriction;\n }\n\n @DataBoundSetter\n public void setBranchRestriction(GitHubPRBranchRestriction branchRestriction) {\n this.branchRestriction = branchRestriction;\n }\n\n public boolean isPreStatus() {\n return preStatus;\n }\n\n @NonNull\n public List<GitHubPREvent> getEvents() {\n return nonNull(events) ? events : emptyList();\n }\n\n public GitHubPRUserRestriction getUserRestriction() {\n return userRestriction;\n }\n\n public GitHubPRBranchRestriction getBranchRestriction() {\n return branchRestriction;\n }\n\n @Override\n public void start(Job<?, ?> job, boolean newInstance) {\n LOG.info(\"Starting GitHub Pull Request trigger for project {}\", job.getFullName());\n super.start(job, newInstance);\n\n if (newInstance && getRepoProvider().isManageHooks(this) && withHookTriggerMode().apply(job)) {\n try {\n getRepoProvider().registerHookFor(this);\n getErrorsAction().removeErrors(GitHubHookRegistrationError.class);\n } catch (Throwable error) {\n getErrorsAction().addOrReplaceError(new GitHubHookRegistrationError(\n String.format(\"Failed register hook for %s. <br/> Because %s\",\n job.getFullName(), error.toString())\n ));\n throw error;\n }\n }\n }\n\n /**\n * Blocking run.\n */\n @Override\n public void doRun() {\n doRun(null);\n }\n\n /**\n * non-blocking run.\n */\n @Override\n public void run() {\n if (getTriggerMode() != LIGHT_HOOKS) {\n // don't consume Timer threads\n queueRun(null);\n }\n }\n\n @CheckForNull\n @Override\n public GitHubPRPollingLogAction getPollingLogAction() {\n if (isNull(pollingLogAction) && nonNull(job)) {\n pollingLogAction = new GitHubPRPollingLogAction(job);\n }\n\n return pollingLogAction;\n }\n\n @Override\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) Jenkins.getInstance().getDescriptor(this.getClass());\n }\n\n /**\n * For running from external places. Goes to queue.\n * <p>\n *\n * @deprecated Why do we need to pass job here? Trigger.start() should happen when job is configured/loaded...\n */\n @Deprecated\n public void queueRun(Job<?, ?> job, final int prNumber) {\n this.job = job;\n queueRun(prNumber);\n }\n\n public void queueRun(final Integer prNumber) {\n getDescriptor().getQueue().execute(() -> doRun(prNumber));\n }\n\n /**\n * Runs check.\n * Synchronised because localRepository state is persisted after trigger decisions were made.\n * When multiple events triggering runs in queue they triggering builds in parallel.\n * TODO implement special queue for parallel prNumbers scans and make polling long async.\n *\n * @param prNumber - PR number for check, if null - then all PRs\n */\n public synchronized void doRun(Integer prNumber) {\n if (not(isBuildable()).apply(job)) {\n LOG.debug(\"Job {} is disabled, but trigger run!\", isNull(job) ? \"<no job>\" : job.getFullName());\n return;\n }\n\n if (!isSupportedTriggerMode(getTriggerMode())) {\n LOG.warn(\"Trigger mode {} is not supported yet ({})\", getTriggerMode(), job.getFullName());\n return;\n }\n\n GitHubPRRepository localRepository = job.getAction(GitHubPRRepository.class);\n if (isNull(localRepository)) {\n LOG.warn(\"Can't get repository info, maybe project {} misconfigured?\", job.getFullName());\n return;\n }\n\n List<GitHubPRCause> causes;\n\n try (LoggingTaskListenerWrapper listener =\n new LoggingTaskListenerWrapper(getPollingLogAction().getPollingLogFile(), UTF_8)) {\n long startTime = System.currentTimeMillis();\n listener.debug(\"Running GitHub Pull Request trigger check for {} on {}\",\n getDateTimeInstance().format(new Date(startTime)), localRepository.getFullName());\n try {\n localRepository.actualise(getRemoteRepository(), listener);\n\n causes = readyToBuildCauses(localRepository, listener, prNumber);\n\n localRepository.saveQuietly();\n\n // TODO print triggering to listener?\n from(causes).filter(new JobRunnerForCause(job, this)).toSet();\n } catch (Throwable t) {\n listener.error(\"Can't end trigger check!\", t);\n }\n\n long duration = System.currentTimeMillis() - startTime;\n listener.info(FINISH_MSG + \" for {} at {}. Duration: {}ms\",\n localRepository.getFullName(), getDateTimeInstance().format(new Date()), duration);\n } catch (Exception e) {\n // out of UI/user viewable error\n LOG.error(\"Can't process check ({})\", e.getMessage(), e);\n }\n }\n\n /**\n * runs check of local (last) Repository state (list of PRs) vs current remote state\n * - local state store only last open PRs\n * - if last open PR <-> now closed -> should trigger only when ClosePREvent exist\n * - last open PR <-> now changed -> trigger only\n * - special comment in PR -> trigger\n *\n * @param localRepository persisted data to compare with remote state\n * @param listener logger to write to console and to polling log\n * @param prNumber pull request number to fetch only required num. Can be null\n * @return causes which ready to be converted to job-starts. One cause per repo.\n */\n private List<GitHubPRCause> readyToBuildCauses(@NonNull GitHubPRRepository localRepository,\n @NonNull LoggingTaskListenerWrapper listener,\n @Nullable Integer prNumber) {\n try {\n GitHub github = getRepoProvider().getGitHub(this);\n if (isNull(github)) {\n LOG.error(\"GitHub connection is null, check Repo Providers!\");\n throw new IllegalStateException(\"GitHub connection is null, check Repo Providers!\");\n }\n\n GHRateLimit rateLimitBefore = github.getRateLimit();\n listener.debug(\"GitHub rate limit before check: {}\", rateLimitBefore);\n\n // get local and remote list of PRs\n //FIXME HiddenField: 'remoteRepository' hides a field? renamed to `remoteRepo`\n GHRepository remoteRepo = getRemoteRepository();\n Set<GHPullRequest> remotePulls = pullRequestsToCheck(prNumber, remoteRepo, localRepository);\n\n Set<GHPullRequest> prepared = from(remotePulls)\n .filter(badState(localRepository, listener))\n .filter(notUpdated(localRepository, listener))\n .toSet();\n\n List<GitHubPRCause> causes = from(prepared)\n .filter(and(\n ifSkippedFirstRun(listener, isSkipFirstRun()),\n withBranchRestriction(listener, getBranchRestriction()),\n withUserRestriction(listener, getUserRestriction())\n ))\n .transform(toGitHubPRCause(localRepository, listener, this))\n .filter(notNull())\n .toList();\n\n LOG.trace(\"Causes count for {}: {}\", localRepository.getFullName(), causes.size());\n\n // refresh all PRs because user may add events that may trigger unexpected builds.\n from(remotePulls).transform(updateLocalRepo(localRepository)).toSet();\n\n saveIfSkipFirstRun();\n\n GHRateLimit rateLimitAfter = github.getRateLimit();\n int consumed = rateLimitBefore.remaining - rateLimitAfter.remaining;\n LOG.info(\"GitHub rate limit after check {}: {}, consumed: {}, checked PRs: {}\",\n localRepository.getFullName(), rateLimitAfter, consumed, remotePulls.size());\n\n return causes;\n } catch (IOException e) {\n listener.error(\"Can't get build causes: \", e);\n return emptyList();\n }\n }\n\n private static boolean isSupportedTriggerMode(GitHubPRTriggerMode mode) {\n return mode != LIGHT_HOOKS;\n }\n\n /**\n * @return remote pull requests for future analysing.\n */\n private static Set<GHPullRequest> pullRequestsToCheck(@Nullable Integer prNumber,\n @NonNull GHRepository remoteRepo,\n @NonNull GitHubPRRepository localRepo) throws IOException {\n if (prNumber != null) {\n return execute(() -> singleton(remoteRepo.getPullRequest(prNumber)));\n } else {\n List<GHPullRequest> remotePulls = execute(() -> remoteRepo.getPullRequests(GHIssueState.OPEN));\n\n Set<Integer> remotePRNums = from(remotePulls).transform(extractPRNumber()).toSet();\n\n return from(localRepo.getPulls().keySet())\n // add PRs that was closed on remote\n .filter(not(in(remotePRNums)))\n .transform(fetchRemotePR(remoteRepo))\n .filter(notNull())\n .append(remotePulls)\n .toSet();\n }\n }\n\n @Override\n public String getFinishMsg() {\n return FINISH_MSG;\n }\n\n @Symbol(\"githubPullRequests\")\n @Extension\n public static class DescriptorImpl extends GitHubTriggerDescriptor {\n\n public DescriptorImpl() {\n load();\n }\n\n @NonNull\n @Override\n public String getDisplayName() {\n return \"GitHub Pull Requests\";\n }\n\n // list all available descriptors for choosing in job configuration\n public static List<GitHubPREventDescriptor> getEventDescriptors() {\n return GitHubPREventDescriptor.all();\n }\n\n public static DescriptorImpl get() {\n return Trigger.all().get(DescriptorImpl.class);\n }\n }\n}", "public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {\n\n @CheckForNull\n private StatusVerifier statusVerifier;\n\n @CheckForNull\n private PublisherErrorHandler errorHandler;\n\n public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {\n this.statusVerifier = statusVerifier;\n this.errorHandler = errorHandler;\n }\n\n public StatusVerifier getStatusVerifier() {\n return statusVerifier;\n }\n\n public PublisherErrorHandler getErrorHandler() {\n return errorHandler;\n }\n\n protected void handlePublisherError(Run<?, ?> run) {\n if (errorHandler != null) {\n errorHandler.markBuildAfterError(run);\n }\n }\n\n public final BuildStepMonitor getRequiredMonitorService() {\n return BuildStepMonitor.NONE;\n }\n\n public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {\n return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);\n }\n\n public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {\n @Override\n public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {\n return true;\n }\n\n @Override\n public abstract String getDisplayName();\n }\n}", "public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {\n\n private Result buildStatus;\n\n @DataBoundConstructor\n public PublisherErrorHandler(Result buildStatus) {\n this.buildStatus = buildStatus;\n }\n\n public Result getBuildStatus() {\n return buildStatus;\n }\n\n public Result markBuildAfterError(Run<?, ?> run) {\n run.setResult(buildStatus);\n return buildStatus;\n }\n\n @Symbol(\"statusOnPublisherError\")\n @Extension\n public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {\n @NonNull\n @Override\n public String getDisplayName() {\n return \"Set build status if publisher failed\";\n }\n\n public ListBoxModel doFillBuildStatusItems() {\n ListBoxModel items = new ListBoxModel();\n items.add(Result.UNSTABLE.toString());\n items.add(Result.FAILURE.toString());\n return items;\n }\n }\n}", "public static void addComment(final int id, final String comment, final Run<?, ?> run, final TaskListener listener) {\n if (comment == null || comment.trim().isEmpty()) {\n return;\n }\n\n String finalComment = comment;\n if (nonNull(run) && nonNull(listener)) {\n try {\n finalComment = run.getEnvironment(listener).expand(comment);\n } catch (Exception e) {\n LOG.error(\"Error\", e);\n }\n }\n\n try {\n if (nonNull(run)) {\n final GitHubPRTrigger trigger = ghPRTriggerFromRun(run);\n\n GHRepository ghRepository = trigger.getRemoteRepository();\n ghRepository.getPullRequest(id).comment(finalComment);\n }\n } catch (IOException ex) {\n LOG.error(\"Couldn't add comment to pull request #{}: '{}'\", id, finalComment, ex);\n }\n}", "public static GHCommitState getCommitState(final Run<?, ?> run, final GHCommitState unstableAs) {\n GHCommitState state;\n Result result = run.getResult();\n if (isNull(result)) {\n LOG.error(\"{} result is null.\", run);\n state = GHCommitState.ERROR;\n } else if (result.isBetterOrEqualTo(SUCCESS)) {\n state = GHCommitState.SUCCESS;\n } else if (result.isBetterOrEqualTo(UNSTABLE)) {\n state = unstableAs;\n } else {\n state = GHCommitState.FAILURE;\n }\n return state;\n}", "@CheckForNull\npublic static GitHubPRCause ghPRCauseFromRun(Run<?, ?> run) {\n return ghCauseFromRun(run, GitHubPRCause.class);\n}", "@CheckForNull\npublic static GitHubPRTrigger ghPRTriggerFromRun(Run<?, ?> run) {\n return triggerFrom(run.getParent(), GitHubPRTrigger.class);\n}" ]
import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractDescribableImpl; import hudson.model.AbstractProject; import hudson.model.Api; import hudson.model.Descriptor; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Publisher; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause; import org.jenkinsci.plugins.github.pullrequest.GitHubPRMessage; import org.jenkinsci.plugins.github.pullrequest.GitHubPRTrigger; import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher; import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler; import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.github.GHCommitState; import org.kohsuke.stapler.DataBoundConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; import java.io.PrintStream; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.addComment; import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getCommitState; import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRCauseFromRun; import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.ghPRTriggerFromRun;
package org.jenkinsci.plugins.github.pullrequest.publishers.impl; /** * Sets build status on GitHub. * * @author Alina Karpovich * @author Kanstantsin Shautsou */ public class GitHubPRBuildStatusPublisher extends GitHubPRAbstractPublisher { private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRBuildStatusPublisher.class); private GitHubPRMessage statusMsg = new GitHubPRMessage("${GITHUB_PR_COND_REF} run ended"); private GHCommitState unstableAs = GHCommitState.FAILURE; private BuildMessage buildMessage = new BuildMessage(); /** * Constructor with defaults. Only for groovy UI. */ @Restricted(NoExternalUse.class) public GitHubPRBuildStatusPublisher() { super(null, null); } @DataBoundConstructor public GitHubPRBuildStatusPublisher(GitHubPRMessage statusMsg, GHCommitState unstableAs, BuildMessage buildMessage, StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) { super(statusVerifier, errorHandler); if (statusMsg != null && isNotEmpty(statusMsg.getContent())) { this.statusMsg = statusMsg; } this.unstableAs = unstableAs; this.buildMessage = buildMessage; } @Override public void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull Launcher launcher, @NonNull TaskListener listener) throws InterruptedException, IOException { PrintStream listenerLogger = listener.getLogger(); String publishedURL = getTriggerDescriptor().getJenkinsURL(); if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) { return; } if (isEmpty(publishedURL)) { return; } GHCommitState state = getCommitState(run, unstableAs); GitHubPRCause c = ghPRCauseFromRun(run); String statusMsgValue = getStatusMsg().expandAll(run, listener); String buildUrl = publishedURL + run.getUrl(); LOGGER.info("Setting status of {} to {} with url {} and message: {}", c.getHeadSha(), state, buildUrl, statusMsgValue); // TODO check permissions to write human friendly message final GitHubPRTrigger trigger = ghPRTriggerFromRun(run); if (isNull(trigger)) { listener.error("Can't get trigger for this run! Silently skipping. " + "TODO implement error handler, like in publishers"); return; } try { trigger.getRemoteRepository().createCommitStatus(c.getHeadSha(), state, buildUrl, statusMsgValue, run.getParent().getFullName()); } catch (IOException ex) { if (nonNull(buildMessage)) { String comment = null; LOGGER.error("Could not update commit status of the Pull Request on GitHub. ", ex); if (state == GHCommitState.SUCCESS) { comment = buildMessage.getSuccessMsg().expandAll(run, listener); } else if (state == GHCommitState.FAILURE) { comment = buildMessage.getFailureMsg().expandAll(run, listener); } listenerLogger.println("Adding comment..."); LOGGER.info("Adding comment, because: ", ex);
addComment(c.getNumber(), comment, run, listener);
5
sensorstorm/StormCV
stormcv-examples/src/nl/tno/stormcv/example/E9_ContrastEnhancementTopology.java
[ "public class StormCVConfig extends Config{\n\n\tprivate static final long serialVersionUID = 6290659199719921212L;\n\n\t/**\n\t * <b>Boolean (default = false)</b> configuration parameter indicating if the spout must cache emitted tuples so they can be replayed\n\t */\n\tpublic static final String STORMCV_SPOUT_FAULTTOLERANT = \"stormcv.spout.faulttolerant\";\n\t\n\t/**\n\t * <b>String (default = \"jpg\" (Frame.JPG))</b> configuration parameter setting the image encoding for frames in the topology. It is up to Operation implementations\n\t * to read this configuration parameter and use it properly.\n\t */\n\tpublic static final String STORMCV_FRAME_ENCODING = \"stormcv.frame.encoding\";\n\t\n\t/**\n\t * <b>Integer (default = 30)</b> configuration parameter setting the maximum time to live for items being cached within the topology (both spouts and bolts use this configuration)\n\t */\n\tpublic static final String STORMCV_CACHES_TIMEOUT_SEC = \"stormcv.caches.timeout\";\n\t\n\t/**\n\t * <b>Integer (default = 500)</b> configuration parameter setting the maximum number of elements being cached by spouts and bolts (used to avoid memory overload) \n\t */\n\tpublic static final String STORMCV_CACHES_MAX_SIZE = \"stormcv.caches.maxsize\";\n\t\n\t/**\n\t * <b>List<Class) (default = NONE) </b> configuration parameter the available {@link FileConnector} in the topology\n\t */\n\tpublic static final String STORMCV_CONNECTORS = \"stormcv.connectors\";\n\t\n\t/**\n\t * <b>Integer (default = 30)</b> configuration parameter setting the maximum idle time in seconds after which the {@link StreamWriterOperation} will close the file\n\t */\n\tpublic static final String STORMCV_MAXIDLE_SEC = \"stormcv.streamwriter.maxidlesecs\";\n\t\n\t/**\n\t * <b>String</b> configuration parameter setting the library name of the OpenCV lib to be used\n\t */\n\tpublic static final String STORMCV_OPENCV_LIB = \"stormcv.opencv.lib\";\n\t\n\t\n\t/**\n\t * Creates a specific Configuration for StormCV.\n\t * <ul>\n\t * <li>Sets buffer sizes to 2 to optimize for few large size {@link Tuple}s instead of loads of small sized Tuples</li>\n\t * <li>Registers known Kryo serializers for the Model. Other serializers can be added using the registerSerialization function.</li>\n\t * <li>Registers known {@link FileConnector} implementations. New file connectors can be added through registerConnector</li>\n\t * </ul>\n\t */\n\tpublic StormCVConfig(){\n\t\tsuper();\n\t\t// ------- Create StormCV specific config -------\n\t\tput(Config.TOPOLOGY_RECEIVER_BUFFER_SIZE, 2); // sets the maximum number of messages to batch before sending them to executers\n\t\tput(Config.TOPOLOGY_TRANSFER_BUFFER_SIZE, 2); // sets the size of the output queue for each worker.\n\t\tput(STORMCV_FRAME_ENCODING, Frame.JPG_IMAGE); // sets the encoding of frames which determines both serialization speed and tuple size\n\t\t\n\t\t// register the basic set Kryo serializers\n\t\tregisterSerialization(VideoChunk.class, VideoChunkSerializer.class);\n\t\tregisterSerialization(GroupOfFrames.class, GroupOfFramesSerializer.class);\n\t\tregisterSerialization(Frame.class, FrameSerializer.class);\n\t\tregisterSerialization(Descriptor.class, DescriptorSerializer.class);\n\t\tregisterSerialization(Feature.class, FeatureSerializer.class);\n\t\t\n\t\t// register FileConnectors\n\t\tArrayList<String> connectorList = new ArrayList<String>();\n\t\tconnectorList.add(LocalFileConnector.class.getName());\n\t\tconnectorList.add(S3Connector.class.getName());\n\t\tconnectorList.add(FtpConnector.class.getName());\n\t\tconnectorList.add(ClasspathConnector.class.getName());\n\t\tput(StormCVConfig.STORMCV_CONNECTORS, connectorList);\n\t}\n\t\n\t/**\n\t * Registers an {@link FileConnector} class which can be used throughout the topology\n\t * @param connectorClass\n\t * @return\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic StormCVConfig registerConnector(Class<? extends FileConnector> connectorClass){\n\t\t((ArrayList<String>)get(StormCVConfig.STORMCV_CONNECTORS)).add(connectorClass.getName());\n\t\treturn this;\n\t}\n\t\n}", "public class SlidingWindowBatcher implements IBatcher{\n\n\tprivate static final long serialVersionUID = -4296426517808304248L;\n\tprivate int windowSize;\n\tprivate int sequenceDelta;\n\tprivate int maxSize = Integer.MAX_VALUE;\n\n\tpublic SlidingWindowBatcher(int windowSize, int sequenceDelta){\n\t\tthis.windowSize = windowSize;\n\t\tthis.sequenceDelta = sequenceDelta;\n\t}\n\t\n\tpublic SlidingWindowBatcher maxSize(int size){\n\t\tthis.maxSize = size;\n\t\treturn this;\n\t}\n\t\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic void prepare(Map conf) throws Exception {\t}\n\n\t@Override\n\tpublic List<List<CVParticle>> partition(History history, List<CVParticle> currentSet) {\n\t\tList<List<CVParticle>> result = new ArrayList<List<CVParticle>>();\n\t\tfor(int i=0; i<=currentSet.size()-windowSize; i++){\n\t\t\tList<CVParticle> window = new ArrayList<CVParticle>();\n\t\t\twindow.addAll(currentSet.subList(i, i+windowSize)); // add all is used to avoid ConcurrentModificationException when the History cleans stuff up\n\t\t\tif(assessWindow(window) || currentSet.size() > maxSize){\n\t\t\t\tresult.add(window);\n\t\t\t\thistory.removeFromHistory(window.get(0));\n\t\t\t} else break;\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Checks if the provided window fits the required windowSize and sequenceDelta criteria\n\t * @param window\n\t * @return\n\t */\n\tprivate boolean assessWindow(List<CVParticle> window){\n\t\tif(window.size() != windowSize) return false;\n\t\tlong previous = window.get(0).getSequenceNr();\n\t\tfor(int i=1; i<window.size(); i++){\n\t\t\tif(window.get(i).getSequenceNr() - previous != sequenceDelta) return false;\n\t\t\tprevious = window.get(i).getSequenceNr();\n\t\t}\n\t\treturn true;\n\t}\n\t\n}", "public class BatchInputBolt extends CVParticleBolt implements RemovalListener<CVParticle, String>{\n\n\tprivate static final long serialVersionUID = -2394218774274388493L;\n\n\tprivate IBatchOperation<? extends CVParticle> operation;\n\tprivate IBatcher batcher;\n\tprivate int TTL = 29;\n\tprivate int maxSize = 256;\n\tprivate Fields groupBy;\n\tprivate History history;\n\tprivate boolean refreshExperation = true;\n\t\n\t/**\n\t * Creates a BatchInputBolt with given Batcher and BatchOperation.\n\t * @param batcher\n\t * @param operation\n\t * @param refreshExpirationOfOlderItems\n\t */\n\tpublic BatchInputBolt(IBatcher batcher, IBatchOperation<? extends CVParticle> operation){\n\t\tthis.operation = operation;\n\t\tthis.batcher = batcher;\n\t}\n\t\n\t/**\n\t * Sets the time to live for items being cached by this bolt\n\t * @param ttl\n\t * @return\n\t */\n\tpublic BatchInputBolt ttl(int ttl){\n\t\tthis.TTL = ttl;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Specifies the maximum size of the cashe used. Hitting the maximum will cause oldest items to be \n\t * expired from the cache\n\t * @param size\n\t * @return\n\t */\n\tpublic BatchInputBolt maxCacheSize(int size){\n\t\tthis.maxSize = size;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Specifies the fields used to group items on. \n\t * @param group\n\t * @return\n\t */\n\tpublic BatchInputBolt groupBy(Fields group){\n\t\tthis.groupBy = group;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Specifies weather items with hither sequence number within a group must have their\n\t * ttl's refreshed if an item with lower sequence number is added\n\t * @param refresh\n\t * @return\n\t */\n\tpublic BatchInputBolt refreshExpiration(boolean refresh){\n\t\tthis.refreshExperation = refresh;\n\t\treturn this;\n\t}\n\t\n\t\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tvoid prepare(Map conf, TopologyContext context) {\n\t\t// use TTL and maxSize from config if they were not set explicitly using the constructor (implicit way of doing this...)\n\t\tif(TTL == 29) TTL = conf.get(StormCVConfig.STORMCV_CACHES_TIMEOUT_SEC) == null ? TTL : ((Long)conf.get(StormCVConfig.STORMCV_CACHES_TIMEOUT_SEC)).intValue();\n\t\tif(maxSize == 256) maxSize = conf.get(StormCVConfig.STORMCV_CACHES_MAX_SIZE) == null ? maxSize : ((Long)conf.get(StormCVConfig.STORMCV_CACHES_MAX_SIZE)).intValue();\n\t\thistory = new History(this);\n\t\t\n\t\t// IF NO grouping was set THEN select the first grouping registered for the spout as the grouping used within the Spout (usually a good guess)\n\t\tif(groupBy == null){\n\t\t\tMap<GlobalStreamId, Grouping> sources = context.getSources(context.getThisComponentId());\n\t\t\tfor(GlobalStreamId id : sources.keySet()){\n\t\t\t\tGrouping grouping = sources.get(id);\n\t\t\t\tthis.groupBy = new Fields(grouping.get_fields());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// prepare the selector and operation\n\t\ttry {\n\t\t\tbatcher.prepare(conf);\n\t\t\toperation.prepare(conf, context);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Unable to preapre the Selector or Operation\", e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void declareOutputFields(OutputFieldsDeclarer declarer) {\n\t\tdeclarer.declare(operation.getSerializer().getFields());\n\t}\n\n\t/**\n\t * Overloaded from superclass, adds the input to the history and asks the selector to create batches (if possible)\n\t * for all the items in the history. If one or multiple batches could be created the operation\n\t * will be executed for each batch and the results are emitted by this bolt.\n\t */\n\t@Override\n\tpublic void execute(Tuple input) {\n\t\tString group = generateKey(input);\n\t\tif(group == null){\n\t\t\tcollector.fail(input);\n\t\t\treturn;\n\t\t}\n\t\tCVParticle particle;\n\t\ttry {\n\t\t\tparticle = deserialize(input);\n\t\t\thistory.add(group, particle);\n\t\t\tList<List<CVParticle>> batches = batcher.partition(history, history.getGroupedItems(group));\n\t\t\tfor(List<CVParticle> batch : batches){\n\t\t\t\ttry{\n\t\t\t\t\tList<? extends CVParticle> results = operation.execute(batch);\n\t\t\t\t\tfor(CVParticle result : results){\n\t\t\t\t\t\tresult.setRequestId(particle.getRequestId());\n\t\t\t\t\t\tcollector.emit(input, serializers.get(result.getClass().getName()).toTuple(result));\n\t\t\t\t\t}\n\t\t\t\t}catch(Exception e){\n\t\t\t\t\tlogger.warn(\"Unable to to process batch due to \", e);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e1) {\n\t\t\tlogger.warn(\"Unable to deserialize Tuple\", e1);\n\t\t}\n\t\tidleTimestamp = System.currentTimeMillis();\n\t}\n\t\n\t@Override\n\tList<? extends CVParticle> execute(CVParticle input) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Generates the key for the provided tuple using the fields provided at construction time\n\t * @param tuple\n\t * @return key created for this tuple or NULL if no key could be created (i.e. tuple does not contain any of groupBy Fields)\n\t */\n\tprivate String generateKey(Tuple tuple){\n\t\tString key = new String();\n\t\tfor(String field : groupBy){\n\t\t\tkey += tuple.getValueByField(field)+\"_\";\n\t\t}\n\t\tif(key.length() == 0) return null;\n\t\treturn key;\n\t}\n\t\n\t/**\n\t * Callback method for removal of items from the histories cache. Items removed from the cache need to be acked or failed\n\t * according to the reason they were removed\n\t */\n\t@Override\n\tpublic void onRemoval(RemovalNotification<CVParticle, String> notification) {\n\t\t// make sure the CVParticle object is removed from the history (even if removal was automatic!)\n\t\thistory.clear(notification.getKey(), notification.getValue());\n\t\tif(notification.getCause() == RemovalCause.EXPIRED || notification.getCause() == RemovalCause.SIZE){\n\t\t\t// item removed automatically --> fail the tuple\n\t\t\tcollector.fail(notification.getKey().getTuple());\n\t\t}else{\n\t\t\t// item removed explicitly --> ack the tuple\n\t\t\tcollector.ack(notification.getKey().getTuple());\n\t\t}\n\t}\n\t\n\t// ----------------------------- HISTORY CONTAINER ---------------------------\n\t/**\n\t * Container that manages the history of tuples received and allows others to clean up the history retained.\n\t * \n\t * @author Corne Versloot\n\t *\n\t */\n\tpublic class History implements Serializable{\n\t\t\n\t\tprivate static final long serialVersionUID = 5353548571380002710L;\n\t\t\n\t\tprivate Cache<CVParticle, String> inputCache;\n\t\tprivate HashMap<String, List<CVParticle>> groups;\n\t\t\n\t\t/**\n\t\t * Creates a History object for the specified Bolt (which is used to ack or fail items removed from the history).\n\t\t * @param bolt\n\t\t */\n\t\tprivate History(BatchInputBolt bolt){\n\t\t\tgroups = new HashMap<String, List<CVParticle>>();\n\t\t\tinputCache = CacheBuilder.newBuilder()\n\t\t\t\t\t.maximumSize(maxSize)\n\t\t\t\t\t.expireAfterAccess(TTL, TimeUnit.SECONDS) // resets also on get(...)!\n\t\t\t\t\t.removalListener(bolt)\n\t\t\t\t\t.build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Adds the new CVParticle object to the history and returns the list of items it was grouped with. \n\t\t * @param group the name of the group the CVParticle belongs to\n\t\t * @param particle the CVParticle object that needs to be added to the history.\n\t\t */\n\t\tprivate void add(String group, CVParticle particle){\n\t\t\tif(!groups.containsKey(group)){\n\t\t\t\tgroups.put(group, new ArrayList<CVParticle>());\n\t\t\t}\n\t\t\tList<CVParticle> list = groups.get(group);\n\t\t\tint i;\n\t\t\tfor(i = list.size()-1; i>=0; i--){\n\t\t\t\tif( particle.getSequenceNr() > list.get(i).getSequenceNr()){\n\t\t\t\t\tlist.add(i+1, particle);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(refreshExperation){\n\t\t\t\t\tinputCache.getIfPresent(list.get(i)); // touch the item passed in the cache to reset its expiration timer\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(i < 0) list.add(0, particle);\n\t\t\tinputCache.put(particle, group);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Removes the object from the history. This will tricker an ACK to be send. \n\t\t * @param particle\n\t\t */\n\t\tpublic void removeFromHistory(CVParticle particle){\n\t\t\tinputCache.invalidate(particle);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Removes the object from the group\n\t\t * @param particle\n\t\t * @param group\n\t\t */\n\t\tprivate void clear(CVParticle particle, String group){\n\t\t\tif(!groups.containsKey(group)) return;\n\t\t\tgroups.get(group).remove(particle);\n\t\t\tif(groups.get(group).size() == 0) groups.remove(group);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns all the items in this history that belong to the specified group\n\t\t * @param group\n\t\t * @return\n\t\t */\n\t\tpublic List<CVParticle> getGroupedItems(String group){\n\t\t\treturn groups.get(group); \n\t\t}\n\t\t\n\t\tpublic long size(){\n\t\t\treturn inputCache.size();\n\t\t}\n\t\t\n\t\tpublic String toString(){\n\t\t\tString result = \"\";\n\t\t\tfor(String group : groups.keySet()){\n\t\t\t\tresult += \" \"+group+\" : \"+groups.get(group).size()+\"\\r\\n\";\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t}// end of History class\n\n}", "public class SingleInputBolt extends CVParticleBolt {\n\t\n\tprivate static final long serialVersionUID = 8954087163234223475L;\n\n\tprivate ISingleInputOperation<? extends CVParticle> operation;\n\n\t/**\n\t * Constructs a SingleInputOperation \n\t * @param operation the operation to be performed\n\t */\n\tpublic SingleInputBolt(ISingleInputOperation<? extends CVParticle> operation){\n\t\tthis.operation = operation;\n\t}\n\t\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tvoid prepare(Map stormConf, TopologyContext context) {\n\t\ttry {\n\t\t\toperation.prepare(stormConf, context);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Unale to prepare Operation \", e);\n\t\t}\t\t\n\t}\n\t\n\n\t@Override\n\tpublic void declareOutputFields(OutputFieldsDeclarer declarer) {\n\t\tdeclarer.declare(operation.getSerializer().getFields());\n\t}\n\n\t@Override\n\tList<? extends CVParticle> execute(CVParticle input) throws Exception{\n\t\tList<? extends CVParticle> result = operation.execute(input);\n\t\t// copy metadata from input to output if configured to do so\n\t\tfor(CVParticle s : result){\n\t\t\tfor(String key : input.getMetadata().keySet()){\n\t\t\t\tif(!s.getMetadata().containsKey(key)){\n\t\t\t\t\ts.getMetadata().put(key, input.getMetadata().get(key));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n}", "public class StreamFrameFetcher implements IFetcher<CVParticle>{\n\n\tprivate static final long serialVersionUID = 7135270229614102711L;\n\tprotected List<String> locations;\n\tprotected int frameSkip = 1;\n\tprivate int groupSize = 1;\n\tprotected LinkedBlockingQueue<Frame> frameQueue = new LinkedBlockingQueue<Frame>(20);\n\tprotected Map<String, StreamReader> streamReaders;\n\tprivate int sleepTime = 0;\n\tprivate String imageType;\n\tprivate int batchSize = 1;\n\tprivate List<Frame> frameGroup;\n\tprivate String id;\n\t\n\tpublic StreamFrameFetcher (List<String> locations){\n\t\tthis.locations = locations;\n\t}\n\t\n\tpublic StreamFrameFetcher frameSkip(int skip){\n\t\tthis.frameSkip = skip;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Sets the number of frames for a group\n\t * @param size\n\t * @return\n\t */\n\tpublic StreamFrameFetcher groupSize(int size){\n\t\tthis.groupSize = size;\n\t\treturn this;\n\t}\n\t\n\tpublic StreamFrameFetcher sleep(int ms){\n\t\tthis.sleepTime = ms;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Specifies the number of frames to be send at once. If set to 1 (default value) this Fetcher will emit\n\t * {@link Frame} objects. If set to 2 or more it will emit {@link GroupOfFrames} objects.\n\t * @param nrFrames\n\t * @return\n\t */\n\tpublic StreamFrameFetcher groupOfFramesOutput(int nrFrames){\n\t\tthis.batchSize = nrFrames;\n\t\treturn this;\n\t}\n\t\n\t@SuppressWarnings({ \"rawtypes\" })\n\t@Override\n\tpublic void prepare(Map conf, TopologyContext context) throws Exception {\n\t\tthis.id = context.getThisComponentId();\n\t\tint nrTasks = context.getComponentTasks(id).size();\n\t\tint taskIndex = context.getThisTaskIndex();\n\t\t\n\t\tif(conf.containsKey(StormCVConfig.STORMCV_FRAME_ENCODING)){\n\t\t\timageType = (String)conf.get(StormCVConfig.STORMCV_FRAME_ENCODING);\n\t\t}\n\t\t\n\t\t// change the list based on the number of tasks working on it\n\t\tif(this.locations != null && this.locations.size() > 0){\n\t\t\tint batchSize = (int) Math.floor(locations.size() / nrTasks);\n\t\t\tint start = batchSize * taskIndex;\n\t\t\tlocations = locations.subList(start, Math.min(start + batchSize, locations.size()));\n\t\t}\n\t}\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\t@Override\n\tpublic CVParticleSerializer getSerializer() {\n\t\tif(batchSize <= 1) return new FrameSerializer();\n\t\telse return new GroupOfFramesSerializer();\n\t}\n\n\t@Override\n\tpublic void activate() {\n\t\tif(streamReaders != null){\n\t\t\tthis.deactivate();\n\t\t}\n\t\tstreamReaders = new HashMap<String, StreamReader>();\n\t\tfor(String location : locations){\n\t\t\t\n\t\t\tString streamId = \"\"+location.hashCode();\n\t\t\tif(location.contains(\"/\")){\n\t\t\t\tstreamId = id+\"_\"+location.substring(location.lastIndexOf(\"/\")+1) + \"_\" + streamId;\n\t\t\t}\n\t\t\tStreamReader reader = new StreamReader(streamId, location, imageType, frameSkip, groupSize, sleepTime, frameQueue);\n\t\t\tstreamReaders.put(location, reader);\n\t\t\tnew Thread(reader).start();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deactivate() {\n\t\tif(streamReaders != null) for(String location : streamReaders.keySet()){\n\t\t\tstreamReaders.get(location).stop();\n\t\t}\n\t\tstreamReaders = null;\n\t}\n\n\t@Override\n\tpublic CVParticle fetchData() {\n\t\tif(streamReaders == null) this.activate();\n\t\tFrame frame = frameQueue.poll();\n\t\tif(frame != null) {\n\t\t\tif(batchSize <= 1){\n\t\t\t\treturn frame;\n\t\t\t}else{\n\t\t\t\tif(frameGroup == null || frameGroup.size() >= batchSize) frameGroup = new ArrayList<Frame>();\n\t\t\t\tframeGroup.add(frame);\n\t\t\t\tif(frameGroup.size() == batchSize){\n\t\t\t\t\treturn new GroupOfFrames(frameGroup.get(0).getStreamId(), frameGroup.get(0).getSequenceNr(), frameGroup);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}", "public class Frame extends CVParticle {\n\n\tpublic final static String NO_IMAGE = \"none\";\n\tpublic final static String JPG_IMAGE = \"jpg\";\n\tpublic final static String PNG_IMAGE = \"png\";\n\tpublic final static String GIF_IMAGE = \"gif\";\n\t\n\tprivate long timeStamp;\n\tprivate String imageType = JPG_IMAGE;\n\tprivate byte[] imageBytes;\n\tprivate BufferedImage image;\n\tprivate Rectangle boundingBox;\n\tprivate List<Feature> features = new ArrayList<Feature>();\n\t\n\tpublic Frame(String streamId, long sequenceNr, String imageType, BufferedImage image, long timeStamp, Rectangle boundingBox, List<Feature> features) throws IOException {\n\t\tthis(streamId, sequenceNr, imageType, image, timeStamp, boundingBox);\n\t\tif(features != null) this.features = features;\n\t}\n\t\n\tpublic Frame(String streamId, long sequenceNr, String imageType, BufferedImage image, long timeStamp, Rectangle boundingBox ) throws IOException {\n\t\tsuper( streamId, sequenceNr);\n\t\tthis.imageType = imageType;\n\t\tsetImage(image);\n\t\tthis.timeStamp = timeStamp;\n\t\tthis.boundingBox = boundingBox;\n\t}\n\t\n\tpublic Frame(String streamId, long sequenceNr, String imageType, byte[] image, long timeStamp, Rectangle boundingBox, List<Feature> features) {\n\t\tthis(streamId, sequenceNr, imageType, image, timeStamp, boundingBox);\n\t\tif(features != null) this.features = features;\n\t}\n\t\n\tpublic Frame(String streamId, long sequenceNr, String imageType, byte[] image, long timeStamp, Rectangle boundingBox ) {\n\t\tsuper(streamId, sequenceNr);\n\t\tthis.imageType = imageType;\n\t\tthis.imageBytes = image;\n\t\tthis.timeStamp = timeStamp;\n\t\tthis.boundingBox = boundingBox;\n\t}\n\t\n\tpublic Frame(Tuple tuple, String imageType, byte[] image, long timeStamp, Rectangle box) {\n\t\tsuper(tuple);\n\t\tthis.imageType = imageType;\n\t\tthis.imageBytes = image;\n\t\tthis.timeStamp = timeStamp;\n\t\tthis.boundingBox = box;\n\t}\n\n\tpublic Rectangle getBoundingBox() {\n\t\treturn boundingBox;\n\t}\n\n\t\n\tpublic BufferedImage getImage() throws IOException {\n\t\tif(imageBytes == null) {\n\t\t\timageType = NO_IMAGE;\n\t\t\treturn null;\n\t\t}\n\t\tif(image == null){\n\t\t\timage = ImageUtils.bytesToImage(imageBytes);\n\t\t}\n\t\treturn image;\n\t}\n\n\tpublic void setImage(BufferedImage image) throws IOException {\n\t\tthis.image = image;\n\t\tif(image != null){\n\t\t\tif(imageType.equals(NO_IMAGE)) imageType = JPG_IMAGE;\n\t\t\tthis.imageBytes = ImageUtils.imageToBytes(image, imageType);\n\t\t}else{\n\t\t\tthis.imageBytes = null;\n\t\t\tthis.imageType = NO_IMAGE;\n\t\t}\n\t}\n\t\n\tpublic void setImage(byte[] imageBytes, String imgType){\n\t\tthis.imageBytes = imageBytes;\n\t\tthis.imageType = imgType;\n\t\tthis.image = null;\n\t}\n\t\n\tpublic void removeImage(){\n\t\tthis.image = null;\n\t\tthis.imageBytes = null;\n\t\tthis.imageType = NO_IMAGE;\n\t}\n\n\n\tpublic long getTimestamp(){\n\t\treturn this.timeStamp;\n\t}\n\n\tpublic List<Feature> getFeatures() {\n\t\treturn features;\n\t}\n\n\tpublic String getImageType() {\n\t\treturn imageType;\n\t}\n\n\tpublic void setImageType(String imageType) throws IOException {\n\t\tthis.imageType = imageType;\n\t\tif(image != null){\n\t\t\timageBytes = ImageUtils.imageToBytes(image, imageType);\n\t\t}else{\n\t\t\timage = ImageUtils.bytesToImage(imageBytes);\n\t\t\timageBytes = ImageUtils.imageToBytes(image, imageType);\n\t\t}\n\t}\n\n\tpublic byte[] getImageBytes() {\n\t\treturn imageBytes;\n\t}\n\n\tpublic String toString(){\n\t\tString result= \"Frame : {streamId:\"+getStreamId()+\", sequenceNr:\"+getSequenceNr()+\", timestamp:\"+getTimestamp()+\", imageType:\"+imageType+\", features:[ \";\n\t\tfor(Feature f : features) result += f.getName()+\" = \"+f.getSparseDescriptors().size()+\", \";\n\t\treturn result + \"] }\";\n\t}\n}", "public class CVParticleSpout implements IRichSpout{\n\t\n\tprivate static final long serialVersionUID = 2828206148753936815L;\n\t\n\tprivate Logger logger = LoggerFactory.getLogger(CVParticleSpout.class);\n\tprivate Cache<Object, Object> tupleCache; // a cache holding emitted tuples so they can be replayed on failure\n\tprotected SpoutOutputCollector collector;\n\tprivate boolean faultTolerant = false;\n\tprivate IFetcher<? extends CVParticle> fetcher;\n\t\n\tpublic CVParticleSpout(IFetcher<? extends CVParticle> fetcher){\n\t\tthis.fetcher = fetcher;\n\t}\n\t\n\t/**\n\t * Indicates if this Spout must cache tuples it has emitted so they can be replayed on failure.\n\t * This setting does not effect anchoring of tuples (which is always done to support TOPOLOGY_MAX_SPOUT_PENDING configuration) \n\t * @param faultTolerant\n\t * @return\n\t */\n\tpublic CVParticleSpout setFaultTolerant(boolean faultTolerant){\n\t\tthis.faultTolerant = faultTolerant;\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Configures the spout by fetching optional parameters from the provided configuration. If faultTolerant is true the open\n\t * function will also construct the cache to hold the emitted tuples.\n\t * Configuration options are:\n\t * <ul>\n\t * <li>stormcv.faulttolerant --> boolean: indicates if the spout must operate in fault tolerant mode (i.e. replay tuples after failure)</li>\n\t * <li>stormcv.tuplecache.timeout --> long: timeout (seconds) for tuples in the cache </li>\n\t * <li>stormcv.tuplecache.maxsize --> int: maximum number of tuples in the cache (used to avoid memory overload)</li>\n\t * </ul>\n\t */\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic void open(Map conf, TopologyContext context,\tSpoutOutputCollector collector) {\n\t\tthis.collector = collector;\n\t\tif(conf.containsKey(StormCVConfig.STORMCV_SPOUT_FAULTTOLERANT)){\n\t\t\tfaultTolerant = (Boolean) conf.get(StormCVConfig.STORMCV_SPOUT_FAULTTOLERANT);\n\t\t}\n\t\tif(faultTolerant){\n\t\t\tlong timeout = conf.get(StormCVConfig.STORMCV_CACHES_TIMEOUT_SEC) == null ? 30 : (Long)conf.get(StormCVConfig.STORMCV_CACHES_TIMEOUT_SEC);\n\t\t\tint maxSize = conf.get(StormCVConfig.STORMCV_CACHES_MAX_SIZE) == null ? 500 : ((Long)conf.get(StormCVConfig.STORMCV_CACHES_MAX_SIZE)).intValue();\n\t\t\ttupleCache = CacheBuilder.newBuilder()\n\t\t\t\t\t.maximumSize(maxSize)\n\t\t\t\t\t.expireAfterAccess(timeout, TimeUnit.SECONDS)\n\t\t\t\t\t.build();\n\t\t}\n\n\t\t// pass configuration to subclasses\n\t\ttry {\n\t\t\tfetcher.prepare(conf, context);\n\t\t} catch (Exception e) {\n\t\t\tlogger.warn(\"Unable to configure spout due to \", e);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void declareOutputFields(OutputFieldsDeclarer declarer) {\n\t\tdeclarer.declare(fetcher.getSerializer().getFields());\n\t}\n\t\n\t@Override\n\tpublic void nextTuple(){\n\t\tCVParticle particle = fetcher.fetchData();\n\t\t\n\t\tif(particle != null) try {\n\t\t\tValues values = fetcher.getSerializer().toTuple(particle);\n\t\t\tString id = particle.getStreamId()+\"_\"+particle.getSequenceNr();\n\t\t\tif(faultTolerant && tupleCache != null) tupleCache.put(id, values);\n\t\t\tcollector.emit(values, id);\n\t\t} catch (IOException e) {\n\t\t\tlogger.warn(\"Unable to fetch next frame from queue due to: \"+e.getMessage());\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void close() {\n\t\tif(faultTolerant && tupleCache != null){\n\t\t\ttupleCache.cleanUp();\n\t\t}\n\t\tfetcher.deactivate();\n\t}\n\n\t@Override\n\tpublic void activate() {\n\t\tfetcher.activate();\n\t}\n\n\t@Override\n\tpublic void deactivate() {\n\t\tfetcher.deactivate();\n\t}\n\n\t@Override\n\tpublic void ack(Object msgId) {\n\t\tif(faultTolerant && tupleCache != null){\n\t\t\ttupleCache.invalidate(msgId);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void fail(Object msgId) {\n\t\tlogger.debug(\"Fail of: \"+msgId);\n\t\tif(faultTolerant && tupleCache != null && tupleCache.getIfPresent(msgId) != null){\n\t\t\tcollector.emit((Values)tupleCache.getIfPresent(msgId), msgId);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Map<String, Object> getComponentConfiguration() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\t\t\n}" ]
import java.util.ArrayList; import java.util.List; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.topology.TopologyBuilder; import backtype.storm.tuple.Fields; import backtype.storm.utils.Utils; import nl.tno.stormcv.StormCVConfig; import nl.tno.stormcv.batcher.SlidingWindowBatcher; import nl.tno.stormcv.bolt.BatchInputBolt; import nl.tno.stormcv.bolt.SingleInputBolt; import nl.tno.stormcv.example.util.GlobalContrastEnhancementOp; import nl.tno.stormcv.example.util.GlobalContrastEnhancementOp.CEAlgorithm; import nl.tno.stormcv.fetcher.StreamFrameFetcher; import nl.tno.stormcv.model.Frame; import nl.tno.stormcv.model.serializer.FrameSerializer; import nl.tno.stormcv.operation.MjpegStreamingOp; import nl.tno.stormcv.spout.CVParticleSpout;
/** * */ package nl.tno.stormcv.example; /** * @author John Schavemaker * */ public class E9_ContrastEnhancementTopology { /** * @param args */ public static void main(String[] args) { // first some global (topology configuration) StormCVConfig conf = new StormCVConfig(); /** * Sets the OpenCV library to be used which depends on the system the topology is being executed on */ //conf.put( StormCVConfig.STORMCV_OPENCV_LIB, "mac64_opencv_java248.dylib" ); conf.setNumWorkers( 4 ); // number of workers in the topology conf.setMaxSpoutPending( 32 ); // maximum un-acked/un-failed frames per spout (spout blocks if this number is reached)
conf.put( StormCVConfig.STORMCV_FRAME_ENCODING, Frame.JPG_IMAGE ); // indicates frames will be encoded as JPG throughout the topology (JPG is the default when not explicitly set)
5
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
[ "public static byte[] getBytes(byte[] buffer, int offset) {\n\tbyte[] b = new byte[buffer.length - offset];\n\tSystem.arraycopy(buffer, offset, b, 0, buffer.length - offset);\n\treturn b;\n}", "public static int getInt(byte[] buffer, int offset, int length) {\n\treturn getInt(getBytes(buffer, offset, length));\n}", "public static String getString(byte[] buffer, int offset, int length) {\n\treturn getString(getBytes(buffer, offset, length));\n}", "public static void write(byte[] data, OutputStream out) throws IOException {\n\twrite(data, data.length, out);\n}", "public static void writeInt(int data, int length, OutputStream out) throws IOException {\n\tout.write(getBytes(data, new byte[length]), 0, length);\n}", "public static void writeString(String data, int length, OutputStream out) throws IOException {\n\tbyte[] s = getBytes(data);\n\tbyte[] b = new byte[length];\n\tSystem.arraycopy(s, 0, b, 0, s.length);\n\tout.write(b, 0, length);\n}" ]
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentIndex extends MobiContent { private static final String IDENTIFIER = "INDX"; public static enum INDEX_TYPE { NORMAL(0), INFLECTION(2); private final int type; private static Map<Integer, INDEX_TYPE> map = new HashMap<Integer, INDEX_TYPE>(); static { for (INDEX_TYPE typeEnum : INDEX_TYPE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private INDEX_TYPE(final int type) { this.type = type; } public static INDEX_TYPE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int headerLength; private int indexType; private int unknown1; private int unknown2; private int idxtIndex; private int indexCount; private int indexEncoding; private int indexLanguage; private int totalIndexCount; private int ordtIndex; private int ligtIndex; private int ordtLigtEntriesCount; private int cncxRecordCount; private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find index header identifier INDX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); indexType = getInt(content, 8, 4); unknown1 = getInt(content, 12, 4); unknown2 = getInt(content, 16, 4); idxtIndex = getInt(content, 20, 4); indexCount = getInt(content, 24, 4); // entries count indexEncoding = getInt(content, 28, 4); indexLanguage = getInt(content, 32, 4); totalIndexCount = getInt(content, 36, 4); // total entries count ordtIndex = getInt(content, 40, 4); ligtIndex = getInt(content, 44, 4); ordtLigtEntriesCount = getInt(content, 48, 4); cncxRecordCount = getInt(content, 52, 4); /* 60-148: phonetizer */ unknownIndxHeaderPart = getBytes(content, 56, headerLength - 56); int ordtType = getInt(content, 164, 4); int ordtEntriesCount = getInt(content, 168, 4); int ordt1Offset = getInt(content, 172, 4); int ordt2Offset = getInt(content, 176, 4); int entrySize = ordtType == 0 ? 1 : 2; int tagxIndex = getInt(content, 180, 4); int tagxNameLength = getInt(content, 184, 4); if(tagxIndex > 0) { tagx = new MobiContentTagx(getBytes(content, tagxIndex)); List<MobiContentTagEntry> tags = tagx.getTags(); for (MobiContentTagEntry tag : tags) { int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee);
writeInt(headerLength, 4, tee);
4
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/FriendAdapter.java
[ "@Service\npublic class FriendService {\n\n private final UserRepository userRepository;\n\n @Autowired\n public FriendService(final UserRepository userRepository) {\n this.userRepository = notNull(userRepository);\n }\n\n public Set<User> friendFor(final String username) {\n return userRepository.findFriendsFor(username);\n }\n\n public boolean usersAreFriends(final String userA, final String userB) {\n notBlank(userA);\n notBlank(userB);\n return userRepository.usersAreFriends(userA, userB);\n }\n\n public void addFriend(final String username, final String friendUsername) {\n notBlank(username);\n notBlank(friendUsername);\n\n final Optional<User> user = getUser(username);\n final Optional<User> friend = getUser(friendUsername);\n\n if (user.isPresent() && friend.isPresent()) {\n userRepository.addFriend(user.get().username, friend.get().username);\n }\n }\n\n private Optional<User> getUser(final String username) {\n notBlank(username);\n return userRepository.findByUsername(username);\n }\n}", "public class Result<S, F> {\n private final S success;\n private final F failure;\n\n private Result(final S success, final F failure) {\n this.success = success;\n this.failure = failure;\n }\n\n public static <S, F> Result<S, F> success(final S success) {\n return new Result<>(success, null);\n }\n\n public static <S, F> Result<S, F> failure(final F failure) {\n return new Result<>(null, failure);\n }\n\n public boolean isSuccess() {\n return success != null;\n }\n\n public boolean isFailure() {\n return success == null;\n }\n\n public S success() {\n return Optional.ofNullable(success).orElseThrow(() -> new IllegalStateException(\"Cannot retrieve success from failure Result\"));\n }\n\n public F failure() {\n return Optional.ofNullable(failure).orElseThrow(() -> new IllegalStateException(\"Cannot retrieve failure from success Result\"));\n }\n}", "@Service\npublic class UserService {\n\n @Autowired\n private UserRepository userRepository;\n\n public Result<UserSuccess, UserFailure> registerUser(final String username, final String email, final String firstname, final String lastname, final String password) {\n notBlank(username);\n notBlank(email);\n notBlank(firstname);\n notBlank(lastname);\n notBlank(password);\n\n final NewUserCredentials credentials = new NewUserCredentials(username, email, firstname, lastname, password);\n final Optional<User> user = getUser(credentials.username);\n\n if (user.isPresent()) {\n return Result.failure(USER_ALREADY_EXISTS);\n }\n\n userRepository.addUser(credentials);\n return Result.success(USER_REGISTERD);\n }\n\n public Result<User, UserFailure> getUserWith(final String username) {\n notBlank(username);\n\n final Optional<User> user = getUser(username);\n return user.isPresent() ? Result.success(user.get()) : Result.failure(USER_DOES_NOT_EXIST);\n }\n\n public List<User> searchForUsersLike(final String query) {\n notBlank(query);\n return userRepository.findLike(query);\n }\n\n private Optional<User> getUser(final String username) {\n notBlank(username);\n return userRepository.findByUsername(username);\n }\n\n public enum UserSuccess {\n USER_REGISTERD;\n }\n\n public enum UserFailure {\n USER_DOES_NOT_EXIST,\n USER_ALREADY_EXISTS;\n }\n}", "public class Friend {\n public final String username;\n public final String firstname;\n public final String lastname;\n\n public Friend(final String username, final String firstname, final String lastname) {\n this.username = notBlank(username);\n this.firstname = notBlank(firstname);\n this.lastname = notBlank(lastname);\n }\n}", "public class AuthenticatedUser {\n public final String userName;\n\n public AuthenticatedUser(final String userName) {\n this.userName = notBlank(userName);\n }\n}", "public class User {\n public final String username;\n public final String email;\n public final String firstname;\n public final String lastname;\n\n /*\n Is there a better way than just using strings I wonder?\n */\n public User(final String username, final String email, final String firstname, final String lastname) {\n this.username = notBlank(username);\n this.email = notBlank(email);\n this.firstname = notBlank(firstname);\n this.lastname = notBlank(lastname);\n }\n\n @Override\n public boolean equals(final Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n final User user = (User) o;\n return Objects.equals(username, user.username) &&\n Objects.equals(email, user.email) &&\n Objects.equals(firstname, user.firstname) &&\n Objects.equals(lastname, user.lastname);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(username, email, firstname, lastname);\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"username='\" + username + '\\'' +\n \", email='\" + email + '\\'' +\n \", firstname='\" + firstname + '\\'' +\n \", lastname='\" + lastname + '\\'' +\n '}';\n }\n}" ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.FriendService; import se.omegapoint.facepalm.application.Result; import se.omegapoint.facepalm.application.UserService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Friend; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.User; import java.util.Set; import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.omegapoint.facepalm.client.adapters; @Adapter public class FriendAdapter { private final FriendService friendService; private final UserService userService; @Autowired public FriendAdapter(final FriendService friendService, final UserService userService) { this.friendService = notNull(friendService); this.userService = notNull(userService); }
public Set<Friend> friendsForCurrentUser() {
3
tomgibara/bits
src/test/java/com/tomgibara/bits/sample/Examples.java
[ "public abstract class AbstractBitStore implements BitStore {\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Bits.bitStoreHasher().intHashValue(this);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) return true;\n\t\tif (!(obj instanceof BitStore)) return false;\n\t\tBitStore that = (BitStore) obj;\n\t\tif (this.size() != that.size()) return false;\n\t\tif (!this.equals().store(that)) return false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Bits.toString(this);\n\t}\n\n}", "@FunctionalInterface\npublic interface BitReader extends BitStream {\n\n\t/**\n\t * Reads a single bit from a stream of bits.\n\t *\n\t * @return the value 0 or 1\n\t * @throws BitStreamException\n\t * if an exception occurs when reading the stream\n\t */\n\n\tint readBit() throws BitStreamException;\n\n\t/**\n\t * Reads a single bit from a stream of bits.\n\t *\n\t * @return whether the bit was set\n\t * @throws BitStreamException\n\t * if an exception occurs when reading the stream\n\t */\n\n\tdefault boolean readBoolean() throws BitStreamException {\n\t\treturn readBit() == 1;\n\t}\n\n\t/**\n\t * Read between 0 and 32 bits from a stream of bits. Bits are returned in\n\t * the least significant places.\n\t *\n\t * @param count\n\t * the number of bits to read\n\t * @return the read bits\n\t * @throws BitStreamException\n\t * if an exception occurs when reading the stream\n\t */\n\n\tdefault int read(int count) throws BitStreamException {\n\t\tif (count < 0) throw new IllegalArgumentException(\"negative count\");\n\t\tif (count > 32) throw new IllegalArgumentException(\"count too great\");\n\t\tif (count == 0) return 0;\n\t\tint acc = readBit();\n\t\twhile (--count > 0) {\n\t\t\tacc = acc << 1 | readBit();\n\t\t}\n\t\treturn acc;\n\t}\n\n\t/**\n\t * Read between 0 and 64 bits from a stream of bits. Bits are returned in\n\t * the least significant places.\n\t *\n\t * @param count\n\t * the number of bits to read\n\t * @return the read bits\n\t * @throws BitStreamException\n\t * if an exception occurs when reading the stream\n\t */\n\n\tdefault long readLong(int count) throws BitStreamException {\n\t\tif (count < 0) throw new IllegalArgumentException(\"negative count\");\n\t\tif (count > 64) throw new IllegalArgumentException(\"count too great\");\n\t\tif (count == 0) return 0L;\n\t\tif (count <= 32) return read(count) & 0x00000000ffffffffL;\n\t\treturn (((long)read(count - 32)) << 32) | (read(32) & 0x00000000ffffffffL);\n\t}\n\n\t/**\n\t * Read a number of bits from a stream of bits.\n\t *\n\t * @param count\n\t * the number of bits to read\n\t * @return the read bits as a big integer\n\t * @throws BitStreamException\n\t * if an exception occurs when reading the stream\n\t */\n\n\tdefault BigInteger readBigInt(int count) throws BitStreamException {\n\t\tBitStore bits = Bits.store(count);\n\t\tbits.readFrom(this);\n\t\treturn bits.toBigInteger();\n\t}\n\n\t/**\n\t * Reads as many consecutive bits as possible together with a single\n\t * terminating bit of the opposite value and returns the number of\n\t * consecutive bits read.\n\t *\n\t * This means that at least one bit is always read (the terminating bit)\n\t * unless the end of the stream has been reached in which case an\n\t * {@link EndOfBitStreamException} is raised.\n\t *\n\t * The number returned does not include the terminating bit in the count.\n\t *\n\t * @param one\n\t * whether ones should be counted instead of zeros\n\t * @return the number of consecutive bits read.\n\t * @throws BitStreamException\n\t * if an exception occurs when reading the stream\n\t */\n\n\tdefault int readUntil(boolean one) throws BitStreamException {\n\t\tint count = 0;\n\t\twhile (readBoolean() != one) count++;\n\t\treturn count;\n\t}\n\n\tdefault long skipBits(long count) throws UnsupportedOperationException, BitStreamException {\n\t\tlong position = getPosition();\n\t\tif (position != -1L) return BitStream.super.skipBits(count);\n\t\tif (count < 0L) throw new UnsupportedOperationException(\"cannot skip backwards\");\n\t\treturn BitStreams.slowForwardSkip(this, count);\n\t}\n\n}", "public interface BitStore extends Mutability<BitStore>, Comparable<BitStore> {\n\n\t// statics\n\n\t/**\n\t * A test that can be made of one {@link BitStore} against another.\n\t */\n\n\tenum Test {\n\n\t\t/**\n\t\t * Whether two {@link BitStore} have the same pattern of true/false-bits.\n\t\t */\n\n\t\tEQUALS,\n\n\t\t/**\n\t\t * Whether there is no position at which both {@link BitStore}s have\n\t\t * a true-bit.\n\t\t */\n\n\t\tEXCLUDES,\n\n\t\t/**\n\t\t * Whether one {@link BitStore} has true-bits at every position that\n\t\t * another does.\n\t\t */\n\n\t\tCONTAINS,\n\n\t\t/**\n\t\t * Whether one {@link BitStore} is has zero bits at exactly every\n\t\t * position that another has one bits.\n\t\t */\n\n\t\tCOMPLEMENTS;\n\n\t\tstatic final Test[] values = values();\n\t}\n\n\t/**\n\t * Operations that can be conducted on a {@link BitStore} using one of the\n\t * logical operations. The supported operations are {@link Operation#SET},\n\t * {@link Operation#AND}, {@link Operation#OR} and {@link Operation#XOR}.\n\t * Instances of this class are obtained via the {@link BitStore#set()},\n\t * {@link BitStore#and()}, {@link BitStore#or()}, {@link BitStore#xor()} and\n\t * {@link BitStore#op(Operation)} methods.\n\t */\n\n\tinterface Op {\n\n\t\t/**\n\t\t * The operation applied by these methods.\n\t\t *\n\t\t * @return the operation\n\t\t */\n\n\t\tOperation getOperation();\n\n\t\t/**\n\t\t * Applies the operation to every bit using the supplied bit value.\n\t\t *\n\t\t * @param value the bit value to apply\n\t\t */\n\n\t\tvoid with(boolean value);\n\n\t\t/**\n\t\t * Applies the operation to a single bit using the supplied bit value.\n\t\t *\n\t\t * @param position\n\t\t * the index of the bit to be operated on\n\t\t * @param value\n\t\t * the bit value to apply\n\t\t */\n\n\t\tvoid withBit(int position, boolean value);\n\n\t\t/**\n\t\t * Returns an existing bit before applying the supplied value using the\n\t\t * operation specified by this object.\n\t\t *\n\t\t * @param position\n\t\t * the index of the bit to be returned and then operated on\n\t\t * @param value\n\t\t * the bit value to apply\n\t\t * @return the bit value prior to the operation\n\t\t */\n\n\t\tboolean getThenWithBit(int position, boolean value);\n\n\t\t/**\n\t\t * Applies the operation to a range of 8 bits using bits of the supplied\n\t\t * byte.\n\t\t *\n\t\t * @param position\n\t\t * the smallest index in the range\n\t\t * @param value\n\t\t * the bits to apply\n\t\t */\n\n\t\tvoid withByte(int position, byte value);\n\n\t\t/**\n\t\t * Applies the operation to a range of 16 bits using bits of the\n\t\t * supplied short.\n\t\t *\n\t\t * @param position\n\t\t * the smallest index in the range\n\t\t * @param value\n\t\t * the bits to apply\n\t\t */\n\n\t\tvoid withShort(int position, short value);\n\n\t\t/**\n\t\t * Applies the operation to a range of 32 bits using bits of the\n\t\t * supplied int.\n\t\t *\n\t\t * @param position\n\t\t * the smallest index in the range\n\t\t * @param value\n\t\t * the bits to apply\n\t\t */\n\n\t\tvoid withInt(int position, int value);\n\n\t\t/**\n\t\t * Applies the operation to a range of 64 bits using bits of the\n\t\t * supplied long.\n\t\t *\n\t\t * @param position\n\t\t * the smallest index in the range\n\t\t * @param value\n\t\t * the bits to apply\n\t\t */\n\n\t\tvoid withLong(int position, long value);\n\n\t\t/**\n\t\t * Applies the operation to a range of bits using bits from the supplied\n\t\t * long. When only a subset of the long bits is required (when the\n\t\t * length is less than 64) the least-significant bits are used.\n\t\t *\n\t\t * @param position\n\t\t * the smallest index in the range\n\t\t * @param length\n\t\t * the number of bits in the range\n\t\t * @param value\n\t\t * the bits to apply\n\t\t */\n\n\t\tvoid withBits(int position, long value, int length);\n\n\t\t/**\n\t\t * Applies the operation all bits, using the bits of another\n\t\t * {@link BitStore}. The bits applied must equal\n\t\t *\n\t\t * @param store\n\t\t * a {@link BitStore} of the same size\n\t\t */\n\n\t\tvoid withStore(BitStore store);\n\n\t\t/**\n\t\t * Applies the operation to a range of bits using bits from the supplied\n\t\t * {@link BitStore}.\n\t\t *\n\t\t * @param position\n\t\t * the smallest index in the range\n\t\t * @param store\n\t\t * contains the bits to apply\n\t\t */\n\n\t\tvoid withStore(int position, BitStore store);\n\n\t\t/**\n\t\t * Applies bits sourced from a byte array. The bit ordering applied to\n\t\t * the byte array is that specified by\n\t\t * {@link Bits#asStore(byte[], int, int)}\n\t\t *\n\t\t * @param position\n\t\t * the position at which the bits will be applied\n\t\t * @param bytes\n\t\t * a byte containing the bit values to apply\n\t\t * @param offset\n\t\t * the index of the first bit from byte array to be applied\n\t\t * @param length\n\t\t * the number of bits in the range\n\t\t */\n\n\t\tvoid withBytes(int position, byte[] bytes, int offset, int length);\n\n\t\t/**\n\t\t * Opens a new writer that writes bits into the underlying\n\t\t * {@link BitStore} using operation specified by this object. Note that\n\t\t * the {@link BitWriter} will <em>write in big-endian order</em> which\n\t\t * this means that the first bit is written at the largest index,\n\t\t * working downwards to the least index.\n\t\t *\n\t\t * @param finalPos\n\t\t * the (exclusive) index at which the writer stops; less than\n\t\t * <code>initialPos</code>\n\t\t * @param initialPos\n\t\t * the (inclusive) index at which the writer starts; greater\n\t\t * than <code>finalPos</code>\n\t\t * @return a {@link BitWriter} into the store\n\t\t * @see #openWriter(int, int)\n\t\t */\n\n\t\tBitWriter openWriter(int finalPos, int initialPos);\n\n\t}\n\n\t/**\n\t * An iterator over the positions of a bit sequence in a {@link BitStore}.\n\t * This interface extends the <code>ListIterator</code> interface and\n\t * honours all of its semantics with the caveat that the\n\t * {@link #add(Object)} and {@link #remove()} methods are only honoured for\n\t * iterators over matched single-bit sequences\n\t *\n\t * @see Matches\n\t */\n\n\tinterface Positions extends ListIterator<Integer> {\n\n\t\t/**\n\t\t * Indicates whether the iterator moves over pattern sequences such that\n\t\t * successive matched ranges do not over overlap.\n\t\t *\n\t\t * @return true if position matches do not overlap, false otherwise\n\t\t */\n\n\t\tboolean isDisjoint();\n\n\t\t/**\n\t\t * <p>\n\t\t * The next matched position. This is equivalent to {@link #next()} but\n\t\t * may be expected to be slightly more efficient, with the differences\n\t\t * being that:\n\t\t *\n\t\t * <ul>\n\t\t * <li>The position is returned as a primitive is returned, not a boxed\n\t\t * primitive.\n\t\t * <li>If there's no position, the value of {@link BitStore#size()} is\n\t\t * returned instead of an exception being raised.\n\t\t * </ul>\n\t\t *\n\t\t * <p>\n\t\t * Otherwise, the effect of calling the method is the same.\n\t\t *\n\t\t * @return the next position, or the first invalid index if there is no\n\t\t * further position\n\t\t */\n\n\t\tint nextPosition();\n\n\t\t/**\n\t\t * <p>\n\t\t * The previous matched position. This is equivalent to\n\t\t * {@link #previous()} but may be expected to be slightly more\n\t\t * efficient, with the differences being that:\n\t\t *\n\t\t * <ul>\n\t\t * <li>The position is returned as a primitive is returned, not a boxed\n\t\t * primitive.\n\t\t * <li>If there's no position, the value of {@link BitStore#size()} is\n\t\t * returned instead of an exception being raised.\n\t\t * </ul>\n\t\t *\n\t\t * <p>\n\t\t * Otherwise, the effect of calling the method is the same.\n\t\t *\n\t\t * @return the previous position, or -1 if there is no further position\n\t\t */\n\n\t\tint previousPosition();\n\n\t\t/**\n\t\t * Replaces the last match returned by the {@link #next()}/\n\t\t * {@link #nextPosition()} and {@link #previous()}/\n\t\t * {@link #previousPosition()} methods, with the supplied bits.\n\t\t *\n\t\t * @param replacement\n\t\t * the bits to replace the matched sequence\n\t\t * @throws IllegalArgumentException\n\t\t * if the replacement size does not match the matched\n\t\t * sequence size\n\t\t * @throws IllegalStateException\n\t\t * if the underlying bit store is immutable, or if no call\n\t\t * to {@link #previous()} or {@link #next()} has been made\n\t\t * @see DisjointMatches#replaceAll(BitStore)\n\t\t */\n\n\t\tvoid replace(BitStore replacement);\n\n\t\t/**\n\t\t * Uniformly replaces the bits of last match returned by the\n\t\t * {@link #next()}/ {@link #nextPosition()} and {@link #previous()}/\n\t\t * {@link #previousPosition()} methods, with the specified bit value.\n\t\t *\n\t\t * @param bits\n\t\t * the bit value with which to replace the matched bits\n\t\t * @throws IllegalStateException\n\t\t * if the underlying bit store is immutable, or if no call\n\t\t * to {@link #previous()} or {@link #next()} has been made\n\t\t * @see DisjointMatches#replaceAll(boolean)\n\t\t */\n\n\t\tvoid replace(boolean bits);\n\t}\n\n\t/**\n\t * Provides information about the positions at which a fixed sequence of\n\t * bits occurs.\n\t *\n\t * @see BitStore#match(BitStore)\n\t * @see BitStore.OverlappingMatches\n\t * @see BitStore.DisjointMatches\n\t * @see BitStore.BitMatches\n\t */\n\n\tinterface Matches {\n\n\t\t/**\n\t\t * The store over which the matches are being reported.\n\t\t *\n\t\t * @return the bit store being matched over\n\t\t */\n\n\t\tBitStore store();\n\n\t\t/**\n\t\t * A {@link BitStore} containing the bit sequence being matched\n\t\t *\n\t\t * @return the bit sequence being matched\n\t\t */\n\n\t\tBitStore sequence();\n\n\t\t/**\n\t\t * Returns an {@link Matches} object that is limited to a subrange. This\n\t\t * is logically equivalent to\n\t\t * <code>store().range(from, to).matches(sequence())</code>. The store\n\t\t * reported by the returned matches reflects the specified range.\n\t\t *\n\t\t * @param from\n\t\t * the position at which the range starts\n\t\t * @param to\n\t\t * the position at which the range ends\n\t\t * @return a {@link Matches} object over the specified range.\n\t\t */\n\n\t\tMatches range(int from, int to);\n\n\t\t/**\n\t\t * The number of matches over the entire store. Depending on whether the\n\t\t * {@link Matches} is {@link OverlappingMatches} (resp.\n\t\t * {@link DisjointMatches}), overlapped sequences will (resp. will not)\n\t\t * be included in the count.\n\t\t *\n\t\t * @return the number of available matches\n\t\t */\n\n\t\tint count();\n\n\t\t/**\n\t\t * The position of the first match. If there is no match, the store size\n\t\t * is returned.\n\t\t *\n\t\t * @return the position of the first match, or the store sizes if there\n\t\t * is no match.\n\t\t */\n\n\t\tint first();\n\n\t\t/**\n\t\t * The position of the last match. If there is no match, -1 is returned.\n\t\t *\n\t\t * @return the position of the last match or -1 if there is no match.\n\t\t */\n\n\t\tint last();\n\n\t\t/**\n\t\t * The position of the first match that occurs at an index greater than\n\t\t * or equal to the specified position. If there is no match, the store\n\t\t * size is returned.\n\t\t *\n\t\t * @param position\n\t\t * position from which the next match should be found\n\t\t * @return the position of the first subsequent match, or the store\n\t\t * sizes if there is no match.\n\t\t */\n\n\t\tint next(int position);\n\n\t\t/**\n\t\t * The position of the first match that occurs at an index less than the\n\t\t * specified position. If there is no match, -1 is returned.\n\t\t *\n\t\t * @param position\n\t\t * position from which the previous match should be found\n\t\t * @return the position of the first prior match, or -1 if there is no\n\t\t * match.\n\t\t */\n\n\t\tint previous(int position);\n\n\t\t/**\n\t\t * Provides iteration over the positions at which matches occur.\n\t\t * Iteration begins at the start of the matched range. If the\n\t\t * {@link Matches} is {@link OverlappingMatches} (resp.\n\t\t * {@link DisjointMatches}) the matches included in this iteration may\n\t\t * (resp. may not) overlap.\n\t\t *\n\t\t * @return the match positions\n\t\t */\n\n\t\tPositions positions();\n\n\t\t/**\n\t\t * Provides iteration over the positions at which matches occur.\n\t\t * Iteration begins at the specified position. If the {@link Matches} is\n\t\t * {@link OverlappingMatches} (resp. {@link DisjointMatches}) the\n\t\t * matches included in this iteration may (resp. may not) overlap.\n\t\t *\n\t\t * @param position\n\t\t * the position at which iteration begins\n\t\t * @return the match positions\n\t\t */\n\n\t\tPositions positions(int position);\n\n\t}\n\n\t/**\n\t * Matches a fixed bit sequences within a {@link BitStore} including\n\t * overlapping subsequences. For example, the overlapped count of the\n\t * sequence \"101\" over \"10101\" would be 2 with matches at indices 0 and 2.\n\t */\n\n\tinterface OverlappingMatches extends Matches {\n\n\t\t/**\n\t\t * Disjoint matches of the same bit sequence over the same\n\t\t * {@link BitStore}.\n\t\t *\n\t\t * @return disjoint matches\n\t\t */\n\n\t\tDisjointMatches disjoint();\n\n\t\t@Override\n\t\tOverlappingMatches range(int from, int to);\n\n\t}\n\n\t/**\n\t * Matches a fixed bit sequences within a {@link BitStore} including\n\t * overlapping subsequences. For example, the disjoint count of the\n\t * sequence \"101\" over \"10101\" would be 1, the single match at index 0.\n\t */\n\n\tinterface DisjointMatches extends Matches {\n\n\t\t/**\n\t\t * Overlapping matches of the same bit sequence over the same\n\t\t * {@link BitStore}.\n\t\t *\n\t\t * @return overlapping matches\n\t\t */\n\n\t\tOverlappingMatches overlapping();\n\n\t\t@Override\n\t\tDisjointMatches range(int from, int to);\n\n\t\t/**\n\t\t * Whether every bit in the {@link BitStore} is accommodated within a\n\t\t * match of the bit sequence.\n\t\t *\n\t\t * @return whether the matches cover every bit in the {@link BitStore}\n\t\t */\n\n\t\tboolean isAll();\n\n\t\t/**\n\t\t * Whether there are no matched bits.\n\t\t *\n\t\t * @return whether there are no matches over the {@link BitStore}\n\t\t */\n\n\t\tboolean isNone();\n\n\t\t/**\n\t\t * Replaces all non-overlapping matches of the sequence with a new\n\t\t * sequence of the same size.\n\t\t *\n\t\t * @param replacement\n\t\t * a replacement bit sequence\n\t\t * @throws IllegalArgumentException\n\t\t * if the replacement size does not match the sequence size.\n\t\t * @throws IllegalStateException\n\t\t * if the underlying store is immutable\n\t\t */\n\n\t\tvoid replaceAll(BitStore replacement);\n\n\t\t/**\n\t\t * Replaces all the bits of every non-overlapping match with the\n\t\t * specified bit.\n\t\t *\n\t\t * @param bits\n\t\t * the replacement for matched bits\n\t\t * @throws IllegalStateException\n\t\t * if the underlying store is immutable\n\t\t */\n\n\t\tvoid replaceAll(boolean bits);\n\n\t}\n\n\t/**\n\t * Provides information about the positions of 1s or 0s in a\n\t * {@link BitStore}.\n\t */\n\n\tinterface BitMatches extends OverlappingMatches, DisjointMatches {\n\n\t\t@Override\n\t\tBitMatches overlapping();\n\n\t\t@Override\n\t\tBitMatches disjoint();\n\n\t\t@Override\n\t\tBitMatches range(int from, int to);\n\n\t\t/**\n\t\t * Whether the {@link BitStore} consists entirely\n\t\t * of the matched bit value.\n\t\t *\n\t\t * @return true if and only if all bits in the store have the value of\n\t\t * {@link #bit()}\n\t\t */\n\n\t\t@Override\n\t\tboolean isAll();\n\n\t\t/**\n\t\t * Whether none of the bits in the {@link BitStore} have the matched bit\n\t\t * value.\n\t\t *\n\t\t * @return true if and only if none of the bits in the store have the\n\t\t * value of {@link #bit()}\n\t\t */\n\n\t\t@Override\n\t\tboolean isNone();\n\n\t\t/**\n\t\t * Whether 1s are being matched.\n\t\t *\n\t\t * @return bit value being matched\n\t\t */\n\n\t\tboolean bit();\n\n\t\t/**\n\t\t * The matched bit positions as a sorted set. The returned set is a live\n\t\t * view over the {@link BitStore} with mutations of the store being\n\t\t * reflected in the set and vice versa. Attempting to add integers to\n\t\t * the set that lie outside the range of valid bit indexes in the store\n\t\t * will fail.\n\t\t *\n\t\t * @return a set view of the matched bit positions\n\t\t */\n\n\t\tSortedSet<Integer> asSet();\n\n\t}\n\n\t/**\n\t * Performs tests of a fixed type against a {@link BitStore}; in this\n\t * documentation, referred to as the <em>source</em>. To perform tests\n\t * against a subrange of the source use the {@link BitStore#range(int, int)}\n\t * method.\n\t *\n\t * @see Test\n\t * @see BitStore#range(int, int)\n\t */\n\n\tinterface Tests {\n\n\t\t/**\n\t\t * The type of tests performed by this object.\n\t\t *\n\t\t * @return the type of test\n\t\t */\n\n\t\tTest getTest();\n\n\t\t/**\n\t\t * Tests a {@link BitStore} against the source.\n\t\t *\n\t\t * @param store\n\t\t * the bits tested against\n\t\t * @return whether the test succeeds\n\t\t * @throws IllegalArgumentException\n\t\t * if the store size does not match the size of the source\n\t\t */\n\n\t\tboolean store(BitStore store);\n\n\t\t/**\n\t\t * Tests the bits of a long against the source {@link BitStore}. In\n\t\t * cases where the size of the source is less than the full 64 bits of\n\t\t * the long, the least-significant bits are used.\n\t\t *\n\t\t * @param bits\n\t\t * the bits tested against\n\t\t * @return whether the test succeeds\n\t\t * @throws IllegalArgumentException\n\t\t * if the size of the source exceeds 64 bits.\n\t\t */\n\n\t\tboolean bits(long bits);\n\n\t}\n\n\t/**\n\t * Permutes the bits of a {@link BitStore}.\n\t */\n\n\tinterface Permutes extends Transposable {\n\n\t\t/**\n\t\t * <p>\n\t\t * Rotates the bits in a {@link BitStore}. The distance is added to the\n\t\t * index of a bit to give its new index. Bits whose indices would lie\n\t\t * outside the range of the {@link BitStore} are mapped on to lower\n\t\t * values modulo the size of the store.\n\t\t *\n\t\t * <p>\n\t\t * Informally, positive distances correspond to a left rotation, and\n\t\t * negative distances correspond to right rotation. Rotation through any\n\t\t * distance which is a multiple of the store's size (including zero,\n\t\t * naturally) leaves the bits of the {@link BitStore} unchanged.\n\t\t *\n\t\t * @param distance\n\t\t * the distance in bits through which the bit values are\n\t\t * rotated\n\t\t */\n\n\t\tvoid rotate(int distance);\n\n\t\t/**\n\t\t * Reverses the bits in the {@link BitStore}.\n\t\t */\n\n\t\tvoid reverse();\n\n\t\t/**\n\t\t * <p>\n\t\t * Randomly shuffles the bits in the store.\n\t\t *\n\t\t * <p>\n\t\t * <b>Note</b>: callers cannot assume that calling this method with the\n\t\t * same randomization will always yield the same permutation. For\n\t\t * greater control over permutations (of all natures) see\n\t\t * <code>com.tomgibara.permute.Permute</code>\n\t\t *\n\t\t * @param random\n\t\t * a source of randomness\n\t\t */\n\n\t\tvoid shuffle(Random random);\n\t}\n\n\t// fundamental methods\n\n\t/**\n\t * <p>\n\t * The size of the {@link BitStore} in bits.\n\t *\n\t * <p>This is a <b>fundamental method</b>.\n\t *\n\t * @return the size of the store, possibly zero, never negative\n\t */\n\n\tint size();\n\n\t/**\n\t * <p>\n\t * Gets the value of a single bit in the {@link BitStore}.\n\t *\n\t * <p>This is a <b>fundamental method</b>.\n\t *\n\t * @param index\n\t * the index of the bit value to be returned\n\t * @return whether the bit at the specified index is a one\n\t */\n\n\tboolean getBit(int index);\n\n\t// fundamental mutation methods\n\n\t/**\n\t * <p>\n\t * Sets the value of a bit in the {@link BitStore}.\n\t *\n\t * <p>\n\t * This is a <b>fundamental mutation method</b>.\n\t *\n\t * @param index\n\t * the index of the bit to be set\n\t * @param value\n\t * the value to be assigned to the bit\n\t */\n\n\tdefault void setBit(int index, boolean value) {\n\t\tthrow new IllegalStateException(\"immutable\");\n\t}\n\n\t// accelerating methods\n\n\t/**\n\t * <p>\n\t * Returns up to 64 bits of the {@link BitStore} starting from a specified\n\t * position, packed in a long. The position specifies the index of the least\n\t * significant bit.\n\t * \n\t * <p>\n\t * The bits will be returned in the least significant places. Any unused\n\t * bits in the long will be zero.\n\t *\n\t * <p>\n\t * This is an <b>acceleration method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit returned\n\t * @param length\n\t * the number of bits to be returned, from 0 to 64 inclusive\n\t * @return a long containing the specified bits\n\t * @see #getBitsAsInt(int, int)\n\t * @see #getByte(int)\n\t * @see #getShort(int)\n\t * @see #getInt(int)\n\t * @see #getLong(int)\n\t */\n\n\tdefault long getBits(int position, int length) {\n\t\tBits.checkBitsLength(length);\n\t\tlong bits = 0L;\n\t\tfor (int i = position + length - 1; i >= position; i--) {\n\t\t\tbits <<= 1;\n\t\t\tif (getBit(i)) bits |= 1L;\n\t\t}\n\t\treturn bits;\n\t}\n\n\t/**\n\t * <p>\n\t * Returns up to 32 bits of the {@link BitStore} starting from a specified\n\t * position, packed in an int. The position specifies the index of the least\n\t * significant bit.\n\t *\n\t * <p>\n\t * The bits will be returned in the least significant places. Any unused\n\t * bits in the long will be zero.\n\t *\n\t * <p>\n\t * This is an <b>acceleration method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit returned\n\t * @param length\n\t * the number of bits to be returned, from 0 to 32 inclusive\n\t * @return an int containing the specified bits\n\t * @see #getBits(int, int)\n\t * @see #getByte(int)\n\t * @see #getShort(int)\n\t * @see #getInt(int)\n\t * @see #getLong(int)\n\t */\n\n\tdefault int getBitsAsInt(int position, int length) {\n\t\tBits.checkIntBitsLength(length);\n\t\tint bits = 0;\n\t\tfor (int i = position + length - 1; i >= position; i--) {\n\t\t\tbits <<= 1;\n\t\t\tif (getBit(i)) bits |= 1L;\n\t\t}\n\t\treturn bits;\n\t}\n\n\t// accelerating mutation methods\n\n\t/**\n\t * <p>\n\t * Flips the bit at a specified index. If the bit has a value of\n\t * <code>1</code> prior to the call, its value is set to <code>o</code>. If\n\t * the bit has a value of <code>0</code> prior to the call, its value is set\n\t * to <code>1</code>.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t *\n\t * @param index\n\t * the bit to be flipped\n\t */\n\n\tdefault void flipBit(int index) {\n\t\tsetBit(index, !getBit(index));\n\t}\n\n\t/**\n\t * <p>\n\t * Sets the value of a bit and returns its value prior to any modification.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t *\n\t * @param index\n\t * the index of the bit to be modified\n\t * @param value\n\t * the value to be assigned to the bit\n\t * @return the value of the bit before assignment\n\t */\n\n\tdefault boolean getThenSetBit(int index, boolean value) {\n\t\tboolean previous = getBit(index);\n\t\tif (previous != value) setBit(index, value);\n\t\treturn previous;\n\t}\n\n\t/**\n\t * <p>\n\t * Sets up to 64 bits of the {@link BitStore}, starting at a specified\n\t * position, with bits packed in a long. The position specifies the index of\n\t * the least significant bit.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit assigned to\n\t * @param value\n\t * the values to be assigned to the bits\n\t * @param length\n\t * the number of bits to be modified\n\t * @see #setBitsAsInt(int, int, int)\n\t */\n\n\tdefault void setBits(int position, long value, int length) {\n\t\tBits.checkBitsLength(length);\n\t\tint to = position + length;\n\t\tif (to > size()) throw new IllegalArgumentException(\"length too great\");\n\t\tfor (int i = position; i < to; i++, value >>= 1) {\n\t\t\tsetBit(i, (value & 1) != 0);\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Sets up to 32 bits of the {@link BitStore}, starting at a specified\n\t * position, with bits packed in an int. The position specifies the index of\n\t * the least significant bit.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit assigned to\n\t * @param value\n\t * the values to be assigned to the bits\n\t * @param length\n\t * the number of bits to be modified\n\t * @see #setBits(int, long, int)\n\t */\n\n\tdefault void setBitsAsInt(int position, int value, int length) {\n\t\tBits.checkIntBitsLength(length);\n\t\tint to = position + length;\n\t\tif (to > size()) throw new IllegalArgumentException(\"length too great\");\n\t\tfor (int i = position; i < to; i++, value >>= 1) {\n\t\t\tsetBit(i, (value & 1) != 0);\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Sets a range of bits in this {@link BitStore} with the bits in another.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t *\n\t * @param position\n\t * the position to which the bits will be copied\n\t * @param store\n\t * the source of the bits to be copied\n\t */\n\n\tdefault void setStore(int position, BitStore store) {\n\t\tif (store == null) throw new IllegalArgumentException(\"null store\");\n\t\tint to = position + store.size();\n\t\tif (to > size()) throw new IllegalArgumentException(\"store size too great\");\n\t\tfor (int i = position; i < to; i++) {\n\t\t\tsetBit(i, store.getBit(i - position));\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Sets every bit in the {@link BitStore}, assigning each bit a value of\n\t * <code>1</code>.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t */\n\n\tdefault void fill() {\n\t\tint size = size();\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tsetBit(i, true);\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Clears every bit in the {@link BitStore}, assigning each bit a value of\n\t * <code>0</code>.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t */\n\n\tdefault void clear() {\n\t\tint size = size();\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tsetBit(i, false);\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Flips every bit in the {@link BitStore}. Every <code>1</code> bit is\n\t * assigned a value of <code>0</code> and every <code>0</code> bit is\n\t * assigned a value of <code>1</code>.\n\t *\n\t * <p>\n\t * This is an <b>accelerating mutation method</b>.\n\t *\n\t * @see #flipBit(int)\n\t */\n\n\tdefault void flip() {\n\t\tint size = size();\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tflipBit(i);\n\t\t}\n\t}\n\n\t// operations\n\n\t/**\n\t * <p>\n\t * An {@link Op} that uses {@link Operation#SET} to 'set' bits on the\n\t * {@link BitStore}. This is equivalent to <code>op(Operation.SET)</code>.\n\t *\n\t * <p>\n\t * This is an <b>operations method</b>.\n\t *\n\t * @return an object for <code>set</code>ting bit values on the\n\t * {@link BitStore}\n\t * @see #op(Operation)\n\t */\n\n\tdefault Op set() {\n\t\treturn new BitStoreOp.Set(this);\n\t}\n\n\t/**\n\t * An {@link Op} that uses {@link Operation#AND} to 'and' bits on the\n\t * {@link BitStore}. This is equivalent to <code>op(Operation.AND)</code>.\n\t *\n\t * <p>\n\t * This is an <b>operations method</b>.\n\t *\n\t * @return an object for <code>and</code>ing bit values on the\n\t * {@link BitStore}\n\t * @see #op(Operation)\n\t */\n\n\tdefault Op and() {\n\t\treturn new BitStoreOp.And(this);\n\t}\n\n\t/**\n\t * <p>\n\t * An {@link Op} that uses {@link Operation#OR} to 'or' bits on the\n\t * {@link BitStore}. This is equivalent to <code>op(Operation.OR)</code>.\n\t *\n\t * <p>\n\t * This is an <b>operations method</b>.\n\t *\n\t * @return an object for <code>or</code>ing bit values on the\n\t * {@link BitStore}\n\t * @see #op(Operation)\n\t */\n\n\tdefault Op or() {\n\t\treturn new BitStoreOp.Or(this);\n\t}\n\n\t/**\n\t * <p>\n\t * An {@link Op} that uses {@link Operation#OR} to 'xor' bits on the\n\t * {@link BitStore}. This is equivalent to <code>op(Operation.XOR)</code>.\n\t *\n\t * <p>\n\t * This is an <b>operations method</b>.\n\t *\n\t * @return an object for <code>xor</code>ing bit values on the\n\t * {@link BitStore}\n\t * @see #op(Operation)\n\t */\n\n\tdefault Op xor() {\n\t\treturn new BitStoreOp.Xor(this);\n\t}\n\n\t// shifting\n\n\t/**\n\t * <p>\n\t * Translates the bits of the {@link BitStore} a fixed distance left or\n\t * right. Vacated bits are filled with the specified value. A positive\n\t * distance corresponds to moving bits left (from lower indices to higher\n\t * indices). A negative distance corresponds to moving bits right (from\n\t * higher indices to lower indices). Calling the method with a distance of\n\t * zero has no effect.\n\t *\n\t * <p>\n\t * This is an <b>shifting method</b>.\n\t *\n\t * @param distance\n\t * the number of indices through which the bits should be\n\t * translated.\n\t * @param fill\n\t * the value that should be assigned to the bits at indices\n\t * unpopulated by the shift\n\t */\n\n\tdefault void shift(int distance, boolean fill) {\n\t\tint size = size();\n\t\tif (size == 0) return;\n\t\tif (distance == 0) return;\n\n\t\t//TODO have separate methods for true/false fill?\n\t\t//TODO this capable of optimization in some cases\n\t\tif (distance > 0) {\n\t\t\tint j = size - 1;\n\t\t\tfor (int i = j - distance; i >= 0; i--, j--) {\n\t\t\t\tsetBit(j, getBit(i));\n\t\t\t}\n\t\t\trange(0, j + 1).setAll(fill);\n\t\t} else {\n\t\t\tint j = 0;\n\t\t\tfor (int i = j - distance; i < size; i++, j++) {\n\t\t\t\tsetBit(j, getBit(i));\n\t\t\t}\n\t\t\trange(j, size).setAll(fill);\n\t\t}\n\t}\n\n\t// matching\n\n\t/**\n\t * <p>\n\t * Returns an object can match the supplied bit sequence against the\n\t * {@link BitStore}.\n\t *\n\t * <p>\n\t * This is a <b>matches method</b>.\n\t *\n\t * @param sequence\n\t * the bit sequence to be matched\n\t * @return the matches of the specified sequence\n\t * @see OverlappingMatches#disjoint()\n\t */\n\n\tdefault OverlappingMatches match(BitStore sequence) {\n\t\tif (sequence == null) throw new IllegalArgumentException(\"null sequence\");\n\t\tif (sequence.size() == 1) return match(sequence.getBit(0));\n\t\treturn new BitStoreOverlappingMatches(this, sequence);\n\t}\n\n\t/**\n\t * <p>\n\t * Returns an object that identifies the positions of each <code>1</code>\n\t * bit in the {@link BitStore}.\n\t *\n\t * <p>\n\t * This is a <b>matches method</b>.\n\t *\n\t * @return the locations of all <code>1</code> bits\n\t * @see #match(boolean)\n\t */\n\n\tdefault BitMatches ones() {\n\t\treturn new BitStoreBitMatches.Ones(this);\n\t}\n\n\t/**\n\t * <p>\n\t * Returns an object that identifies the positions of each <code>0</code>\n\t * bit in the {@link BitStore}.\n\t *\n\t * <p>\n\t * This is a <b>matches method</b>.\n\t *\n\t * @return the locations of all <code>0</code> bits\n\t * @see #match(boolean)\n\t */\n\n\tdefault BitMatches zeros() {\n\t\treturn new BitStoreBitMatches.Zeros(this);\n\t}\n\n\t// testing\n\n\t/**\n\t * <p>\n\t * Tests for equality.\n\t *\n\t * <p>\n\t * This is a <b>tests method</b>.\n\t *\n\t * @return tests for equality\n\t *\n\t * @see Test#EQUALS\n\t * @see #test(Test)\n\t */\n\n\tdefault Tests equals() {\n\t\treturn new BitStoreTests.Equals(this);\n\t}\n\n\t/**\n\t * <p>\n\t * Tests for exclusion.\n\t *\n\t * <p>\n\t * This is a <b>tests method</b>.\n\t *\n\t * @return tests for exclusion\n\t *\n\t * @see Test#EXCLUDES\n\t * @see #test(Test)\n\t */\n\n\tdefault Tests excludes() {\n\t\treturn new BitStoreTests.Excludes(this);\n\t}\n\n\t/**\n\t * <p>\n\t * Tests for containment.\n\t *\n\t * <p>\n\t * This is a <b>tests method</b>.\n\t *\n\t * @return tests for containment\n\t *\n\t * @see Test#CONTAINS\n\t * @see #test(Test)\n\t */\n\n\tdefault Tests contains() {\n\t\treturn new BitStoreTests.Contains(this);\n\t}\n\n\t/**\n\t * <p>\n\t * Tests for complement.\n\t *\n\t * <p>\n\t * This is a <b>tests method</b>.\n\t *\n\t * @return tests for complement\n\t *\n\t * @see Test#COMPLEMENTS\n\t * @see #test(Test)\n\t */\n\n\tdefault Tests complements() {\n\t\treturn new BitStoreTests.Complements(this);\n\t}\n\n\t// I/O\n\n\t/**\n\t * <p>\n\t * Opens a {@link BitWriter} that writes bits into the {@link BitStore}. The\n\t * bit writer writes 'backwards' from the initial position, with the first\n\t * bit written having an index of <code>initialPos - 1</code>. The last bit\n\t * is written to <code>finalPos</code>. In other words, the writer writes to\n\t * the range <code>[finalPos, initialPos)</code> in big-endian order. If the\n\t * positions are equal, no bits are written.\n\t *\n\t * <p>\n\t * This is an <b>I/O method</b>.\n\t *\n\t * @param finalPos\n\t * the index at which the writer terminates, equ. the start of\n\t * the range to which bits are written\n\t * @param initialPos\n\t * the position beyond the index at which the writer begins, equ.\n\t * the end of the range to which bits are written\n\t * @return a writer over the range\n\t * @see Op#openWriter(int, int)\n\t */\n\n\tdefault BitWriter openWriter(int finalPos, int initialPos) {\n\t\treturn Bits.newBitWriter(this, finalPos, initialPos);\n\t}\n\n\t/**\n\t * <p>\n\t * Opens a {@link BitReader} that reads bits from the {@link BitStore}. The\n\t * bit reader reads 'backwards' from the initial position, with the first\n\t * bit read having an index of <code>initialPos - 1</code>. The last bit is\n\t * read from <code>finalPos</code>. In other words, the reader reads from\n\t * the range <code>[finalPos, initialPos)</code> in big-endian order. If the\n\t * positions are equal, no bits are read.\n\t *\n\t * <p>\n\t * This is an <b>I/O method</b>.\n\t *\n\t * @param finalPos\n\t * the index at which the reader terminates, equ. the start of\n\t * the range from which bits are read\n\t * @param initialPos\n\t * the position beyond the index at which the reader begins, equ.\n\t * the end of the range from which bits are read\n\t * @return a reader over the range\n\t */\n\n\tdefault BitReader openReader(int finalPos, int initialPos) {\n\t\treturn Bits.newBitReader(this, finalPos, initialPos);\n\t}\n\n\t/**\n\t * <p>\n\t * Writes the bits in the {@link BitStore} to the supplied writer, in\n\t * big-endian order. The bit at <code>size() - 1</code> is the first bit\n\t * written. The bit at <code>0</code> is the last bit written.\n\t *\n\t * <p>\n\t * This is an <b>I/O method</b>.\n\t *\n\t * @param writer\n\t * the writer to which the bits should be written\n\t * @return the number of bits written\n\t */\n\n\tdefault int writeTo(BitWriter writer) {\n\t\tint size = size();\n\t\tBits.transfer(openReader(), writer, size);\n\t\treturn size;\n\t}\n\n\t/**\n\t * <p>\n\t * Reads bits from the supplied reader into the {@link BitStore}, in\n\t * big-endian order. The bit at <code>size() - 1</code> is the first bit\n\t * written to. The bit at <code>0</code> is the last bit written to.\n\t *\n\t * <p>\n\t * This is an <b>I/O method</b>.\n\t *\n\t * @param reader\n\t * the reader from which the bits are read\n\t */\n\n\tdefault void readFrom(BitReader reader) {\n\t\tBits.transfer(reader, openWriter(), size());\n\t}\n\n\t/**\n\t * <p>\n\t * Writes the bits in the {@link BitStore} as bytes to the supplied writer,\n\t * in big-endian order. If the size of the bit store is not a multiple of 8\n\t * (ie. does not span a whole number of bytes), then the first byte written\n\t * is padded with zeros in its most significant bits.\n\t *\n\t * <p>\n\t * This is an <b>I/O method</b>.\n\t *\n\t * @param writer\n\t * the writer to which the bits will be written\n\t */\n\n\tdefault void writeTo(WriteStream writer) {\n\t\tif (writer == null) throw new IllegalArgumentException(\"null writer\");\n\t\tint start = size();\n\t\tint head = start & 7;\n\t\tif (head != 0) {\n\t\t\tbyte value = (byte) getBits(start - head, head);\n\t\t\twriter.writeByte(value);\n\t\t\tstart -= head;\n\t\t}\n\t\tfor (start -=8; start >= 0; start -= 8) {\n\t\t\twriter.writeByte(getByte(start));\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Populates the {@link BitStore} with bytes read from the supplied reader.\n\t * If the size of the bit store is not a multiple of 8 (ie. does not span a\n\t * whole number of bytes), then a number of the most-significant bits of the\n\t * first byte are skipped so that exactly {@link #size()} bits are written\n\t * to the {@link BitStore}.\n\t *\n\t * <p>\n\t * This is an <b>I/O method</b>.\n\t *\n\t * @param reader\n\t * the reader from which the bits are read\n\t */\n\n\tdefault void readFrom(ReadStream reader) {\n\t\tif (reader == null) throw new IllegalArgumentException(\"null reader\");\n\t\tBitWriter writer = openWriter();\n\t\tint start = size();\n\t\tint head = start & 7;\n\t\tif (head != 0) {\n\t\t\twriter.write(reader.readByte(), head);\n\t\t}\n\t\tfor (int i = (start >> 3) - 1; i >= 0; i--) {\n\t\t\twriter.write(reader.readByte(), 8);\n\t\t}\n\t}\n\n\t// views\n\n\t/**\n\t * <p>\n\t * A sub-range of this {@link BitStore}. The returned store is a view over\n\t * this store, changes in either are reflected in the other. If this store\n\t * is immutable, so too is the returned store.\n\t *\n\t * <p>\n\t * The returned store as a size of <code>to - from</code> and\n\t * has its own indexing, starting at zero (which maps to index\n\t * <code>from</code> in this store).\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @param from\n\t * the start of the range (inclusive)\n\t * @param to\n\t * the end of the range (exclusive)\n\t * @return a sub range of the {@link BitStore}\n\t * @see #rangeFrom(int)\n\t * @see #rangeTo(int)\n\t */\n\n\tdefault BitStore range(int from, int to) {\n\t\treturn Bits.newRangedView(this, from, to);\n\t}\n\n\t/**\n\t * <p>\n\t * A view of this {@link BitStore} in which each bit is flipped. The\n\t * returned store is a view over this store, changes in either are reflected\n\t * in the other. If this store is immutable, so too is the returned store.\n\t *\n\t * <p>\n\t * The returned store has the same size as this store.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @return a store in which each bit value is flipped from its value in this\n\t * store\n\t * @see #flip()\n\t */\n\n\tdefault BitStore flipped() {\n\t\treturn new FlippedBitStore(this);\n\t}\n\n\t/**\n\t * <p>\n\t * A view of this {@link BitStore} in which the bit indices are reversed.\n\t * The returned store is a view over this store, changes in either are\n\t * reflected in the other. If this store is immutable, so too is the\n\t * returned store.\n\t *\n\t * <p>\n\t * The returned store has the same size as this store with the bit at index\n\t * <code>i</code> drawing its value from the bit at index\n\t * <code>size - i - 1</code> from this store.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @return a store in which each bit is reversed\n\t * @see #flip()\n\t */\n\n\tdefault BitStore reversed() {\n\t\treturn new ReversedBitStore(this);\n\t}\n\n\t/**\n\t * <p>\n\t * A permutable view of this {@link BitStore} that allows the bits of this\n\t * store to be permuted.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @return a permutable view\n\t */\n\n\tdefault Permutes permute() {\n\t\treturn new BitStorePermutes(this);\n\t}\n\n\t/**\n\t * <p>\n\t * Copies the {@link BitStore} to a byte array. The most significant bits\n\t * of the {@link BitStore} are written to the first byte in the array that\n\t * is padded with zeros for each unused bit.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @return the bits of the bit store in a byte array\n\t */\n\n\tdefault byte[] toByteArray() {\n\t\tStreamBytes bytes = Streams.bytes((size() + 7) >> 3);\n\t\twriteTo(bytes.writeStream());\n\t\treturn bytes.directBytes();\n\t}\n\n\t/**\n\t * <p>\n\t * Copies the {@link BitStore} into a <code>BigInteger</code>. The returned\n\t * <code>BigInteger</code> is the least positive integer such that\n\t * <code>bigint.testBit(i) == store.getBit(i)</code>.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @return the value of the {@link BitStore} as a big integer\n\t * @see Bits#asStore(BigInteger)\n\t */\n\n\tdefault BigInteger toBigInteger() {\n\t\treturn size() == 0 ? BigInteger.ZERO : new BigInteger(1, toByteArray());\n\t}\n\n\t/**\n\t * <p>\n\t * Returns the string representation of the {@link BitStore} in the given\n\t * radix. The radix must be in the range <code>Character.MIN_RADIX</code>\n\t * and <code>Character.MAX_RADIX</code> inclusive. The value is always\n\t * positive.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @param radix\n\t * a valid radix\n\t * @return the {@link BitStore} as a string in the specified radix\n\t * @throws IllegalArgumentException\n\t * if the radix is invalid\n\t */\n\n\tdefault String toString(int radix) {\n\t\tif (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) throw new IllegalArgumentException(\"invalid radix\");\n\t\treturn toBigInteger().toString(radix);\n\t}\n\n\t/**\n\t * <p>\n\t * Copies the {@link BitStore} into a <code>BitSet</code>.\n\t *\n\t * <p>\n\t * This is an <b>view method</b>.\n\t *\n\t * @return the {@link BitStore} as a <code>BitSet</code>\n\t */\n\n\tdefault BitSet toBitSet() {\n\t\tBitMatches ones = ones();\n\t\tint previous = ones.last();\n\t\tfinal BitSet bitSet = new BitSet(previous + 1);\n\t\twhile (previous > -1) {\n\t\t\tbitSet.set(previous);\n\t\t\tprevious = ones.previous(previous);\n\t\t}\n\t\treturn bitSet;\n\t}\n\n\t/**\n\t * <p>\n\t * A view of this {@link BitStore} as a <code>Number</code>. The returned\n\t * number is a view over this store so changes in the {@link BitStore}\n\t * are reflected in the numeric view.\n\t *\n\t * <p>\n\t * This is a <b>view method</b>.\n\t *\n\t * @return the {@link BitStore} as a <code>Number</code>.\n\t */\n\n\tdefault Number asNumber() {\n\t\treturn Bits.asNumber(this);\n\t}\n\n\t/**\n\t * <p>\n\t * A view of this {@link BitStore} as a <code>List</code> of boolean values.\n\t * The returned list is a view over this store, changes in either are\n\t * reflected in the other. If this store is immutable, the returned list is\n\t * unmodifiable.\n\t *\n\t * <p>\n\t * The size of the returned list matches the size of the {@link BitStore}.\n\t * The list supports mutation if the the store is mutable, but does not\n\t * support operations which would modify the length of the list (and\n\t * therefore the store) such as <code>add</code> and <code>remove</code>.\n\t *\n\t * <p>\n\t * This is an <b>view method</b>.\n\t *\n\t * @return the {@link BitStore} as a list\n\t */\n\n\tdefault List<Boolean> asList() {\n\t\treturn new BitStoreList(this);\n\t}\n\n\t// mutability methods\n\n\t@Override\n\tdefault boolean isMutable() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tdefault BitStore mutableCopy() {\n\t\treturn BitVector.fromStore(this);\n\t}\n\n\t@Override\n\tdefault BitStore immutableCopy() {\n\t\treturn mutableCopy().immutableView();\n\t}\n\n\t@Override\n\tdefault BitStore immutableView() {\n\t\treturn new ImmutableBitStore(this);\n\t}\n\n\t// comparable methods\n\n\t/**\n\t * <p>\n\t * Compares the {@link BitStore} numerically to another {@link BitStore}. A\n\t * numerical comparison treats the stores as positive binary integers and\n\t * compares them using the natural ordering of the integers.\n\t *\n\t * <p>\n\t * This is a <b>comparable method</b>.\n\t *\n\t * @param that\n\t * the store being compared against.\n\t * @return zero if the stores are equal, a negative value if this store is\n\t * less than the given store, a positive value otherwise.\n\t * @see #compareTo(BitStore)\n\t * @see Bits#compareNumeric(BitStore, BitStore)\n\t * @see #compareLexicallyTo(BitStore)\n\t */\n\n\tdefault int compareNumericallyTo(BitStore that) {\n\t\tif (this == that) return 0; // cheap check\n\t\tif (that == null) throw new IllegalArgumentException(\"that\");\n\t\treturn Bits.compareNumeric(this, that);\n\t}\n\n\t/**\n\t * <p>\n\t * Compares the {@link BitStore} lexically to another {@link BitStore}. A\n\t * lexical comparison treats the stores as binary strings and compares them\n\t * using the conventional ordering of Java strings.\n\t *\n\t * <p>\n\t * This is a <b>comparable method</b>.\n\t *\n\t * @param that\n\t * the store being compared against.\n\t * @return zero if the stores are equal, a negative value if this store\n\t * precedes the given store in lexical order, a positive value\n\t * otherwise.\n\t * @see Bits#compareLexical(BitStore, BitStore)\n\t * @see #compareNumericallyTo(BitStore)\n\t */\n\n\tdefault int compareLexicallyTo(BitStore that) {\n\t\tif (this == that) return 0; // cheap check\n\t\tif (that == null) throw new IllegalArgumentException(\"that\");\n\t\tint s1 = this.size();\n\t\tint s2 = that.size();\n\t\tif (s1 == s2) return Bits.compareNumeric(this, that);\n\t\treturn s1 > s2 ?\n\t\t\t\t Bits.compareLexical(this, that) :\n\t\t\t\t- Bits.compareLexical(that, this);\n\t}\n\n\t// convenience methods\n\n\t/**\n\t * <p>\n\t * Sets all bits in the bit store to the specified value.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param value\n\t * the bit value to assign to all bits\n\t * @see #fill()\n\t * @see #clear()\n\t */\n\n\tdefault void setAll(boolean value) {\n\t\tif (value) {\n\t\t\tfill();\n\t\t} else {\n\t\t\tclear();\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Returns an {@link Op} that applies the specified {@link Operation} to the\n\t * bits of this {@link BitStore}.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param operation\n\t * the operation to be applied to the bits of this store.\n\t * @return an object that can applies the operation to this bit store.\n\t * @see #set()\n\t * @see #and()\n\t * @see #or()\n\t * @see #xor()\n\t */\n\n\tdefault Op op(Operation operation) {\n\t\tif (operation == null) throw new IllegalArgumentException(\"null operation\");\n\t\tswitch (operation) {\n\t\tcase SET: return set();\n\t\tcase AND: return and();\n\t\tcase OR: return or();\n\t\tcase XOR: return xor();\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException(\"Unsupported operation\");\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Returns an object that identifies each position with the specified bits\n\t * value.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param bit\n\t * the bit value to match\n\t * @return the locations of the matching bits\n\t * @see #ones()\n\t * @see #zeros()\n\t */\n\n\tdefault BitMatches match(boolean bit) {\n\t\treturn bit ? ones() : zeros();\n\t}\n\n\t/**\n\t * <p>\n\t * Returns tests of a specified nature.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param test\n\t * the test to be applied\n\t * @return an object that applies the specified test\n\t * @see #equals()\n\t * @see #contains()\n\t * @see #excludes()\n\t * @see #complements()\n\t */\n\n\tdefault Tests test(Test test) {\n\t\tif (test == null) throw new IllegalArgumentException(\"null test\");\n\t\tswitch (test) {\n\t\tcase EQUALS: return equals();\n\t\tcase CONTAINS: return contains();\n\t\tcase EXCLUDES: return excludes();\n\t\tcase COMPLEMENTS: return complements();\n\t\tdefault: throw new IllegalStateException(\"Unexpected test\");\n\t\t}\n\t}\n\n\t/**\n\t * <p>\n\t * Opens a {@link BitWriter} that writes bits into the {@link BitStore}. The\n\t * bit writer writes 'backwards' (in big-endian order) from the\n\t * highest-indexed (most-significant) bit to the zero-indexed\n\t * (least-significant) bit.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @return a writer over the bit store\n\t * @see #openWriter(int, int)\n\t */\n\n\tdefault BitWriter openWriter() {\n\t\treturn openWriter(0, size());\n\t}\n\n\t/**\n\t * <p>\n\t * Opens a {@link BitReader} that reads bits from the {@link BitStore}. The\n\t * bit reader reads 'backwards' (in big-endian order) from the\n\t * highest-indexed (most-significant) bit to the zero-indexed\n\t * (least-significant) bit.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @return a reader over the bit store\n\t * @see #openReader(int, int)\n\t */\n\n\tdefault BitReader openReader() {\n\t\treturn openReader(0, size());\n\t}\n\n\t/**\n\t * <p>\n\t * A sub-range from a given position to the end of the {@link BitStore}.\n\t * Equivalent to <code>range(from, size)</code> where <code>size</code> is\n\t * the size of this store.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param from\n\t * the start of the range (inclusive)\n\t * @return a sub range of the {@link BitStore}\n\t * @see #range(int, int)\n\t */\n\n\tdefault BitStore rangeFrom(int from) {\n\t\treturn range(from, size());\n\t}\n\n\t/**\n\t * <p>\n\t * A sub-range the start of the {@link BitStore} to a given position.\n\t * Equivalent to <code>range(0, to)</code>.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param to\n\t * the end of the range (exclusive)\n\t * @return a sub range of the {@link BitStore}\n\t * @see #range(int, int)\n\t */\n\n\tdefault BitStore rangeTo(int to) {\n\t\treturn range(0, to);\n\t}\n\n\t/**\n\t * <p>\n\t * Compares this {@link BitStore} to another. The comparison is numerical\n\t * and equivalent to that performed by\n\t * {@link #compareNumericallyTo(BitStore)}.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param that\n\t * the comparand\n\t * @return zero if the stores are equal, a negative value if this store is\n\t * less than the given store, a positive value otherwise.\n\t * @throws NullPointerException\n\t * if the supplied bit store is null as per the contract for\n\t * <code>Comparable</code>\n\t * @see #compareNumericallyTo(BitStore)\n\t */\n\n\tdefault int compareTo(BitStore that) {\n\t\tif (that == null) throw new NullPointerException(); // as per compareTo() contract\n\t\treturn compareNumericallyTo(that);\n\t}\n\n\t/**\n\t * <p>\n\t * Returns 8 bits of the {@link BitStore} starting from a specified\n\t * position, packed into a <code>byte</code>. The position specifies the\n\t * index of the least significant bit.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit returned\n\t * @return a byte containing 8 bits of the {@link BitStore}\n\t * @see #getBits(int, int)\n\t */\n\n\tdefault byte getByte(int position) {\n\t\treturn (byte) getBits(position, 8);\n\t}\n\n\t/**\n\t * <p>\n\t * Returns 16 bits of the {@link BitStore} starting from a specified\n\t * position, packed into a <code>short</code>. The position specifies the\n\t * index of the least significant bit.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit returned\n\t * @return a short containing 16 bits of the {@link BitStore}\n\t * @see #getBits(int, int)\n\t */\n\n\tdefault short getShort(int position) {\n\t\treturn (short) getBits(position, 16);\n\t}\n\n\t/**\n\t * <p>\n\t * Returns 32 bits of the {@link BitStore} starting from a specified\n\t * position, packed into an <code>int</code>. The position specifies the\n\t * index of the least significant bit.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit returned\n\t * @return an int containing 32 bits of the {@link BitStore}\n\t * @see #getBits(int, int)\n\t */\n\n\tdefault int getInt(int position) {\n\t\treturn (int) getBits(position, 32);\n\t}\n\n\t/**\n\t * <p>\n\t * Returns 64 bits of the {@link BitStore} starting from a specified\n\t * position, packed into a <code>long</code>. The position specifies the\n\t * index of the least significant bit.\n\t *\n\t * <p>\n\t * This is a <b>convenience method</b>.\n\t *\n\t * @param position\n\t * the index of the least bit returned\n\t * @return a long containing 64 bits of the {@link BitStore}\n\t * @see #getBits(int, int)\n\t */\n\n\tdefault long getLong(int position) {\n\t\treturn getBits(position, 64);\n\t}\n\n}", "public class BitStreamException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 6076037872218957434L;\n\n\tpublic BitStreamException() {\n\t}\n\n\tpublic BitStreamException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic BitStreamException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic BitStreamException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}", "@FunctionalInterface\npublic interface BitWriter extends BitStream {\n\n\t/**\n\t * Writes the least significant bit of an int to the stream.\n\t *\n\t * @param bit\n\t * the value to write\n\t *\n\t * @return the number of bits written, always 1\n\t * @throws BitStreamException\n\t * if an exception occurs when writing to the stream\n\t */\n\n\tint writeBit(int bit) throws BitStreamException;\n\n\t/**\n\t * Write a single bit to the stream.\n\t *\n\t * @param bit\n\t * the value to write\n\t *\n\t * @return the number of bits written, always 1\n\t * @throws BitStreamException\n\t * if an exception occurs when writing to the stream\n\t */\n\n\tdefault int writeBoolean(boolean bit) throws BitStreamException {\n\t\treturn writeBit(bit ? 1 : 0);\n\t}\n\n\t/**\n\t * Writes the specified number of bits to the stream.\n\t *\n\t * @param value\n\t * the bit value to be written\n\t * @param count\n\t * the number of bits to write\n\t *\n\t * @return the number of bits written\n\t * @throws BitStreamException\n\t * if an exception occurs when writing to the stream\n\t */\n\n\tdefault long writeBooleans(boolean value, long count) throws BitStreamException {\n\t\tif (count == 0) return 0;\n\t\tfinal int bits = value ? -1 : 0;\n\t\tif (count <= 32) return write(bits, (int) count);\n\n\t\tint c = 0;\n\t\twhile (count > 32) {\n\t\t\tc += write(bits, 32);\n\t\t\tcount -= 32;\n\t\t}\n\t\treturn c;\n\t}\n\n\t/**\n\t * Writes between 0 and 32 bits to the stream. Bits are read from the least\n\t * significant places.\n\t *\n\t * @param bits\n\t * the bits to write\n\t * @param count\n\t * the number of bits to write\n\t *\n\t * @return the number of bits written, always count\n\t * @throws BitStreamException\n\t * if an exception occurs when writing to the stream\n\t */\n\n\tdefault int write(int bits, int count) throws BitStreamException {\n\t\tif (count < 0) throw new IllegalArgumentException(\"negative count\");\n\t\tif (count > 32) throw new IllegalArgumentException(\"count too great\");\n\t\tif (count == 0) return 0;\n\t\tint c = 0;\n\t\tfor (count--; count >= 0; count--) {\n\t\t\tc += writeBit(bits >>> count);\n\t\t}\n\t\treturn c;\n\t}\n\n\t/**\n\t * Writes between 0 and 64 bits to the stream. Bits are read from the least\n\t * significant places.\n\t *\n\t * @param bits\n\t * the bits to write\n\t * @param count\n\t * the number of bits to write\n\t *\n\t * @return the number of bits written, always count\n\t * @throws BitStreamException\n\t * if an exception occurs when writing to the stream\n\t */\n\n\tdefault int write(long bits, int count) throws BitStreamException {\n\t\tif (count < 0) throw new IllegalArgumentException(\"negative count\");\n\t\tif (count > 64) throw new IllegalArgumentException(\"count too great\");\n\t\tif (count <= 32) {\n\t\t\treturn write((int) bits, count);\n\t\t} else {\n\t\t\treturn write((int)(bits >> 32), count - 32) + write((int) bits, 32);\n\t\t}\n\t}\n\n\t/**\n\t * Writes the specified number of bits to the stream. Bits are read from the least\n\t * significant places.\n\t *\n\t * @param bits\n\t * the bits to write\n\t * @param count\n\t * the number of bits to write\n\t *\n\t * @return the number of bits written, always count\n\t * @throws BitStreamException\n\t * if an exception occurs when writing to the stream\n\t */\n\n\tdefault int write(BigInteger bits, int count) throws BitStreamException {\n\t\tif (count < 0) throw new IllegalArgumentException(\"negative count\");\n\t\tif (count <= 32) return write(bits.intValue(), count);\n\t\tif (count <= 64) return write(bits.longValue(), count);\n\t\tint c = 0;\n\t\tfor (count--; count >= 0; count--) {\n\t\t\tc += writeBoolean( bits.testBit(count) );\n\t\t}\n\t\treturn c;\n\t}\n\n\t/**\n\t * Flushes this output stream and forces any buffered output bits to be\n\t * written out to an underlying stream. This DOES NOT necessarily flush an\n\t * underlying stream.\n\t *\n\t * NOTE: Implementations that write bits to an underlying medium that cannot\n\t * persist individual bits may necessarily pad their output to make the\n\t * flush possible.\n\t *\n\t * The number of bits with which the output stream was padded is returned\n\t * from the call. Padding is always performed with zero bits.\n\t *\n\t * @return the number of bits with which the stream was padded to enable\n\t * flushing\n\t * @throws BitStreamException\n\t * if an exception occurs flushing the stream\n\t */\n\n\tdefault int flush() throws BitStreamException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Pads the stream with zeros up to the specified boundary. If the stream is\n\t * already positioned on the boundary, no bits will be written.\n\t *\n\t * NOTE: This method may not be supported by writers that cannot track their\n\t * position in the bit stream.\n\t *\n\t * @param boundary\n\t * the 'size' of boundary\n\t * @return the number of zero bits written to the stream\n\t * @throws UnsupportedOperationException\n\t * if the stream does not support padding\n\t * @throws BitStreamException\n\t * if an exception occurs when padding\n\t */\n\n\tdefault int padToBoundary(BitBoundary boundary) throws UnsupportedOperationException, BitStreamException {\n\t\tif (boundary == null) throw new IllegalArgumentException(\"null boundary\");\n\t\tlong position = getPosition();\n\t\tif (position == -1L) throw new UnsupportedOperationException(\"padding to boundary not supported\");\n\t\tint bits = boundary.bitsFrom(position);\n\t\tif (bits == 0) return 0;\n\t\treturn (int) writeBooleans(false, bits);\n\t}\n\n}", "public final class Bits {\n\n\tprivate enum StorageType {\n\t\tBYTE,\n\t\tLONG;\n\n\t\tBitStore sized(int size) {\n\t\t\tswitch (this) {\n\t\t\tcase BYTE: return new BytesBitStore(size);\n\t\t\tcase LONG: return new BitVector(size);\n\t\t\tdefault: throw new IllegalStateException();\n\t\t\t}\n\t\t}\n\n\t\tBitStore random(int size, Random random, float probability) {\n\t\t\tswitch (this) {\n\t\t\tcase BYTE: return new BytesBitStore(random, probability, size);\n\t\t\tcase LONG: return new BitVector(random, probability, size);\n\t\t\tdefault: throw new IllegalStateException();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static final String STORAGE_PROPERTY = \"com.tomgibara.bits.preferredStorage\";\n\tprivate static final StorageType DEFAULT_STORAGE = StorageType.LONG;\n\n\tprivate static final StorageType preferredType = preferredType();\n\n\tprivate static StorageType preferredType() {\n\t\tString property = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(STORAGE_PROPERTY));\n\t\tif (property == null) return DEFAULT_STORAGE;\n\t\tswitch (property.toLowerCase()) {\n\t\tcase \"byte\" : return StorageType.BYTE;\n\t\tcase \"long\" : return StorageType.LONG;\n\t\tdefault:\n\t\t\tSystem.err.println(\"unrecognized storage type '\" + property + \"' for system property '\" + STORAGE_PROPERTY + \"'\");\n\t\t\treturn DEFAULT_STORAGE;\n\t\t}\n\t}\n\n\tprivate static final Hasher<BitStore> bitStoreHasher = bitStoreHasher((b,s) -> b.writeTo(s));\n\n\tprivate static final Comparator<BitStore> numericalComparator = new Comparator<BitStore>() {\n\t\t@Override\n\t\tpublic int compare(BitStore a, BitStore b) {\n\t\t\treturn a.compareNumericallyTo(b);\n\t\t}\n\t};\n\n\tprivate static final Comparator<BitStore> lexicalComparator = new Comparator<BitStore>() {\n\t\t@Override\n\t\tpublic int compare(BitStore a, BitStore b) {\n\t\t\treturn a.compareLexicallyTo(b);\n\t\t}\n\t};\n\n\t// public\n\n\t// helpers\n\n\t/**\n\t * Produces a binary String representation consistent with that specified in\n\t * the contract for {@link BitStore}. This method is intended to assist\n\t * implementors of the {@link BitStore} interface and consequently does not\n\t * rely on the <code>toString()</code> implementation of the supplied store.\n\t *\n\t * @param store\n\t * a bit store\n\t * @return the supplied bit store as a binary string\n\t */\n\n\tpublic static String toString(BitStore store) {\n\t\tif (store == null) throw new IllegalArgumentException(\"null store\");\n\t\tint size = store.size();\n\t\tswitch (size) {\n\t\tcase 0 : return \"\";\n\t\tcase 1 : return store.getBit(0) ? \"1\" : \"0\";\n\t\tdefault:\n\t\t\tStringBuilder sb = new StringBuilder(size);\n\t\t\tint to = size;\n\t\t\tint from = size & ~63;\n\t\t\tif (from != to) {\n\t\t\t\tint length = to - from;\n\t\t\t\tlong bits = store.getBits(from, length) << (64 - length);\n\t\t\t\tfor (; length > 0; length --) {\n\t\t\t\t\tsb.append(bits < 0L ? '1' : '0');\n\t\t\t\t\tbits <<= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile (from != 0) {\n\t\t\t\tfrom -= 64;\n\t\t\t\tlong bits = store.getLong(from);\n\t\t\t\tfor (int i = 0; i < 64; i++) {\n\t\t\t\t\tsb.append(bits < 0L ? '1' : '0');\n\t\t\t\t\tbits <<= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn sb.toString();\n\t\t}\n\t}\n\n\t/**\n\t * A hasher that generates hash codes that are consistent with the stated\n\t * contract for {@link BitStore}. The resulting hasher may be used for this\n\t * purpose as follows:\n\t * <code>Bits.bitStoreHasher().intHashValue(store)</code>.\n\t *\n\t * @return a hasher of {@link BitStore}\n\t */\n\n\tpublic static Hasher<BitStore> bitStoreHasher() {\n\t\treturn bitStoreHasher;\n\t}\n\n\t/**\n\t * A comparator that orders bit stores consistently with\n\t * {@link BitStore#compareNumericallyTo(BitStore)}.\n\t *\n\t * @return a numerical comparator of {@link BitStore}\n\t */\n\n\tpublic static Comparator<BitStore> numericalComparator() {\n\t\treturn numericalComparator;\n\t}\n\n\t/**\n\t * A comparator that orders bit stores consistently with\n\t * {@link BitStore#compareLexicallyTo(BitStore)}.\n\t *\n\t * @return a lexical comparator of {@link BitStore}\n\t */\n\n\tpublic static Comparator<BitStore> lexicalComparator() {\n\t\treturn lexicalComparator;\n\t}\n\n\t// new bit store\n\n\t/**\n\t * Creates a new mutable {@link BitStore} instance with the specified size.\n\t * The implementing class is likely to vary with the requested size.\n\t *\n\t * @param size\n\t * the capacity, in bits, of the new {@link BitStore}\n\t *\n\t * @return a new mutable {@link BitStore} of the specified size.\n\t */\n\n\tpublic static BitStore store(int size) {\n\t\tif (size < 0) throw new IllegalArgumentException();\n\t\tswitch (size) {\n\t\tcase 0 : return VoidBitStore.MUTABLE;\n\t\tcase 1 : return new Bit();\n\t\tcase 64: return new LongBitStore();\n\t\tdefault:\n\t\t\treturn size < 64 ?\n\t\t\t\t\tnew LongBitStore().range(0, size) : // assumed preferred irrespective of storage preference\n\t\t\t\t\t // because allocation of array is avoided\n\t\t\t\t\tpreferredType.sized(size);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a mutable {@link BitStore} initialized with a binary string of\n\t * characters. The size of store will equal the number of characters. The\n\t * string is treated as an arbitrary length binary number, so (by way of\n\t * example) the value the zeroth character in the string determines the\n\t * value of the highest indexed bit in the store.\n\t *\n\t * @param chars\n\t * a character sequence of the binary characters <code>'0'</code>\n\t * and <code>'1'</code>\n\t * @return a new mutable {@link BitStore} initialized with the specified\n\t * binary string\n\t * @see #asStore(CharSequence)\n\t * @see #readerFrom(CharSequence)\n\t */\n\n\tpublic static BitStore toStore(CharSequence chars) {\n\t\tif (chars == null) throw new IllegalArgumentException(\"null chars\");\n\t\tint size = chars.length();\n\t\tBitStore store = store(size);\n\t\ttransferImpl( new CharBitReader(chars), store.openWriter(), size );\n\t\treturn store;\n\t}\n\n\t/**\n\t * Creates a mutable {@link BitStore} initialized with random bit values.\n\t *\n\t * @param size\n\t * the capacity, in bits, of the new {@link BitStore}\n\t * @param random\n\t * a source of randomness\n\t * @param probability\n\t * a number between 0 and 1 inclusive, being the independent\n\t * probability that a bit is set\n\t * @return a new mutable {@link BitStore} initialized with random bit values\n\t */\n\n\tpublic static BitStore toStore(int size, Random random, float probability) {\n\t\treturn preferredType.random(size, random, probability);\n\t}\n\n\t/**\n\t * Creates a mutable {@link BitStore} initialized with random bit values;\n\t * the independent probability of each bit having a value of 1 being equal\n\t * to 0.5.\n\t *\n\t * @param size\n\t * the capacity, in bits, of the new {@link BitStore}\n\t * @param random\n\t * a source of randomness\n\t * @return a new mutable {@link BitStore} initialized with random bit values\n\t */\n\n\tpublic static BitStore toStore(int size, Random random) {\n\t\treturn preferredType.random(size, random, 0.5f);\n\t}\n\n\t/**\n\t * Creates a mutable {@link BitStore} instance of size one (ie. containing a\n\t * single bit).\n\t *\n\t * @param bit\n\t * the value of the single bit in the new {@link BitStore}\n\t *\n\t * @return a new mutable {@link BitStore} initialized with the specified bit\n\t * value\n\t */\n\n\tpublic static BitStore toStore(boolean bit) {\n\t\treturn new Bit(bit);\n\t}\n\n\t/**\n\t * Creates a mutable {@link BitStore} instance of size 64, initialized with\n\t * the bit values of the supplied long. The long is treated as a big-endian\n\t * value, so (by way of example) its least significant bit determines the\n\t * value of the store's zero indexed bit.\n\t *\n\t * @param bits\n\t * the values of the bits in the new {@link BitStore}\n\t *\n\t * @return a new mutable {@link BitStore} of size 64 initialized with the\n\t * bits of the supplied long\n\t */\n\n\tpublic static BitStore toStore(long bits) {\n\t\treturn new LongBitStore(bits);\n\t}\n\n\t/**\n\t * Creates a mutable {@link BitStore} instance initialized with the bit\n\t * values from a supplied long. The long is treated as a big-endian value,\n\t * so (by way of example) its least significant bit determines the value of\n\t * the store's zero indexed bit. The count parameter determines the number\n\t * of bits read from the long value that are used to construct the new\n\t * {@link BitStore}, and consequently, the size of the returned bit store.\n\t * Where the count is less that 64, the least signficant bits of the long\n\t * value are used.\n\t *\n\t * @param bits\n\t * the values of the bits in the new {@link BitStore}\n\t * @param count\n\t * between 0 and 64 inclusive, the number of bits used to\n\t * populate the new {@link BitStore}\n\t *\n\t * @return a new mutable {@link BitStore} initialized with the bits of the\n\t * supplied long\n\t */\n\n\tpublic static BitStore toStore(long bits, int count) {\n\t\treturn new LongBitStore(bits).range(0, count);\n\t}\n\n\t// immutable bit stores\n\n\t/**\n\t * An immutable {@link BitStore} of zero size.\n\t *\n\t * @return an immutable zero size {@link BitStore}\n\t */\n\n\tpublic static BitStore noBits() {\n\t\treturn VoidBitStore.MUTABLE;\n\t}\n\n\t/**\n\t * An immutable {@link BitStore} consisting of a single one bit.\n\t *\n\t * @return an immutable {@link BitStore} of size 1, containing a one bit.\n\t * @see #bit(boolean)\n\t */\n\n\tpublic static BitStore oneBit() {\n\t\treturn ImmutableOne.INSTANCE;\n\t}\n\n\t/**\n\t * An immutable {@link BitStore} consisting of a single zero bit.\n\t *\n\t * @return an immutable {@link BitStore} of size 1, containing a zero bit.\n\t * @see #bit(boolean)\n\t */\n\n\tpublic static BitStore zeroBit() {\n\t\treturn ImmutableZero.INSTANCE;\n\t}\n\n\t/**\n\t * An immutable {@link BitStore} containing a specified number one bits.\n\t *\n\t * @param size\n\t * the number of bits in the bit store\n\t * @return an immutable {@link BitStore} of the specified size containing\n\t * only one bits\n\t * @see #bits(boolean,int)\n\t */\n\n\tpublic static BitStore oneBits(int size) {\n\t\tcheckSize(size);\n\t\treturn new ImmutableBits.ImmutablesOnes(size);\n\t}\n\n\t/**\n\t * An immutable {@link BitStore} containing a specified number zero bits.\n\t *\n\t * @param size\n\t * the number of bits in the bit store\n\t * @return an immutable {@link BitStore} of the specified size containing\n\t * only zero bits\n\t * @see #bits(boolean,int)\n\t */\n\n\tpublic static BitStore zeroBits(int size) {\n\t\tcheckSize(size);\n\t\treturn new ImmutableBits.ImmutablesZeros(size);\n\t}\n\n\t/**\n\t * An immutable {@link BitStore} consisting of a single bit with a specified\n\t * value.\n\t *\n\t * @param bit\n\t * the bit with which the {@link BitStore} is populated\n\t * @return an immutable {@link BitStore} consisting of the specified bit\n\t * @see #oneBit()\n\t * @see #zeroBit()\n\t */\n\n\tpublic static BitStore bit(boolean bit) {\n\t\treturn ImmutableBit.instanceOf(bit);\n\t}\n\n\t/**\n\t * An immutable {@link BitStore} of identical bits.\n\t *\n\t * @param ones\n\t * true if the {@link BitStore} contains ones, false if it\n\t * contains zeros\n\t * @param size\n\t * the number of bits in the {@link BitStore}\n\t * @return an immutable {@link BitStore} of the specified bits\n\t * @see #oneBits(int)\n\t * @see #zeroBits(int)\n\t */\n\n\tpublic static BitStore bits(boolean ones, int size) {\n\t\treturn ones ? oneBits(size) : zeroBits(size);\n\t}\n\n\t// bit store views\n\n\t/**\n\t * Exposes a <code>BitSet</code> as a {@link BitStore}. The returned bit\n\t * store is a live view over the bit set; changes made to the bit set are\n\t * reflected in the bit store and vice versa. Unlike bit sets, bit stores\n\t * have a fixed size which must be specified at construction time and which\n\t * is not required to match the length of the bit set. In all cases, the\n\t * bits of the bit set are drawn from the lowest-indexed bits.\n\t *\n\t * @param bitSet\n\t * the bits of the {@link BitStore}\n\t * @param size\n\t * the size, in bits, of the {@link BitStore}\n\t * @return a {@link BitStore} view over the bit set.\n\t */\n\n\tpublic static BitStore asStore(BitSet bitSet, int size) {\n\t\tif (bitSet == null) throw new IllegalArgumentException(\"null bitSet\");\n\t\tcheckSize(size);\n\t\treturn new BitSetBitStore(bitSet, 0, size, true);\n\t}\n\n\t/**\n\t * Exposes the bits of a byte array as a {@link BitStore}. The returned bit\n\t * store is a live view over the byte array; changes made to the array are\n\t * reflected in bit store and vice versa. The bit store contains every bit\n\t * in the array with the zeroth indexed bit of the store taking its value\n\t * from the least significant bit of the byte at index zero.\n\t *\n\t * @param bytes\n\t * the byte data\n\t * @return a {@link BitStore} over the bytes.\n\t * @see #asStore(byte[], int, int)\n\t * @see BitVector#fromByteArray(byte[], int)\n\t */\n\n\tpublic static BitStore asStore(byte[] bytes) {\n\t\tif (bytes == null) throw new IllegalArgumentException(\"null bytes\");\n\t\tif (bytes.length * 8L > Integer.MAX_VALUE) throw new IllegalArgumentException(\"index overflow\");\n\t\treturn new BytesBitStore(bytes, 0, bytes.length << 3, true);\n\t}\n\n\t/**\n\t * Exposes a subrange of the bits of a byte array as a {@link BitStore}. The\n\t * returned bit store is a live view over the bytes; changes made to the\n\t * array are reflected in bit store and vice versa. The size of the returned\n\t * bit vector is the length of the sub range.\n\t *\n\t * @param bytes\n\t * the byte data\n\t * @param offset\n\t * the index, in bits of the first bit in the bit store\n\t * @param length\n\t * the number of bits spanned by the bit store\n\t * @return a {@link BitStore} over some range of bytes\n\t * @see #asStore(byte[])\n\t * @see BitVector#fromByteArray(byte[], int)\n\t */\n\n\tpublic static BitStore asStore(byte[] bytes, int offset, int length) {\n\t\tif (bytes == null) throw new IllegalArgumentException(\"null bytes\");\n\t\tint size = bytes.length << 3;\n\t\tif (offset < 0) throw new IllegalArgumentException(\"negative offset\");\n\t\tif (length < 0) throw new IllegalArgumentException(\"negative length\");\n\t\tint finish = offset + length;\n\t\tif (finish < 0) throw new IllegalArgumentException(\"index overflow\");\n\t\tif (finish > size) throw new IllegalArgumentException(\"exceeds size\");\n\t\treturn new BytesBitStore(bytes, offset, finish, true);\n\t}\n\n\t/**\n\t * Exposes an array of booleans as a {@link BitStore}. The returned bit\n\t * store is a live view over the booleans; changes made to the array are\n\t * reflected in bit store and vice versa. The size of the returned bit\n\t * vector equals the length of the array with the bits of the\n\t * {@link BitStore} indexed as per the underlying array.\n\t *\n\t * @param bits\n\t * the bit values\n\t * @return a {@link BitStore} over the boolean array\n\t */\n\n\tpublic static BitStore asStore(boolean[] bits) {\n\t\tif (bits == null) throw new IllegalArgumentException(\"null bits\");\n\t\treturn new BooleansBitStore(bits, 0, bits.length, true);\n\t}\n\n\t/**\n\t * Exposes a sub-range of a boolean array as a {@link BitStore}. The\n\t * returned bit store is a live view over the booleans; changes made to the\n\t * array are reflected in bit store and vice versa. The size of the returned\n\t * bit vector equals the length of the range with the least-significant bit\n\t * of the {@link BitStore} taking its value from the lowest-indexed value in\n\t * the range.\n\t *\n\t * @param bits\n\t * an array of bit values\n\t * @param offset\n\t * the index of the first boolean value in the {@link BitStore}\n\t * @param length\n\t * the number of boolean values covered by the {@link BitStore}\n\t * @return a {@link BitStore} over the boolean array\n\t */\n\n\tpublic static BitStore asStore(boolean[] bits, int offset, int length) {\n\t\tif (bits == null) throw new IllegalArgumentException(\"null bits\");\n\t\tint size = bits.length;\n\t\tif (offset < 0) throw new IllegalArgumentException(\"negative offset\");\n\t\tif (length < 0) throw new IllegalArgumentException(\"negative length\");\n\t\tint finish = offset + length;\n\t\tif (finish < 0) throw new IllegalArgumentException(\"index overflow\");\n\t\tif (finish > size) throw new IllegalArgumentException(\"exceeds size\");\n\t\treturn new BooleansBitStore(bits, offset, finish, true);\n\t}\n\n\t/**\n\t * Exposes a <code>BigInteger</code> as an immutable {@link BitStore}. The\n\t * returned bit store draws its values directly from the supplied big\n\t * integer (no copying of bit data takes place) with the bit indexing\n\t * consistent with that of <code>BigInteger</code>. The size of the bit\n\t * store is <code>bigInt.bitLength()</code>.\n\t *\n\t * @param bigInt\n\t * a big integer\n\t * @return a {@link BitStore} view over the big integer.\n\t */\n\n\tpublic static BitStore asStore(BigInteger bigInt) {\n\t\tif (bigInt == null) throw new IllegalArgumentException(\"null bigInt\");\n\t\treturn new BigIntegerBitStore(bigInt);\n\t}\n\n\t/**\n\t * Exposes a <code>SortedSet</code> of <code>Integer</code> as\n\t * {@link BitStore}. The <code>start</code> and <code>finish</code>\n\t * parameters must form a valid sub-range of the set. Since it is not\n\t * possible to determine whether a set is modifiable, the mutability of the\n\t * generated {@link BitStore} must be specified as a call parameter.\n\t * Creating a mutable {@link BitStore} over an unmodifiable set may result\n\t * in unspecified errors on any attempt to mutate the bit store.\n\t *\n\t * @param set\n\t * a sorted set of integers\n\t * @param start\n\t * the least integer exposed by the {@link BitStore}\n\t * @param finish\n\t * the least integer greater than or equal to <code>start</code>\n\t * that is not exposed by the {@link BitStore}\n\t * @param mutable\n\t * whether the returned {@link BitStore} is mutable\n\t * @throws IllegalArgumentException\n\t * if the range start-to-finish does not form a valid sub-range\n\t * of the supplied set.\n\t * @return a {@link BitStore} view over the set\n\t */\n\n\tpublic static BitStore asStore(SortedSet<Integer> set, int start, int finish, boolean mutable) {\n\t\tif (set == null) throw new IllegalArgumentException(\"null set\");\n\t\tif (start < 0L) throw new IllegalArgumentException(\"negative start\");\n\t\tif (finish < start) throw new IllegalArgumentException(\"start exceeds finish\");\n\t\tset = set.subSet(start, finish);\n\t\treturn new IntSetBitStore(set, start, finish, mutable);\n\t}\n\n\t/**\n\t * <p>\n\t * Exposes a <code>CharSequence</code> as a {@link BitStore}. The returned\n\t * bit store draws its values directly from the supplied character data (no\n\t * copying of bit data takes place) such that the character at index zero is\n\t * exposed as the <em>most-significant</em> bit in the store. This\n\t * consistent with the conventional string representation of binary values.\n\t *\n\t * <p>\n\t * The supplied character sequence is required to consist only of the\n\t * characters <code>'0'</code> and <code>'1'</code>. Since\n\t * <code>CharSequence</code> instances may be mutable, it is not possible to\n\t * enforce, in general, that a sequence meets this requirement; sequences\n\t * consisting of invalid characters may result an\n\t * <code>IllegalStateException</code> being thrown when the bit store is\n\t * operated on.\n\t *\n\t * <p>\n\t * It is not possible, given an arbitrary <code>CharSequence</code> instance\n\t * to determine its mutability. For this reason the current implementation\n\t * is conservative and makes the following assumption: that\n\t * <code>StringBuilder</code> or <code>StringBuffer</code> instances are\n\t * mutable and that all other <code>CharSequence</code> instances (including\n\t * <code>String</code> are not. This is used to determine the mutability of\n\t * the returned {@link BitStore}.\n\t *\n\t * @param chars\n\t * a sequence of characters\n\t * @return a {@link BitStore} over the character sequence.\n\t * @see #toStore(CharSequence)\n\t * @see #readerFrom(CharSequence)\n\t */\n\n\tpublic static BitStore asStore(CharSequence chars) {\n\t\tif (chars == null) throw new IllegalArgumentException(\"null chars\");\n\t\treturn new CharsBitStore(chars);\n\t}\n\n\t// bit streams\n\n\t/**\n\t * A {@link BitReader} that sources its bits from a\n\t * <code>CharSequence</code>. Bits are read from the sequence starting with\n\t * the character at index zero. The presence of a character other than a '1'\n\t * or '0' will result in a {@link BitStreamException} being thrown when an\n\t * attempt is made to read a bit at that index.\n\t *\n\t * @param chars\n\t * the source characters\n\t * @return a bit reader over the characters\n\t */\n\n\tpublic static BitReader readerFrom(CharSequence chars) {\n\t\tif (chars == null) throw new IllegalArgumentException(\"null chars\");\n\t\treturn new CharBitReader(chars);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources its bits from an array of bytes. Bits\n\t * are read from the byte array starting at index zero. Within each byte,\n\t * the most significant bits are read first.\n\t *\n\t * @param bytes\n\t * the source bytes\n\t * @return a bit reader over the bytes\n\t */\n\n\tpublic static BitReader readerFrom(byte[] bytes) {\n\t\tif (bytes == null) throw new IllegalArgumentException(\"null bytes\");\n\t\treturn new ByteArrayBitReader(bytes);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources its bits from an array of bytes. Bits are\n\t * read from the byte array starting at index zero. Within each byte, the\n\t * most significant bits are read first.\n\t *\n\t * @param bytes\n\t * the source bytes\n\t * @param size\n\t * the number of bits that may be read, not negative and no\n\t * greater than the number of bits supplied by the array\n\t * @return a bit reader over the bytes\n\t */\n\n\tpublic static BitReader readerFrom(byte[] bytes, long size) {\n\t\tif (bytes == null) throw new IllegalArgumentException(\"null bytes\");\n\t\tcheckSize(size, ((long) bytes.length) << 3);\n\t\treturn new ByteArrayBitReader(bytes, size);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources its bits from an array of ints. Bits are\n\t * read from the int array starting at index zero. Within each int, the most\n\t * significant bits are read first. The size of the reader will equal the\n\t * total number of bits in the array.\n\t *\n\t * @param ints\n\t * the source ints\n\t * @return a bit reader over the ints\n\t */\n\n\tpublic static BitReader readerFrom(int[] ints) {\n\t\tif (ints == null) throw new IllegalArgumentException(\"null ints\");\n\t\treturn new IntArrayBitReader(ints);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources its bits from an array of ints. Bits are\n\t * read from the int array starting at index zero. Within each int, the most\n\t * significant bits are read first.\n\t *\n\t * @param ints\n\t * the source ints\n\t * @param size\n\t * the number of bits that may be read, not negative and no\n\t * greater than the number of bits supplied by the array\n\t * @return a bit reader over the ints\n\t */\n\n\tpublic static BitReader readerFrom(int[] ints, long size) {\n\t\tif (ints == null) throw new IllegalArgumentException(\"null ints\");\n\t\tcheckSize(size, ((long) ints.length) << 5);\n\t\treturn new IntArrayBitReader(ints, size);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources bits from a <code>FileChannel</code>.\n\t * This stream operates with a byte buffer. This will generally improve\n\t * performance in applications that skip forwards or backwards across the\n\t * file.\n\t *\n\t * Note that using a direct ByteBuffer should generally yield better\n\t * performance.\n\t *\n\t * @param channel\n\t * the file channel from which bits are to be read\n\t * @param buffer\n\t * the buffer used to store file data\n\t * @return a bit reader over the channel\n\t */\n\n\tpublic static BitReader readerFrom(FileChannel channel, ByteBuffer buffer) {\n\t\tif (channel == null) throw new IllegalArgumentException(\"null channel\");\n\t\tif (buffer == null) throw new IllegalArgumentException(\"null buffer\");\n\t\treturn new FileChannelBitReader(channel, buffer);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources its bits from an\n\t * <code>InputStream</code>.\n\t *\n\t * @param in\n\t * the source input stream\n\t * @return a bit reader over the input stream\n\t */\n\n\tpublic static BitReader readerFrom(InputStream in) {\n\t\tif (in == null) throw new IllegalArgumentException(\"null in\");\n\t\treturn new InputStreamBitReader(in);\n\t}\n\n\t/**\n\t * A {@link BitReader} that sources its bits from a <code>ReadStream</code>.\n\t *\n\t * @param stream\n\t * the source stream\n\t * @return a bit reader over the stream\n\t */\n\n\tpublic static BitReader readerFrom(ReadStream stream) {\n\t\tif (stream == null) throw new IllegalArgumentException(\"null stream\");\n\t\treturn new StreamBitReader(stream);\n\t}\n\n\t/**\n\t * A {@link BitWriter} that writes its bits to an array of bytes. Bits are\n\t * written to the byte array starting at index zero. Within each byte, the\n\t * most significant bits is written to first.\n\t *\n\t * @param bytes\n\t * the array of bytes\n\t * @return a writer that writes bits to the supplied array\n\t */\n\n\tpublic static BitWriter writerTo(byte[] bytes) {\n\t\tif (bytes == null) throw new IllegalArgumentException(\"null bytes\");\n\t\treturn new ByteArrayBitWriter(bytes);\n\t}\n\n\t/**\n\t * A {@link BitWriter} that writes its bits to an array of bytes. Bits are\n\t * written to the byte array starting at index zero. Within each byte, the\n\t * most significant bits is written to first.\n\t *\n\t * @param bytes\n\t * the array of bytes\n\t * @param size\n\t * the number of bits that may be written, not negative and no\n\t * greater than the number of bits supplied by the array\n\t * @return a writer that writes bits to the supplied array\n\t */\n\n\tpublic static BitWriter writerTo(byte[] bytes, long size) {\n\t\tif (bytes == null) throw new IllegalArgumentException(\"null bytes\");\n\t\tcheckSize(size, ((long) bytes.length) << 3);\n\t\treturn new ByteArrayBitWriter(bytes, size);\n\t}\n\n\t/**\n\t * Writes bits to an array of ints.\n\t *\n\t * @param ints\n\t * the array of ints\n\t * @return a writer that writes bits to the supplied array\n\t */\n\n\tpublic static BitWriter writerTo(int[] ints) {\n\t\tif (ints == null) throw new IllegalArgumentException(\"null ints\");\n\t\treturn new IntArrayBitWriter(ints);\n\t}\n\n\t/**\n\t * Writes bits to an array of ints up-to a specified limit.\n\t *\n\t * @param ints\n\t * the array of ints\n\t * @param size\n\t * the greatest number of bits the writer will write to the array\n\t * @return a writer that writes bits to the supplied array\n\t */\n\n\tpublic static BitWriter writerTo(int[] ints, long size) {\n\t\tif (ints == null) throw new IllegalArgumentException(\"null ints\");\n\t\tif (size < 0) throw new IllegalArgumentException(\"negative size\");\n\t\tlong maxSize = ((long) ints.length) << 5;\n\t\tif (size > maxSize) throw new IllegalArgumentException(\"size exceeds maximum permitted by array length\");\n\t\treturn new IntArrayBitWriter(ints);\n\t}\n\n\t/**\n\t * A {@link BitWriter} that writes its bits to an <code>OutputStream</code>.\n\t *\n\t * @param out\n\t * an output stream\n\t * @return a writer over the output stream\n\t */\n\n\tpublic static BitWriter writerTo(OutputStream out) {\n\t\tif (out == null) throw new IllegalArgumentException(\"null out\");\n\t\treturn new OutputStreamBitWriter(out);\n\t}\n\n\t/**\n\t * A {@link BitWriter} that writes its bits to <code>WriteStream</code>.\n\t *\n\t * @param stream\n\t * a stream\n\t * @return a writer over the stream\n\t */\n\n\tpublic static BitWriter writerTo(WriteStream stream) {\n\t\tif (stream == null) throw new IllegalArgumentException(\"null stream\");\n\t\treturn new StreamBitWriter(stream);\n\t}\n\n\t/**\n\t * <p>\n\t * A new 'null' bit stream that only counts the number of bits written,\n\t * without storing the bits. The number of bits written can be recovered\n\t * from the {@link BitWriter#getPosition()} method.\n\t *\n\t * <p>\n\t * This class is intended to be used in circumstances where adjusting writer\n\t * capacity may be less efficient than writing twice to a stream: once to\n\t * count the length before allocating storage and a second time to store the\n\t * bits written.\n\t *\n\t * @return a new bit stream.\n\t */\n\n\tpublic static BitWriter writerToNothing() {\n\t\treturn new NullBitWriter();\n\t}\n\n\t/**\n\t * A convenient writer for dumping bits to the <code>System.out</code> print\n\t * stream.\n\t *\n\t * @return a bit writer that outputs <code>'1'</code>s and <code>'0'</code>s\n\t * to STDOUT.\n\t */\n\n\tpublic static BitWriter writerToStdout() {\n\t\treturn new PrintStreamBitWriter(System.out);\n\t}\n\n\t/**\n\t * A convenient writer for dumping bits to a specified\n\t * <code>PrintWriter</code>.\n\t *\n\t * @param stream\n\t * a print writer\n\t * @return a bit writer that outputs <code>'1'</code>s and <code>'0'</code>s\n\t * to the <code>PrintWriter</code>.\n\t *\n\t * @see #writerToStdout()\n\t */\n\n\tpublic static BitWriter writerTo(PrintStream stream) {\n\t\tif (stream == null) throw new IllegalArgumentException(\"null stream\");\n\t\treturn new PrintStreamBitWriter(stream);\n\t}\n\n\t// exposed to assist implementors of BitStore.Op interface\n\n\t/**\n\t * Creates a {@link BitWriter} that writes its bits to a {@link BitStore}\n\t * using a specified {@link Operation}. This method is primarily intended to\n\t * assist in implementing a highly adapted {@link BitStore} implementation.\n\t * Generally {@link BitStore.Op#openWriter(int, int)},\n\t * {@link BitStore#openWriter(int, int)}\n\t * {@link BitStore.Op#openWriter(int, int)} and should be used in preference\n\t * to this method. Note that the {@link BitWriter} will\n\t * <em>write in big-endian order</em> which this means that the first bit is\n\t * written at the largest index, working downwards to the least index.\n\t *\n\t * @param store\n\t * the store to which bits will be written\n\t * @param operation\n\t * the operation that should be applied on writing\n\t * @param finalPos\n\t * the (exclusive) index at which the writer stops; less than\n\t * <code>initialPos</code>\n\t * @param initialPos\n\t * the (inclusive) index at which the writer starts; greater than\n\t * <code>finalPos</code>\n\t * @return a writer into the store\n\t * @see BitStore#openWriter()\n\t * @see BitStore#openWriter(int, int)\n\t * @see BitStore.Op#openWriter(int, int)\n\t */\n\n\tpublic static BitWriter writerTo(BitStore store, Operation operation, int finalPos, int initialPos) {\n\t\tif (store == null) throw new IllegalArgumentException(\"null store\");\n\t\tif (operation == null) throw new IllegalArgumentException(\"null operation\");\n\t\tif (finalPos < 0) throw new IllegalArgumentException(\"negative finalPos\");\n\t\tif (initialPos < finalPos) throw new IllegalArgumentException(\"finalPos exceeds initialPos\");\n\t\tif (initialPos > store.size()) throw new IllegalArgumentException(\"invalid initialPos\");\n\n\t\tswitch(operation) {\n\t\tcase SET: return new BitStoreWriter.Set(store, finalPos, initialPos);\n\t\tcase AND: return new BitStoreWriter.And(store, finalPos, initialPos);\n\t\tcase OR: return new BitStoreWriter.Or (store, finalPos, initialPos);\n\t\tcase XOR: return new BitStoreWriter.Xor(store, finalPos, initialPos);\n\t\tdefault:\n\t\t\tthrow new IllegalStateException(\"unsupported operation\");\n\t\t}\n\t}\n\n\t// miscellany\n\n\t/**\n\t * Creates a mutable, resized copy of a {@link BitStore}. The new size may\n\t * be equal, larger or smaller than original size. When the the new size is\n\t * greater than the original size, the new bits are identically zero. The\n\t * method makes no guarantees about the BitStore implementation that\n\t * results, in particular, there is certainly no guarantee that the returned\n\t * {@link BitStore} will share its implementation with the supplied\n\t * {@link BitStore}.\n\t *\n\t * @param store\n\t * a BitStore\n\t * @param newSize\n\t * a new size for the BitStore\n\t * @param anchorLeft\n\t * true if the most-significant bit of the original store should\n\t * remain the most-significant bit of the resized store, false if\n\t * the least-significant bit of the original store should remain\n\t * the least-significant bit of the resized store\n\t * @return a resized copy of the original {@link BitStore}\n\t */\n\n\tpublic static BitStore resizedCopyOf(BitStore store, int newSize, boolean anchorLeft) {\n\t\tif (newSize < 0) throw new IllegalArgumentException();\n\t\tint size = store.size();\n\t\tif (size == newSize) return store.mutableCopy();\n\t\tint from;\n\t\tint to;\n\t\tif (anchorLeft) {\n\t\t\tfrom = size - newSize;\n\t\t\tto = size;\n\t\t} else {\n\t\t\tfrom = 0;\n\t\t\tto = newSize;\n\t\t}\n\t\tif (newSize < size) return store.range(from, to).mutableCopy();\n\t\tBitStore copy = store(newSize);\n\t\tcopy.setStore(-from, store);\n\t\treturn copy;\n\t}\n\n\t/**\n\t * <p>\n\t * An immutable reindexed view of the supplied {@link BitStore}. The\n\t * returned store is a view over this store, changes in either are reflected\n\t * in the other. In contrast to the {@link BitStore#range(int, int)} method\n\t * this method places no restriction of on the <code>to</code> and\n\t * <code>from</code> parameters.\n\t * \n\t * <p>\n\t * If <code>from</code> is less than zero and/or <code>to</code> exceeds the\n\t * store size, the view returned is padded with the specified extension\n\t * value. Additionally, if <code>from</code> exceeds <code>to</code>, the\n\t * view returned is reversed.\n\t *\n\t * <p>\n\t * The returned store as a size of <code>to - from</code> and has its own\n\t * indexing, starting at zero (which maps to index <code>from</code> the\n\t * supplied store).\n\t *\n\t * @param store\n\t * the bits backing the view\n\t * @param from\n\t * the start of the range (inclusive)\n\t * @param to\n\t * the end of the range (exclusive)\n\t * @param extension\n\t * whether the returned view should be padded with ones where the\n\t * range exceeds the bounds of the store, otherwise padding is\n\t * with zeros\n\t * @return a reindexed range of the supplied {@link BitStore}\n\t * @see BitStore#range(int,int)\n\t * @see BitStore#reversed()\n\t */\n\n\tpublic static BitStore freeRangeViewOf(BitStore store, int from, int to, boolean extension) {\n\t\tif (from == to) return Bits.noBits();\n\t\tint size = store.size();\n\t\tif (size == 0) return Bits.noBits();\n\t\tif (from > to) {\n\t\t\tstore = store.reversed();\n\t\t\tint t = from;\n\t\t\tfrom = to;\n\t\t\tto = t;\n\t\t}\n\t\tif ((long) to - (long) from > Integer.MAX_VALUE) throw new IllegalArgumentException(\"maximum size exceeded\");\n\t\tif (to <= 0 || from >= size) return bits(extension, to - from);\n\t\tif (from == 0 && to == size) return store.immutableView();\n\t\tif (from >= 0 && to <= size) return store.immutableView().range(from, to);\n\t\tif (from >= 0) return new ExtendedBitStore(store.rangeFrom(from), extension, 0, to - size);\n\t\tif (to <= size) return new ExtendedBitStore(store.rangeTo(to), extension, 0 - from, 0);\n\t\treturn new ExtendedBitStore(store, extension, 0 - from, to - size);\n\t}\n\n\t/**\n\t * Creates a new growable bits container with a specified initial capacity.\n\t *\n\t * It's implementation is such that, if writes do not exceed the initial\n\t * capacity, no copies or new allocations of bit data will occur.\n\t *\n\t * @param initialCapacity\n\t * the initial capacity in bits\n\t * @return new growable bits\n\t */\n\n\tpublic static GrowableBits growableBits(int initialCapacity) {\n\t\tif (initialCapacity < 0) throw new IllegalArgumentException(\"negative initialCapacity\");\n\t\treturn new GrowableBits(new BitVectorWriter(initialCapacity));\n\t}\n\n\t/**\n\t * Creates a new growable bits container with a default initial capacity.\n\t *\n\t * The default capacity is currently 64 bits, but this is not guaranteed to\n\t * remain unchanged between releases.\n\t *\n\t * @return new growable bits\n\t */\n\n\tpublic static GrowableBits growableBits() {\n\t\treturn new GrowableBits(new BitVectorWriter());\n\t}\n\n\tpublic static void transfer(BitReader reader, BitWriter writer, long count) {\n\t\tif (reader == null) throw new IllegalArgumentException(\"null reader\");\n\t\tif (writer == null) throw new IllegalArgumentException(\"null writer\");\n\t\tif (count < 0L) throw new IllegalArgumentException(\"negative count\");\n\t\ttransferImpl(reader, writer, count);\n\t}\n\n\t// package only\n\n\tstatic <B> Hasher<B> bitStoreHasher(StreamSerializer<B> s) {\n\t\treturn Hashing.murmur3Int().hasher(s);\n\t}\n\n\t// available via default BitStore method\n\tstatic BitStore newRangedView(BitStore store, int from, int to) {\n\t\tif (store == null) throw new IllegalArgumentException(\"null store\");\n\t\tif (from < 0) throw new IllegalArgumentException();\n\t\tif (from > to) throw new IllegalArgumentException();\n\t\tif (to > store.size()) throw new IllegalArgumentException();\n\t\treturn new AbstractBitStore() {\n\n\t\t\t@Override\n\t\t\tpublic int size() {\n\t\t\t\treturn to - from;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean getBit(int index) {\n\t\t\t\treturn store.getBit(adjIndex(index));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void setBit(int index, boolean value) {\n\t\t\t\tstore.setBit(adjIndex(index), value);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void flipBit(int index) {\n\t\t\t\tstore.flipBit(adjIndex(index));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic long getBits(int position, int length) {\n\t\t\t\treturn store.getBits(adjPosition(position), length);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getBitsAsInt(int position, int length) {\n\t\t\t\treturn store.getBitsAsInt(adjPosition(position), length);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean getThenSetBit(int index, boolean value) {\n\t\t\t\treturn store.getThenSetBit(adjIndex(index), value);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void setStore(int position, BitStore that) {\n\t\t\t\tstore.setStore(adjPosition(position), that);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic BitWriter openWriter() {\n\t\t\t\treturn Bits.newBitWriter(store, from, to);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic BitWriter openWriter(int finalPos, int initialPos) {\n\t\t\t\treturn store.openWriter(adjPosition(finalPos), adjPosition(initialPos));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic BitReader openReader() {\n\t\t\t\treturn store.openReader(from, to);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic BitReader openReader(int finalPos, int initialPos) {\n\t\t\t\treturn store.openReader(adjPosition(finalPos), adjPosition(initialPos));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isMutable() {\n\t\t\t\treturn store.isMutable();\n\t\t\t}\n\n\t\t\tprivate int adjIndex(int index) {\n\t\t\t\tif (index < 0) throw new IllegalArgumentException(\"negative index\");\n\t\t\t\tindex += from;\n\t\t\t\tif (index >= to) throw new IllegalArgumentException(\"index too large\");\n\t\t\t\treturn index;\n\t\t\t}\n\n\t\t\tprivate int adjPosition(int position) {\n\t\t\t\tif (position < 0) throw new IllegalArgumentException(\"negative position\");\n\t\t\t\tposition += from;\n\t\t\t\tif (position > to) throw new IllegalArgumentException(\"position too large\");\n\t\t\t\treturn position;\n\t\t\t}\n\t\t};\n\t}\n\n\t// available via default BitStore method\n\tstatic Number asNumber(BitStore store) {\n\t\treturn new Number() {\n\n\t\t\tprivate static final long serialVersionUID = -2906430071162493968L;\n\n\t\t\tfinal int size = store.size();\n\n\t\t\t@Override\n\t\t\tpublic byte byteValue() {\n\t\t\t\treturn (byte) store.getBits(0, Math.min(8, size));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic short shortValue() {\n\t\t\t\treturn (short) store.getBits(0, Math.min(16, size));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int intValue() {\n\t\t\t\treturn (int) store.getBits(0, Math.min(32, size));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic long longValue() {\n\t\t\t\treturn store.getBits(0, Math.min(64, size));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic float floatValue() {\n\t\t\t\treturn store.toBigInteger().floatValue();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic double doubleValue() {\n\t\t\t\treturn store.toBigInteger().doubleValue();\n\t\t\t}\n\n\t\t};\n\t}\n\n\t//TODO further optimizations possible\n\t// available via default BitStore method\n\tstatic BitWriter newBitWriter(BitStore store, int finalPos, int initialPos) {\n\t\treturn writerTo(store, Operation.SET, finalPos, initialPos);\n\t}\n\n\t// available via default BitStore method\n\tstatic BitReader newBitReader(BitStore store, final int finalPos, final int initialPos) {\n\t\tif (store == null) throw new IllegalArgumentException(\"null store\");\n\t\tif (finalPos < 0) throw new IllegalArgumentException(\"negative finalPos\");\n\t\tif (initialPos > store.size()) throw new IllegalArgumentException(\"initialPos too large\");\n\n\t\treturn new BitReader() {\n\t\t\tint pos = initialPos;\n\n\t\t\t@Override\n\t\t\tpublic long getPosition() {\n\t\t\t\treturn initialPos - pos;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic long setPosition(long newPosition) {\n\t\t\t\tif (newPosition < finalPos) {\n\t\t\t\t\tpos = finalPos - initialPos;\n\t\t\t\t\treturn finalPos;\n\t\t\t\t}\n\t\t\t\tif (newPosition >= initialPos) {\n\t\t\t\t\tpos = 0;\n\t\t\t\t\treturn initialPos;\n\t\t\t\t}\n\t\t\t\tpos = initialPos - (int) newPosition;\n\t\t\t\treturn newPosition;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean readBoolean() throws BitStreamException {\n\t\t\t\tif (pos <= 0) throw new EndOfBitStreamException();\n\t\t\t\treturn store.getBit(--pos);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int readBit() throws BitStreamException {\n\t\t\t\treturn readBoolean() ? 1 : 0;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic long readLong(int count) throws BitStreamException {\n\t\t\t\tif (count < 0) throw new IllegalArgumentException();\n\t\t\t\tif (count > 64) throw new IllegalArgumentException();\n\t\t\t\tpos -= count;\n\t\t\t\tif (pos < 0) throw new EndOfBitStreamException();\n\t\t\t\treturn store.getBits(pos, count);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int read(int count) throws BitStreamException {\n\t\t\t\tif (count < 0) throw new IllegalArgumentException();\n\t\t\t\tif (count > 32) throw new IllegalArgumentException();\n\t\t\t\tpos -= count;\n\t\t\t\tif (pos < 0) throw new EndOfBitStreamException();\n\t\t\t\treturn (int) store.getBits(pos, count);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int readUntil(boolean one) throws BitStreamException {\n\t\t\t\t//TODO efficient implementation needs next/previous bit support on BitStore\n\t\t\t\treturn BitReader.super.readUntil(one);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic BigInteger readBigInt(int count) throws BitStreamException {\n\t\t\t\tswitch(count) {\n\t\t\t\tcase 0 : return BigInteger.ZERO;\n\t\t\t\tcase 1 : return readBoolean() ? BigInteger.ONE : BigInteger.ZERO;\n\t\t\t\tdefault :\n\t\t\t\t\tfinal int from = pos - count;\n\t\t\t\t\tif (from < 0) throw new EndOfBitStreamException();\n\t\t\t\t\tfinal int to = pos;\n\t\t\t\t\tpos = from;\n\t\t\t\t\treturn store.range(from, to).toBigInteger();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\t// available via default BitStore method\n\tstatic Positions newPositions(Matches matches, int position) {\n\t\tif (matches == null) throw new IllegalArgumentException(\"null matches\");\n\t\tif (position < 0L) throw new IllegalArgumentException();\n\t\t//TODO consider restoring dedicated size accessor on matches\n\t\tif (position > matches.store().size()) throw new IllegalArgumentException();\n\t\treturn new BitStorePositions(matches, false, position);\n\t}\n\n\t// available via default BitStore method\n\tstatic Positions newPositions(Matches matches) {\n\t\tif (matches == null) throw new IllegalArgumentException(\"null matches\");\n\t\treturn new BitStorePositions(matches, false, 0);\n\t}\n\n\t// available via default BitStore method\n\tstatic Positions newDisjointPositions(Matches matches) {\n\t\tif (matches == null) throw new IllegalArgumentException(\"null matches\");\n\t\treturn new BitStorePositions(matches, true, 0);\n\t}\n\n\t// available via default BitStore method\n\tstatic Positions newDisjointPositions(Matches matches, int position) {\n\t\tif (matches == null) throw new IllegalArgumentException(\"null matches\");\n\t\tif (position < 0L) throw new IllegalArgumentException();\n\t\t//TODO consider restoring dedicated size accessor on matches\n\t\tif (position > matches.store().size()) throw new IllegalArgumentException();\n\t\tint p = matches.first();\n\t\tint s = matches.sequence().size();\n\t\twhile (p < position) {\n\t\t\tp = matches.next(p + s);\n\t\t}\n\t\treturn new BitStorePositions(matches, true, p);\n\t}\n\n\tstatic int compareNumeric(BitStore a, BitStore b) {\n\t\tListIterator<Integer> as = a.ones().positions(a.size());\n\t\tListIterator<Integer> bs = b.ones().positions(b.size());\n\t\twhile (true) {\n\t\t\tboolean ap = as.hasPrevious();\n\t\t\tboolean bp = bs.hasPrevious();\n\t\t\tif (ap && bp) {\n\t\t\t\tint ai = as.previous();\n\t\t\t\tint bi = bs.previous();\n\t\t\t\tif (ai == bi) continue;\n\t\t\t\treturn ai > bi ? 1 : -1;\n\t\t\t} else {\n\t\t\t\tif (ap) return 1;\n\t\t\t\tif (bp) return -1;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// expects a strictly longer than b\n\tstatic int compareLexical(BitStore a, BitStore b) {\n\t\tint aSize = a.size();\n\t\tint bSize = b.size();\n\t\tint diff = a.size() - b.size();\n\t\tListIterator<Integer> as = a.ones().positions(aSize);\n\t\tListIterator<Integer> bs = b.ones().positions(bSize);\n\t\twhile (true) {\n\t\t\tboolean ap = as.hasPrevious();\n\t\t\tboolean bp = bs.hasPrevious();\n\t\t\tif (ap && bp) {\n\t\t\t\tint ai = as.previous();\n\t\t\t\tint bi = bs.previous() + diff;\n\t\t\t\tif (ai == bi) continue;\n\t\t\t\treturn ai > bi ? 1 : -1;\n\t\t\t} else {\n\t\t\t\treturn bp ? -1 : 1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tstatic boolean isAllOnes(BitStore s) {\n\t\t//TODO could use a reader?\n\t\tint size = s.size();\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tif (!s.getBit(i)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstatic boolean isAllZeros(BitStore s) {\n\t\t//TODO could use a reader?\n\t\tint size = s.size();\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tif (s.getBit(i)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t//duplicated here to avoid dependencies\n\tstatic int gcd(int a, int b) {\n\t\twhile (a != b) {\n\t\t\tif (a > b) {\n\t\t\t\tint na = a % b;\n\t\t\t\tif (na == 0) return b;\n\t\t\t\ta = na;\n\t\t\t} else {\n\t\t\t\tint nb = b % a;\n\t\t\t\tif (nb == 0) return a;\n\t\t\t\tb = nb;\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n\n\tstatic void checkMutable() {\n\t\tthrow new IllegalStateException(\"immutable\");\n\t}\n\n\tstatic void checkMutable(boolean mutable) {\n\t\tif (!mutable) throw new IllegalStateException(\"immutable\");\n\t}\n\n\tstatic void checkPosition(int position, int size) {\n\t\tif (position < 0L) throw new IllegalArgumentException(\"negative position\");\n\t\tif (position > size) throw new IllegalArgumentException(\"position exceeds size\");\n\t}\n\n\tstatic void checkBounds(int finalPos, int initialPos, int size) {\n\t\tif (finalPos < 0) throw new IllegalArgumentException(\"negative finalPos\");\n\t\tif (initialPos < finalPos) throw new IllegalArgumentException(\"finalPos exceeds initialPos\");\n\t\tif (initialPos > size) throw new IllegalArgumentException(\"initialPos exceeds size\");\n\t}\n\n\tstatic void checkBitsLength(int length) {\n\t\tif (length < 0) throw new IllegalArgumentException(\"negative length\");\n\t\tif (length > 64) throw new IllegalArgumentException(\"length exceeds 64\");\n\t}\n\n\tstatic void checkIntBitsLength(int length) {\n\t\tif (length < 0) throw new IllegalArgumentException(\"negative length\");\n\t\tif (length > 32) throw new IllegalArgumentException(\"length exceeds 32\");\n\t}\n\n\tstatic int adjIndex(int index, int start, int finish) {\n\t\tif (index < 0) throw new IllegalArgumentException(\"negative index: \" + index);\n\t\tindex += start;\n\t\tif (index >= finish) throw new IllegalArgumentException(\"index too large: \" + (index - start));\n\t\treturn index;\n\t}\n\n\tstatic int adjPosition(int position, int start, int finish) {\n\t\tif (position < 0) throw new IllegalArgumentException(\"negative position: \" + position);\n\t\tposition += start;\n\t\tif (position > finish) throw new IllegalArgumentException(\"position too large: \" + (position - start));\n\t\treturn position;\n\t}\n\n\t// private static methods\n\n\tprivate static void transferImpl(BitReader reader, BitWriter writer, long count) {\n\t\twhile (count >= 64) {\n\t\t\t//TODO could benefit from reading into a larger buffer here - eg bytes?\n\t\t\tlong bits = reader.readLong(64);\n\t\t\twriter.write(bits, 64);\n\t\t\tcount -= 64;\n\t\t}\n\t\tif (count != 0L) {\n\t\t\tlong bits = reader.readLong((int) count);\n\t\t\twriter.write(bits, (int) count);\n\t\t}\n\t}\n\n\tprivate static void checkSize(int size) {\n\t\tif (size < 0) throw new IllegalArgumentException(\"negative size\");\n\t}\n\n\tprivate static void checkSize(long size, long maxSize) {\n\t\tif (size < 0L) throw new IllegalArgumentException(\"negative size\");\n\t\tif (size > maxSize) throw new IllegalArgumentException(\"size exceeds maximum permitted\");\n\t}\n\n\t// constructor\n\n\tprivate Bits() { }\n\n}", "public class EndOfBitStreamException extends BitStreamException {\n\n\tprivate static final long serialVersionUID = -4892414594243780142L;\n\n\tpublic EndOfBitStreamException() {\n\t}\n\n\tpublic EndOfBitStreamException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic EndOfBitStreamException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic EndOfBitStreamException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}" ]
import static com.tomgibara.streams.Streams.streamInput; import static com.tomgibara.streams.Streams.streamOutput; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.BitSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.SortedSet; import junit.framework.TestCase; import com.tomgibara.bits.AbstractBitStore; import com.tomgibara.bits.BitReader; import com.tomgibara.bits.BitStore; import com.tomgibara.bits.BitStreamException; import com.tomgibara.bits.BitWriter; import com.tomgibara.bits.Bits; import com.tomgibara.bits.EndOfBitStreamException;
package com.tomgibara.bits.sample; public class Examples extends TestCase { public void testExamples() throws IOException { // preamble int distance = 0; boolean fill = false; BigInteger bigInt = BigInteger.ONE; byte[] bytes = new byte[] {}; int[] ints = new int[] {}; int size = 1; BitSet bitSet = new BitSet(); String string = ""; Random random = new Random(0L); int from = 0; int to = 1; BitStore store = Bits.store(1000); BitStore otherStore = Bits.store(1000);
BitReader reader = Bits.zeroBits(100000).openReader();
1
dmillett/prank
src/test/java/net/prank/example/ExampleScoreCard.java
[ "public class Indices\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /** A collection of indices for any object that is subject to multiple sorts */\n private final List<Integer> _indices;\n\n public Indices(int originalIndex) {\n _indices = new ArrayList<>();\n _indices.add(originalIndex);\n }\n\n public int getOriginalIndex() {\n return _indices.get(0);\n }\n\n public int getLastIndex() {\n return _indices.get(_indices.size() - 1);\n }\n\n public List<Integer> getIndices() {\n return new ArrayList<>(_indices);\n }\n\n public void updateWithCurrentIndex(int currentIndex) {\n _indices.add(currentIndex);\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n Indices indices = (Indices) o;\n return _indices.equals(indices._indices);\n }\n\n @Override\n public int hashCode() {\n return _indices.hashCode();\n }\n\n @Override\n public String toString() {\n return \"Indices{\" +\n \"_indices=\" + _indices +\n '}';\n }\n}", "public class RequestOptions {\n\n /** Defaults to 0.0 */\n private final double _minPoints;\n /** Defaults to 10.0 */\n private final double _maxPoints;\n /** Defaults to 10 */\n private final int _bucketCount;\n /** Defaults to 'true' */\n private final boolean _enabled;\n /** Defaults to 50 milliseconds */\n private final long _timeoutMillis;\n\n public RequestOptions(double minPoints, double maxPoints, int bucketCount, boolean enabled, long timeoutMillis) {\n _minPoints = minPoints;\n _maxPoints = maxPoints;\n _bucketCount = bucketCount;\n _enabled = enabled;\n _timeoutMillis = timeoutMillis;\n }\n\n public double getMinPoints() {\n return _minPoints;\n }\n\n public double getMaxPoints() {\n return _maxPoints;\n }\n\n public int getBucketCount() {\n return _bucketCount;\n }\n\n public boolean isEnabled() {\n return _enabled;\n }\n\n public long getTimeoutMillis() {\n return _timeoutMillis;\n }\n\n /**\n * Use this if any of the defaults are acceptable, otherwise specify every value\n * in the RequestOptions constructor. This could be renamed to something simpler,\n * such as Builder, since it is statically referenced from RequestOptions (todo: 2.0)\n */\n public static class RequestOptionsBuilder {\n\n private double _minPointsB = 0.0;\n private double _maxPointsB = 10.0;\n private int _bucketCountB = 10;\n private boolean _enabledB = true;\n private long _timeoutMillisB = 50;\n\n public RequestOptionsBuilder setMinPointsB(double minPointsB) {\n _minPointsB = minPointsB;\n return this;\n }\n\n public RequestOptionsBuilder setMaxPointsB(double maxPointsB) {\n _maxPointsB = maxPointsB;\n return this;\n }\n\n public RequestOptionsBuilder setBucketCountB(int bucketCountB) {\n _bucketCountB = bucketCountB;\n return this;\n }\n\n public RequestOptionsBuilder setEnabledB(boolean enabledB) {\n _enabledB = enabledB;\n return this;\n }\n\n public RequestOptionsBuilder setTimeoutMillisB(long timeoutMillisB) {\n _timeoutMillisB = timeoutMillisB;\n return this;\n }\n\n public RequestOptions build() {\n return new RequestOptions(_minPointsB, _maxPointsB, _bucketCountB, _enabledB, _timeoutMillisB);\n }\n }\n}", "public class Result<T>\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /**\n * ORIGINAL - setupScoring per original scoring\n * ADJUSTED - indicates that an adjustment (+/-/*) may have occurred\n */\n public enum ResultScoreType {\n\n ORIGINAL,\n NORMALIZED,\n ADJUSTED\n }\n\n /** Name of the ScoreCard for this result, corresponds to Prankster 'key' */\n private final String _scoreCardName;\n /** The value to score on (price, shipping time, etc) */\n private final T _scoredValue;\n /** Initial position prior to scoring and ranking */\n private final Indices _indices;\n\n /** Encapsulating score, adjusted score, max points, min points, number of buckets, etc */\n private final ScoreData _score;\n /** Capture average and deviations (mean, median, standard) */\n private final Statistics _statistics;\n\n /**\n * Instantiate directly or use the Builder\n * @param scoreCardName The name of the score card that produced a result\n * @param scoredValue The value that the score card produced\n * @param indices Original index order position\n * @param score The score data specifics\n * @param stats Any statistical measurements for the collection\n */\n public Result(String scoreCardName, T scoredValue, Indices indices, ScoreData score, Statistics stats) {\n\n _scoreCardName = scoreCardName;\n _scoredValue = scoredValue;\n _indices = indices;\n _score = score;\n _statistics = stats;\n }\n\n public String getScoreCardName() {\n return _scoreCardName;\n }\n\n public T getScoredValue() {\n return _scoredValue;\n }\n\n public Indices getPosition() {\n return _indices;\n }\n\n public ScoreData getScoreData() {\n return _score;\n }\n\n public Statistics getStatistics() {\n return _statistics;\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n Result result = (Result) o;\n\n if ( _indices != null ? !_indices.equals(result._indices) : result._indices != null )\n {\n return false;\n }\n\n if ( _score != null ? !_score.equals(result._score) : result._score != null )\n {\n return false;\n }\n\n if ( _scoreCardName != null ? !_scoreCardName.equals(result._scoreCardName) : result._scoreCardName != null )\n {\n return false;\n }\n\n if ( _scoredValue != null ? !_scoredValue.equals(result._scoredValue) : result._scoredValue != null )\n {\n return false;\n }\n\n if ( _statistics != null ? !_statistics.equals(result._statistics) : result._statistics != null )\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _scoreCardName != null ? _scoreCardName.hashCode() : 0;\n result = 31 * result + (_scoredValue != null ? _scoredValue.hashCode() : 0);\n result = 31 * result + (_indices != null ? _indices.hashCode() : 0);\n result = 31 * result + (_score != null ? _score.hashCode() : 0);\n result = 31 * result + (_statistics != null ? _statistics.hashCode() : 0);\n\n return result;\n }\n\n @Override\n public String toString() {\n return \"Result{\" +\n \"_scoreCardName='\" + _scoreCardName + '\\'' +\n \", _scoredValue=\" + _scoredValue +\n \", _position=\" + _indices +\n \", _score=\" + _score +\n \", _statistics=\" + _statistics +\n '}';\n }\n\n /**\n * A helper since the constructor is large.\n */\n public static class Builder<T> {\n\n private String _bCardName;\n private T _bOriginal;\n private Indices _bIndices;\n private ScoreData _bScore;\n private Statistics _bStatistics;\n\n public Builder() {}\n\n public Builder(Result<T> original) {\n\n if (original != null)\n {\n _bCardName = original._scoreCardName;\n _bOriginal = original._scoredValue;\n _bIndices = original._indices;\n _bScore = original._score;\n _bStatistics = original._statistics;\n }\n }\n\n public Builder(String name, ScoreData score) {\n _bCardName = name;\n _bScore = score;\n }\n\n public Builder setPosition(Indices bPosition) {\n _bIndices = bPosition;\n return this;\n }\n\n public Builder setOriginal(T bOriginal) {\n _bOriginal = bOriginal;\n return this;\n }\n\n public Builder setScore(ScoreData bScore) {\n _bScore = bScore;\n return this;\n }\n\n public Builder setStatistics(Statistics bStatistics) {\n _bStatistics = bStatistics;\n return this;\n }\n\n public Builder setCardName(String bCardName) {\n _bCardName = bCardName;\n return this;\n }\n\n public Result build() {\n return new Result<>(_bCardName, _bOriginal, _bIndices, _bScore, _bStatistics);\n }\n }\n}", "public interface ScoreCard<T> {\n\n /**\n * Score a single object with default options\n * @param scoringObject The object to score\n * @return The score summary after scoring\n */\n public ScoreSummary score(T scoringObject);\n /**\n * Score a single object with specified options, otherwise use defaults\n * @param scoringObject The object to score\n * @param options The request specific options to use for scoring\n * @return The score summary\n */\n public ScoreSummary scoreWith(T scoringObject, RequestOptions options);\n\n /**\n * Score and update an object or collection of objects with default options\n * @param scoringObject The object to score\n */\n public void updateObjectsWithScore(T scoringObject);\n /**\n * Score and update an object or collection of objects with specific options\n * @param scoringObject The object to score\n * @param options The request specific scoring parameters\n */\n public void updateObjectsWithScore(T scoringObject, RequestOptions options);\n\n /**\n * A setupScoring card name to use as a key in ScoreSummary\n * The name of the ScoreCard for reporting, applying, etc\n *\n * @return The name of the ScoreCard\n */\n public String getName();\n}", "public class ScoreData\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n\n /** The value given by a ScoreCard */\n private final BigDecimal _score;\n /** The value of adjusting '_score' */\n private final BigDecimal _adjustedScore;\n /** A normalized score (if necessary) */\n private final BigDecimal _normalizedScore;\n /** The number of buckets allocated across the range given by '_minPoints' and '_maxPoints' */\n private final int _buckets;\n /** The maximum possible score */\n private final BigDecimal _maxPoints;\n /** The minimum possible score */\n private final BigDecimal _minPoints;\n\n /**\n * Use this or the builder to create a ScoreData object in your ScoreCard\n * implementation. It represents the details/state of a specific Score\n *\n * @param score The score value\n * @param adjustedScore The adjusted score value\n * @param normalizedScore The normalized score\n * @param buckets The number of scoring buckets between min and max\n * @param maxPoints The maximum points in a group\n * @param minPoints The minimum points in a group\n */\n public ScoreData(BigDecimal score, BigDecimal adjustedScore, BigDecimal normalizedScore, int buckets,\n BigDecimal maxPoints, BigDecimal minPoints) {\n\n _score = score;\n _adjustedScore = adjustedScore;\n _normalizedScore = normalizedScore;\n _buckets = buckets;\n _maxPoints = maxPoints;\n _minPoints = minPoints;\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n ScoreData score = (ScoreData) o;\n\n if ( _buckets != score._buckets )\n {\n return false;\n }\n\n if ( _adjustedScore != null ? !_adjustedScore.equals(score._adjustedScore) : score._adjustedScore != null )\n {\n return false;\n }\n\n if ( _normalizedScore != null ? !_normalizedScore.equals(score._normalizedScore) :\n score._normalizedScore != null )\n {\n return false;\n }\n\n if ( _maxPoints != null ? !_maxPoints.equals(score._maxPoints) : score._maxPoints != null )\n {\n return false;\n }\n\n if ( _minPoints != null ? !_minPoints.equals(score._minPoints) : score._minPoints != null )\n {\n return false;\n }\n\n if ( _score != null ? !_score.equals(score._score) : score._score != null )\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _score != null ? _score.hashCode() : 0;\n result = 31 * result + (_adjustedScore != null ? _adjustedScore.hashCode() : 0);\n result = 31 * result + (_normalizedScore != null ? _normalizedScore.hashCode() : 0);\n result = 31 * result + _buckets;\n result = 31 * result + (_maxPoints != null ? _maxPoints.hashCode() : 0);\n result = 31 * result + (_minPoints != null ? _minPoints.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"ScoreData{\" +\n \"_score=\" + _score +\n \", _adjustedScore=\" + _adjustedScore +\n \", _normalizedScore=\" + _normalizedScore +\n \", _buckets=\" + _buckets +\n \", _maxPoints=\" + _maxPoints +\n \", _minPoints=\" + _minPoints +\n '}';\n }\n\n /**\n * Multiplies the '_score' by a multiplier and returns a new ScoreData object,\n * otherwise returns this\n *\n * @param multiplier A multiplier applied to '_score' if not null\n * @return A new ScoreData object with adjusted score or this\n */\n public ScoreData adjustScore(BigDecimal multiplier) {\n\n if ( multiplier == null || _score == null )\n {\n return this;\n }\n\n BigDecimal adjustedScore = _score.multiply(multiplier);\n return new ScoreData(_score, adjustedScore, _normalizedScore, _buckets, _maxPoints, _minPoints);\n }\n\n /**\n *\n * @return score:adjustedScore:maxPoints:minPoints:buckets\n */\n public String dump() {\n\n ScoreFormatter formatter = new ScoreFormatter();\n return formatter.dumpScoreData(this);\n }\n\n public BigDecimal getScore() {\n return _score;\n }\n\n public BigDecimal getAdjustedScore() {\n return _adjustedScore;\n }\n\n public BigDecimal getNormalizedScore() {\n return _normalizedScore;\n }\n\n public int getBuckets() {\n return _buckets;\n }\n\n public BigDecimal getMaxPoints() {\n return _maxPoints;\n }\n\n public BigDecimal getMinPoints() {\n return _minPoints;\n }\n\n public static class Builder {\n\n private BigDecimal _bScore;\n private BigDecimal _bAdjustedScore;\n private BigDecimal _bNormalizedScore;\n private int _bBuckets;\n private BigDecimal _bMaxPoints;\n private BigDecimal _bMinPoints;\n\n public ScoreData build() {\n return new ScoreData(_bScore, _bAdjustedScore, _bNormalizedScore, _bBuckets, _bMaxPoints, _bMinPoints);\n }\n\n public Builder setScore(BigDecimal score) {\n _bScore = score;\n return this;\n }\n\n public Builder setAdjustedScore(BigDecimal adjustedScore) {\n _bAdjustedScore = adjustedScore;\n return this;\n }\n\n public Builder setNormalizedScore(BigDecimal normalizedScore) {\n _bNormalizedScore = normalizedScore;\n return this;\n }\n\n public Builder setBuckets(int buckets) {\n _bBuckets = buckets;\n return this;\n }\n\n public Builder setMaxPoints(BigDecimal maxPoints) {\n _bMaxPoints = maxPoints;\n return this;\n }\n\n public Builder setMinPoints(BigDecimal minPoints) {\n _bMinPoints = minPoints;\n return this;\n }\n }\n}", "public class ScoreSummary\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n private final Map<String, Result> _results;\n private final String _name;\n\n public ScoreSummary(String name) {\n _name = name;\n _results = new HashMap<>();\n }\n\n public void addResult(String key, Result result) {\n _results.put(key, result);\n }\n\n public Result getResultByScoreCard(String scoreCardName) {\n return _results.get(scoreCardName);\n }\n\n public Map<String, Result> getResults() {\n return _results;\n }\n\n public String getName() {\n return _name;\n }\n\n /**\n * Add up all the scores for each Result.\n *\n * @return The sum of all Result.getScore() or null\n */\n public BigDecimal tallyScore() {\n return tallyScore(_results.keySet(), Result.ResultScoreType.ORIGINAL);\n }\n\n public BigDecimal tallyScore(Result.ResultScoreType scoreType) {\n return tallyScore(_results.keySet(), scoreType);\n }\n\n /**\n * Get the setupScoring for a subset of ScoreCards by name.\n *\n * @param scoreCardNames The names of score cards to apply\n * @return The tallied BigDecimal score\n */\n public BigDecimal tallyScoreFor(Set<String> scoreCardNames) {\n return tallyScoreFor(scoreCardNames, Result.ResultScoreType.ORIGINAL);\n }\n\n /**\n * Tally score based on score cards, by name, and scoring type\n * @param scoreCardNames The score cards to apply\n * @param scoreType The scoring type to use\n * @return The score or 'null'\n */\n // todo: use ScoringTool.tallyScoreFor()?\n public BigDecimal tallyScoreFor(Set<String> scoreCardNames, Result.ResultScoreType scoreType) {\n\n if (scoreCardNames == null)\n {\n return null;\n }\n\n Set<String> scoreCards = findScoreCardsByName(scoreCardNames);\n return tallyScore(scoreCards, scoreType);\n }\n\n /**\n * todo: use ScoringTool.tallyScoreFor()?\n *\n * @param scoreCardNames The names of score cards to apply\n * @param scoreType The score type to use when calculating the score\n * @return null if there are no matching ScoreCards, otherwise the tally(+)\n */\n public BigDecimal tallyScore(Set<String> scoreCardNames, Result.ResultScoreType scoreType) {\n\n if (scoreCardNames.isEmpty())\n {\n return null;\n }\n\n BigDecimal tally = null;\n\n for (String scoreCardName : scoreCardNames)\n {\n if (scoreCardName == null)\n {\n continue;\n }\n\n tally = updateTallyFromResult(scoreType, tally, scoreCardName);\n }\n\n return tally;\n }\n\n private BigDecimal updateTallyFromResult(Result.ResultScoreType scoreType, BigDecimal tally,\n String scoreCardName) {\n\n Result result = _results.get(scoreCardName);\n\n if (result == null) { return tally; }\n\n if (tally == null)\n {\n tally = new BigDecimal(\"0.0\");\n }\n\n if (scoreType.equals(Result.ResultScoreType.ORIGINAL))\n {\n if (result.getScoreData().getScore() != null)\n {\n tally = tally.add(result.getScoreData().getScore());\n }\n }\n else if (scoreType.equals(Result.ResultScoreType.ADJUSTED))\n {\n if (result.getScoreData().getAdjustedScore() != null)\n {\n tally = tally.add(result.getScoreData().getAdjustedScore());\n }\n }\n\n return tally;\n }\n\n /**\n * Flexible way of determining which scores to tally\n *\n * @param scoreCards The names of score cards to apply\n * @return The BigDecimal score result\n */\n public BigDecimal tallyScoreFor(String... scoreCards) {\n return tallyScoreFor(Result.ResultScoreType.ORIGINAL, scoreCards);\n }\n\n /**\n * Flexible way of determining which adjusted scores to tally based on setupScoring type\n * (original or adjusted)\n *\n * @param scoreType Original or Adjusted\n * @param scoreCards The score card names to apply\n * @return The resulting score\n */\n public BigDecimal tallyScoreFor(Result.ResultScoreType scoreType, String... scoreCards) {\n\n if (scoreCards == null || scoreCards.length == 0)\n {\n return null;\n }\n\n return tallyScore(new HashSet<>(Arrays.asList(scoreCards)), scoreType);\n }\n\n /**\n * Find any of these that are currently part of the summary\n */\n private Set<String> findScoreCardsByName(Set<String> scoreCardNames) {\n\n Set<String> scoreCards = new HashSet<>();\n\n for (String scoreCardName : _results.keySet())\n {\n if (scoreCardNames.contains(scoreCardName))\n {\n scoreCards.add(scoreCardName);\n }\n }\n\n return scoreCards;\n }\n\n @Override\n public String toString() {\n return \"ScoreSummary{\" +\n \"_results=\" + _results +\n \", _name='\" + _name + '\\'' +\n '}';\n }\n\n /**\n * Uses ScoreFormatter.dumpResult() for each ScoreCard result.\n * @return A formatted score\n */\n public String dump() {\n\n ScoreFormatter scf = new ScoreFormatter();\n return scf.dumpScoreSummary(this);\n }\n\n @Override\n public boolean equals(Object o) {\n\n if (this == o)\n {\n return true;\n }\n\n if (o == null || getClass() != o.getClass())\n {\n return false;\n }\n\n ScoreSummary that = (ScoreSummary) o;\n\n if (_name != null ? !_name.equals(that._name) : that._name != null)\n {\n return false;\n }\n\n if (_results != null ? !_results.equals(that._results) : that._results != null)\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _results != null ? _results.hashCode() : 0;\n result = 31 * result + (_name != null ? _name.hashCode() : 0);\n return result;\n }\n}", "public class Statistics\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /** The minimum value within a collection */\n private final BigDecimal _min;\n /** The maximum value within a collection */\n private final BigDecimal _max;\n /** The sample size */\n private final int _sampleSize;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _average;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _meanDeviation;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _medianDeviation;\n /** Use your favorite stats library or NumericTools */\n private final BigDecimal _standardDeviation;\n\n public Statistics(BigDecimal min, BigDecimal max, int sampleSize, BigDecimal average,\n BigDecimal meanAbsoluteDeviation,BigDecimal medianAbsoluteDeviation,\n BigDecimal standardDeviation) {\n\n _min = min;\n _max = max;\n _sampleSize = sampleSize;\n _average = average;\n _meanDeviation = meanAbsoluteDeviation;\n _medianDeviation = medianAbsoluteDeviation;\n _standardDeviation = standardDeviation;\n }\n\n public BigDecimal getMin() {\n return _min;\n }\n\n public BigDecimal getMax() {\n return _max;\n }\n\n public int getSampleSize() {\n return _sampleSize;\n }\n\n public BigDecimal getAverage() {\n return _average;\n }\n\n public BigDecimal getMeanDeviation() {\n return _meanDeviation;\n }\n\n public BigDecimal getMedianDeviation() {\n return _medianDeviation;\n }\n\n public BigDecimal getStandardDeviation() {\n return _standardDeviation;\n }\n\n /**\n *\n * Builds a String representation of these values with their\n * original scale. If value is null, then just appends a \":\" delimiter.\n *\n * min:max:sample size:average:mean deviation:median devation:standard deviation\n *\n * Example:\n * :::: // all values are null\n * 40.00:5.31:: // average, mean devation not null\n * 5.10:1.144:1.00:1.654 // no null values\n *\n * Option:\n * Use a custom Formatter and the Statistics object\n *\n * @return A formatted score, statistics, etc\n */\n public String dump() {\n return dump(-1, RoundingMode.UNNECESSARY);\n }\n\n /**\n * Same as dump(), but with a specified scale and RoundingMode.HALF_EVEN\n * @param scale will truncate to value\n * @return A formatted score, statistics, etc\n */\n public String dump(int scale) {\n return dump(scale, null);\n }\n\n /**\n * Same as dump() but with both scale and rounding mode\n * @param scale The scale to use for score format printer\n * @param roundingMode The rounding mode for the score format printer\n * @return A formatted score, statistics, etc\n */\n public String dump(int scale, RoundingMode roundingMode) {\n\n ScoreFormatter formatter = new ScoreFormatter();\n return formatter.dumpStatistics(this, scale, roundingMode);\n }\n\n @Override\n public boolean equals(Object o) {\n\n if ( this == o )\n {\n return true;\n }\n\n if ( o == null || getClass() != o.getClass() )\n {\n return false;\n }\n\n Statistics that = (Statistics) o;\n\n if ( _sampleSize != that._sampleSize )\n {\n return false;\n }\n\n if ( _average != null ? !_average.equals(that._average) : that._average != null )\n {\n return false;\n }\n\n if ( _max != null ? !_max.equals(that._max) : that._max != null )\n {\n return false;\n }\n\n if ( _meanDeviation != null ? !_meanDeviation.equals(that._meanDeviation) : that._meanDeviation != null )\n {\n return false;\n }\n\n if ( _medianDeviation != null ? !_medianDeviation.equals(that._medianDeviation) :\n that._medianDeviation != null )\n {\n return false;\n }\n\n if ( _min != null ? !_min.equals(that._min) : that._min != null )\n {\n return false;\n }\n\n if ( _standardDeviation != null ? !_standardDeviation.equals(that._standardDeviation) :\n that._standardDeviation != null )\n {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n\n int result = _min != null ? _min.hashCode() : 0;\n result = 31 * result + (_max != null ? _max.hashCode() : 0);\n result = 31 * result + _sampleSize;\n result = 31 * result + (_average != null ? _average.hashCode() : 0);\n\n result = 31 * result + (_meanDeviation != null ? _meanDeviation.hashCode() : 0);\n result = 31 * result + (_medianDeviation != null ? _medianDeviation.hashCode() : 0);\n result = 31 * result + (_standardDeviation != null ? _standardDeviation.hashCode() : 0);\n return result;\n }\n\n /** More flexibility for creating a Statistics object. */\n public static class Builder {\n\n private BigDecimal _bMin;\n private BigDecimal _bMax;\n private int _bSampleSize;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bAverage;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bMeanDeviation;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bMedianDeviation;\n /** Use your favorite stats library or NumericTools */\n private BigDecimal _bStandardDeviation;\n\n public Statistics build() {\n return new Statistics(_bMin, _bMax, _bSampleSize, _bAverage, _bMeanDeviation, _bMedianDeviation,\n _bStandardDeviation);\n }\n\n public Builder setMin(BigDecimal bMin) {\n _bMin = bMin;\n return this;\n }\n\n public Builder setSampleSize(int bSampleSize) {\n _bSampleSize = bSampleSize;\n return this;\n }\n\n public Builder setMax(BigDecimal bMax) {\n _bMax = bMax;\n return this;\n }\n\n public Builder setStandardDeviation(BigDecimal bStandardDeviation) {\n _bStandardDeviation = bStandardDeviation;\n return this;\n }\n\n public Builder setAverage(BigDecimal bAverage) {\n _bAverage = bAverage;\n return this;\n }\n\n public Builder setMeanDeviation(BigDecimal bMeanDeviation) {\n _bMeanDeviation = bMeanDeviation;\n return this;\n }\n\n public Builder setMedianDeviation(BigDecimal bMedianDeviation) {\n _bMedianDeviation = bMedianDeviation;\n return this;\n }\n\n }\n}" ]
import net.prank.core.Indices; import net.prank.core.RequestOptions; import net.prank.core.Result; import net.prank.core.ScoreCard; import net.prank.core.ScoreData; import net.prank.core.ScoreSummary; import net.prank.core.Statistics; import java.math.BigDecimal;
package net.prank.example; /** * A very simple example of a setupScoring card. More complex examples should still be stateless for * thread safety. Typically, the higher the setupScoring, the better the result. * <p/> * The adjustments are just examples of how scoring might be adjusted to make some * setupScoring cards more/less important than other setupScoring cards. If machine learning (ML) * indicates that price is the most important factor for all customers (or individual), * then it should have "heavier" weighting and it's setupScoring should be adjusted (+) * <p/> * Examples: * Price: the lowest price has the highest setupScoring. * Shipping cost: how much to ship the item * Shipping time: how long it takes an item to ship * * * @author dmillett * * Copyright 2012 David Millett * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ExampleScoreCard implements ScoreCard<ExampleObject> { private final String _name = "SolutionPriceScoreCard"; // Mutable state (single threaded only) -- D private final int _scoreAdjustment; private final int _positionAdjustment; private final double _averageAdjustment; private final double _standardDeviationAdjustment; public ExampleScoreCard() { _scoreAdjustment = 5; _positionAdjustment = 3; _averageAdjustment = 2; _standardDeviationAdjustment = 1.0; } public ExampleScoreCard(int scoreAdjustment, int positionAdjustment, double averageAdjustment, double standardDeviationAdjustment) { _scoreAdjustment = scoreAdjustment; _positionAdjustment = positionAdjustment; _averageAdjustment = averageAdjustment; _standardDeviationAdjustment = standardDeviationAdjustment; } public ScoreSummary score(ExampleObject scoringObject) { // Ignore the summary for now performScoring(scoringObject); return null; } @Override
public ScoreSummary scoreWith(ExampleObject scoringObject, RequestOptions options) {
1
i2p/i2p.itoopie
src/net/i2p/itoopie/gui/component/chart/InboundBandwidthTracker.java
[ "public class JSONRPC2SessionException extends Exception {\n\n\t\n\t/**\n\t * The exception cause is network or I/O related.\n\t */\n\tpublic static final int NETWORK_EXCEPTION = 1;\n\t\n\t\n\t/**\n\t * Unexpected \"Content-Type\" header value of the HTTP response.\n\t */\n\tpublic static final int UNEXPECTED_CONTENT_TYPE = 2;\n\t\n\t\n\t/**\n\t * Invalid JSON-RPC 2.0 response.\n\t */\n\tpublic static final int BAD_RESPONSE = 3;\n\t\n\t\n\t/**\n\t * Indicates the type of cause for this exception, see\n\t * constants.\n\t */\n\tprivate int causeType;\n\t\n\t\n\t/**\n\t * Creates a new JSON-RPC 2.0 session exception with the specified \n\t * message and cause type.\n\t *\n\t * @param message The message.\n\t * @param causeType The cause type, see the constants.\n\t */\n\tpublic JSONRPC2SessionException(final String message, final int causeType) {\n\t\n\t\tsuper(message);\n\t\tthis.causeType = causeType;\n\t}\n\t\n\t\n\t/**\n\t * Creates a new JSON-RPC 2.0 session exception with the specified \n\t * message, cause type and cause.\n\t *\n\t * @param message The message.\n\t * @param causeType The cause type, see the constants.\n\t * @param cause The original exception.\n\t */\n\tpublic JSONRPC2SessionException(final String message, final int causeType, final Throwable cause) {\n\t\n\t\tsuper(message, cause);\n\t\tthis.causeType = causeType;\n\t}\n\t\n\t\n\t/**\n\t * Returns the exception cause type.\n\t *\n\t * @return The cause type constant.\n\t */\n\tpublic int getCauseType() {\n\t\n\t\treturn causeType;\n\t}\n}", "public class InvalidParametersException extends Exception {\n\n\t/**\n\t * Signifies that the paramers we sent were invalid for the used JSONRPC2\n\t * method.\n\t */\n\tprivate static final long serialVersionUID = 4044188679464846005L;\n\n}", "public class InvalidPasswordException extends Exception {\n\n\t/**\n\t * The remote I2PControl server is rejecting the provided password.\n\t */\n\tprivate static final long serialVersionUID = 8461972369522962046L;\n\n}", "public class GetRateStat{\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static Double execute(String stat, long period)\n\t\t\tthrows InvalidPasswordException, JSONRPC2SessionException, InvalidParametersException {\n\n\t\tJSONRPC2Request req = new JSONRPC2Request(\"GetRate\", JSONRPC2Interface.incrNonce());\n\t\t@SuppressWarnings(\"rawtypes\")\n\t\tMap params = new HashMap();\n\t\tparams.put(\"Stat\", stat);\n\t\tparams.put(\"Period\", period);\n\t\treq.setParams(params);\n\n\t\tJSONRPC2Response resp = null;\n\t\ttry {\n\t\t\tresp = JSONRPC2Interface.sendReq(req);\n\t\t\tHashMap inParams = (HashMap) resp.getResult();\n\t\t\t\n\t\t\tif (inParams == null)\n\t\t\t\treturn 0D;\n\t\t\t\n\t\t\ttry {\n\t\t\t\tDouble dbl = (Double) inParams.get(\"Result\"); \n\t\t\t\treturn dbl;\n\t\t\t} catch (ClassCastException e){\n\t\t\t\tLog _log = LogFactory.getLog(GetRateStat.class);\n\t\t\t\t_log.debug(\"Error: Tried to cast a BigDecimal as Double\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tBigDecimal bigNum = (BigDecimal) inParams.get(\"Result\"); \t\t\t\t\t\n\t\t\t\tDouble dbl = bigNum.doubleValue();\n\t\t\t\treturn dbl;\n\t\t\t} catch (ClassCastException e){\n\t\t\t\tLog _log = LogFactory.getLog(GetRateStat.class);\n\t\t\t\t_log.debug(\"Error: Tried to cast a double as a BigDecimal\");\n\t\t\t} \n\t\t}catch (UnrecoverableFailedRequestException e) {\n\t\t\tLog _log = LogFactory.getLog(GetRateStat.class);\n\t\t\t_log.error(\"getRateStat failed.\", e);\n\t\t}\n\t\treturn new Double(0);\n\t}\n}", "public class GetRouterInfo {\n\tprivate static HashMap<Integer, NETWORK_STATUS> enumMap;\n\t\n\tpublic static enum NETWORK_STATUS{\n\t\tOK\t\t\t\t\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Ok.\"); }},\n\t\tTESTING\t\t\t\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Testing.\"); }},\n\t\tFIREWALLED\t\t\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Firewalled.\"); }},\n\t\tHIDDEN\t\t\t\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Hidden.\"); }},\n\t\tWARN_FIREWALLED_AND_FAST\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Warning, firewalled and fast.\"); }},\n\t\tWARN_FIREWALLED_AND_FLOODFILL\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Warning, firewalled and floodfill.\"); }},\n\t\tWARN_FIREWALLED_WITH_INBOUND_TCP\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Warning, firewalled with inbound TCP enabled.\"); }},\n\t\tWARN_FIREWALLED_WITH_UDP_DISABLED\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Warning, firewalled with UDP disabled.\"); }},\n\t\tERROR_I2CP\t\t\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Error, I2CP issue. Check logs.\"); }},\n\t\tERROR_CLOCK_SKEW\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Error, clock skew. Try setting system clock.\"); }},\n\t\tERROR_PRIVATE_TCP_ADDRESS\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Error, private TCP address.\"); }},\n\t\tERROR_SYMMETRIC_NAT\t\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Error, behind symmetric NAT. Can't recieve connections.\"); }},\n\t\tERROR_UDP_PORT_IN_USE\t\t\t\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Error, UDP port already in use.\"); }},\n\t\tERROR_NO_ACTIVE_PEERS_CHECK_CONNECTION_AND_FIREWALL\t{\tpublic String toString(){ return Transl._t(\"Error, no active peers. Check connection and firewall.\"); }},\n\t\tERROR_UDP_DISABLED_AND_TCP_UNSET\t\t\t\t\t{\tpublic String toString(){ return Transl._t(\"Error, UDP disabled and TCP unset.\"); }}\n\t};\n\t\n\t\n\tstatic {\n\t\tenumMap = new HashMap<Integer, NETWORK_STATUS>();\n\t\tfor (NETWORK_STATUS n : NETWORK_STATUS.values()){\n\t\t\tenumMap.put(n.ordinal(), n);\n\t\t}\n\t}\n\t\n\tpublic static EnumMap<ROUTER_INFO, Object> execute(ROUTER_INFO ... info) \n\t\t\tthrows InvalidPasswordException, JSONRPC2SessionException{\n\n\t\tJSONRPC2Request req = new JSONRPC2Request(\"RouterInfo\", JSONRPC2Interface.incrNonce());\n\t\t@SuppressWarnings(\"rawtypes\")\n\t\tMap outParams = new HashMap();\n\t\tList<ROUTER_INFO> list = Arrays.asList(info);\n\t\t\n\t\tfor (ROUTER_INFO e : list){\n\t\t\tif(e.isReadable()){\n\t\t\t\toutParams.put(e.toString(), null);\n\t\t\t}\n\t\t}\n\n\t\treq.setParams(outParams);\n\n\t\tJSONRPC2Response resp = null;\n\t\ttry {\n\t\t\tresp = JSONRPC2Interface.sendReq(req);\n\t\t\tHashMap map = (HashMap) resp.getResult();\n\t\t\tif (map != null){\n\t\t\t\tSet<Entry> set = map.entrySet();\n\t\t\t\tEnumMap<ROUTER_INFO, Object> output = new EnumMap<ROUTER_INFO, Object>(ROUTER_INFO.class);\n\t\t\t\t// Present the result as an <Enum,Object> map.\n\t\t\t\tfor (Entry e: set){\n\t\t\t\t\tString key = (String) e.getKey();\n\t\t\t\t\tROUTER_INFO RI = RouterInfo.getEnum(key);\n\t\t\t\t\t// If the enum exists. They should exists, but safety first.\n\t\t\t\t\tif (RI != null){\n\t\t\t\t\t\toutput.put(RI, e.getValue());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn output;\n\t\t\t} else {\n\t\t\t\treturn new EnumMap<ROUTER_INFO, Object>(ROUTER_INFO.class);\n\t\t\t}\t\t\n\t\t} catch (UnrecoverableFailedRequestException e) {\n\t\t\tLog _log = LogFactory.getLog(GetRouterInfo.class);\n\t\t\t_log.error(\"getRouterInfo failed.\", e);\n\t\t} catch (InvalidParametersException e) {\n\t\t\tLog _log = LogFactory.getLog(GetRouterInfo.class);\n\t\t\t_log.error(\"Remote host rejected provided parameters: \" + req.toJSON().toJSONString());\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t\n\tpublic static NETWORK_STATUS getEnum(Integer key){\n\t\treturn enumMap.get(key);\n\t}\n}", "public enum ROUTER_INFO implements Remote{\n\tVERSION { \t\t\t\tpublic boolean isReadable(){ return true;}\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.version\"; }},\n\t\t\t\t\t\t\n\tUPTIME { \t\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.uptime\"; }},\n\t\t\t\t\t\t\n\tSTATUS { \t\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.status\"; }},\n\t\t\t\t\t\t\n\tNETWORK_STATUS {\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.net.status\"; }},\n\t\t\n\tBW_INBOUND_1S {\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.net.bw.inbound.1s\"; }},\n\t\t\t\t\t\t\t\n\tBW_INBOUND_15S {\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.net.bw.inbound.15s\"; }},\n\t\t\n\tBW_OUTBOUND_1S {\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.net.bw.outbound.1s\"; }},\n\t\t\t\t\t\t\t\n\tBW_OUTBOUND_15S {\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.net.bw.outbound.15s\"; }},\n\t\t\n\tTUNNELS_PARTICIPATING {\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.net.tunnels.participating\"; }},\n\t\t\t\t\t\n\tKNOWN_PEERS {\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.netdb.knownpeers\"; }},\n\t\t\n\tACTIVE_PEERS {\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.netdb.activepeers\"; }},\n\t\t\t\t\t\t\t\n\tFAST_PEERS {\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.netdb.fastpeers\"; }},\n\t\t\n\tHIGH_CAPACITY_PEERS {\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.netdb.highcapacitypeers\"; }},\n\t\t\t\t\t\t\t\t\n\tIS_RESEEDING {\t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\t\tpublic boolean isWritable(){ return false;} \n\t\t\t\t\t\t\tpublic String toString() { return \"i2p.router.netdb.isreseeding\"; }}\t\t\t\t\t\t\t\t\t\t\t\t\t\n};" ]
import java.util.EnumMap; import java.util.HashMap; import com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException; import net.i2p.itoopie.i2pcontrol.InvalidParametersException; import net.i2p.itoopie.i2pcontrol.InvalidPasswordException; import net.i2p.itoopie.i2pcontrol.methods.GetRateStat; import net.i2p.itoopie.i2pcontrol.methods.GetRouterInfo; import net.i2p.itoopie.i2pcontrol.methods.RouterInfo.ROUTER_INFO;
package net.i2p.itoopie.gui.component.chart; public class InboundBandwidthTracker extends Thread implements Tracker { /** Last read bw */ private double m_value = 0; private final int updateInterval; private volatile boolean running; /** * Start daemon that checks to current inbound bandwidth of the router. */ public InboundBandwidthTracker(int interval) { super("IToopie-IBT"); updateInterval = interval; this.setDaemon(true); this.start(); } /** * @see java.lang.Runnable#run() */ @Override public void run() { running = true; while (running) { runOnce(); try { Thread.sleep(updateInterval); } catch (InterruptedException e) { break; } } } public synchronized void runOnce(){ try {
EnumMap<ROUTER_INFO, Object> em = GetRouterInfo.execute(ROUTER_INFO.BW_INBOUND_1S);
4
itsJoKr/LocalNetwork
localnet/src/main/java/dev/jokr/localnet/ServerService.java
[ "public class DiscoveryReply implements Serializable {\n\n private String ip;\n private int port;\n\n public DiscoveryReply(String ip, int port) {\n this.ip = ip;\n this.port = port;\n }\n\n public String getIp() {\n return ip;\n }\n\n public int getPort() {\n return port;\n }\n}", "public class ConnectedClients {\n\n private HashMap<Long, RegisterMessage> registeredClients;\n\n public ConnectedClients(HashMap<Long, RegisterMessage> registeredClients) {\n this.registeredClients = registeredClients;\n }\n\n public Payload<?> getPayload(int clientId) {\n if (registeredClients.containsKey(clientId))\n return registeredClients.get(clientId).getPayload();\n else\n return null;\n }\n\n public Set<Long> getAllClientsIds() {\n return registeredClients.keySet();\n }\n\n public int getClientsSize() {\n return registeredClients.size();\n }\n\n}", "public class Payload<T> implements Serializable {\n\n private T payload;\n\n public Payload(T payload) {\n this.payload = payload;\n }\n\n public T getPayload() {\n return payload;\n }\n\n\n}", "public class RegisterMessage implements Serializable {\n\n private Payload<?> payload;\n private String ip;\n private int port;\n\n public RegisterMessage(Payload<?> payload, String ip, int port) {\n this.payload = payload;\n this.ip = ip;\n this.port = port;\n }\n\n public String getIp() {\n return ip;\n }\n\n public int getPort() {\n return port;\n }\n\n public Payload<?> getPayload() {\n return payload;\n }\n}", "public class SessionMessage implements Serializable {\n\n public static final int NONE = 0;\n public static final int START = 1;\n public static final int END = 2;\n\n private Payload<?> payload;\n private int signal;\n\n\n public SessionMessage(Payload<?> payload) {\n this.payload = payload;\n this.signal = NONE;\n }\n\n public SessionMessage(Payload<?> payload, int signal) {\n this.payload = payload;\n this.signal = signal;\n }\n\n public int getSignal() {\n return signal;\n }\n\n public Payload<?> getPayload() {\n return payload;\n }\n}", "public class NetworkUtil {\n\n\n // My favourite number. We need hardcoded port because we cannot broadcast over all ports\n public static final int BASE_PORT = 52100;\n\n /**\n * Checks to see if a specific port is available.\n *\n * @param port the port to check for availability\n */\n public static boolean available(int 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) {\n ds.close();\n }\n\n if (ss != null) {\n try {\n ss.close();\n } catch (IOException e) {\n /* should not be thrown */\n }\n }\n }\n\n return false;\n }\n\n\n public static long getIdFromIpAddress(String ipAddr) {\n int[] ip = new int[4];\n String[] parts = ipAddr.split(\"\\\\.\");\n\n for (int i = 0; i < 4; i++) {\n ip[i] = Integer.parseInt(parts[i]);\n }\n\n long ipNumbers = 0;\n for (int i = 0; i < 4; i++) {\n ipNumbers += ip[i] << (24 - (8 * i));\n }\n\n return ipNumbers;\n }\n}" ]
import android.app.Notification; import android.app.Service; import android.content.Intent; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.NotificationCompat; import android.text.format.Formatter; import android.util.Log; import java.util.HashMap; import dev.jokr.localnet.discovery.models.DiscoveryReply; import dev.jokr.localnet.models.ConnectedClients; import dev.jokr.localnet.models.Payload; import dev.jokr.localnet.models.RegisterMessage; import dev.jokr.localnet.models.SessionMessage; import dev.jokr.localnet.utils.NetworkUtil;
package dev.jokr.localnet; /** * Created by JoKr on 8/28/2016. */ public class ServerService extends Service implements ServerSocketThread.ServiceCallback, Communicator { public static final String ACTION = "action"; public static final int NOTIFICATION_ID = 521; // Keys for extras public static final String CLASS = "class"; public static final String BUNDLE = "bundle"; public static final String PAYLOAD = "payload"; // Possible service actions: public static final int START_SESSION = 1; public static final int SESSION_EVENT = 2; private HashMap<Long, RegisterMessage> registeredClients; private LocalSession session; private LocalBroadcastManager manager; private Thread serverSocketThread; private Thread discoverySocketThread; @Override public void onCreate() { super.onCreate(); this.manager = LocalBroadcastManager.getInstance(this); registeredClients = new HashMap<>(); serverSocketThread = new Thread(new ServerSocketThread(this)); serverSocketThread.start(); runServiceInForeground(); } /* Multiple calls to Context.startService() will result in multiple calls to onStartCommand, but only one call to onCreate, so we use it as a way to send data to Service. */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("USER", "onStartCommand called"); int action = intent.getIntExtra(ACTION, 0); processAction(action, intent); return START_NOT_STICKY; } private void processAction(int action, Intent intent) { if (action == 0) return; if (action == START_SESSION) startSession((Class) intent.getSerializableExtra(CLASS), intent.getBundleExtra(BUNDLE)); else if (action == SESSION_EVENT) session.onEvent((Payload<?>) intent.getSerializableExtra(PAYLOAD)); } private void startSession(Class c, Bundle b) { try { Object o = c.newInstance(); if (!LocalSession.class.isInstance(o)) { throw new IllegalArgumentException("Class " + c.getName() + " is not instance of LocalSession"); } session = (LocalSession) o; session.preCreateInit(this); session.onCreate(b, new ConnectedClients(registeredClients)); sendSessionStartMessage(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } private void sendSessionStartMessage() { SessionMessage message = new SessionMessage(null, SessionMessage.START); for (RegisterMessage client : registeredClients.values()) { Thread t = new Thread(new SendHandler(message, client.getIp(), client.getPort())); t.start(); } } private void runServiceInForeground() { Notification notification = new NotificationCompat.Builder(this) .setContentTitle("LocalNet Session") .setContentText("Session is currently running") .setSmallIcon(R.drawable.ic_play_circle_filled_black_24dp) .build(); startForeground(NOTIFICATION_ID, notification); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onInitializedSocket(int port) { discoverySocketThread = new Thread(new DiscoverySocketThread(new DiscoveryReply(getLocalIp(), port))); discoverySocketThread.start(); } @Override public void onClientConnected(RegisterMessage message) { Log.d("USER", "onClientConnected: " + message.getPayload());
Long id = NetworkUtil.getIdFromIpAddress(message.getIp());
5
bigjelly/AndFast
app/src/main/java/com/andfast/app/view/common/TabManager.java
[ "public class AndFastApplication extends Application {\n\n private final static String TAG = \"AndFastApplication\";\n private static Context mContext;\n\n @Override\n public void onCreate() {\n super.onCreate();\n mContext = getApplicationContext();\n StorageUtils.initExtDir(getApplicationContext());\n initLog();\n CrashHandler.getInstance().init(getApplicationContext());\n LogUtils.i(TAG,\"<><><><><><><><><>\");\n LogUtils.i(TAG,\" app is start!\");\n LogUtils.i(TAG,\"<><><><><><><><><>\");\n }\n\n private void initLog() {\n LogUtils.setRootTag(\"andfast\");\n LogUtils.setLogPath(StorageUtils.getLogDir());\n LogUtils.setSaveRuntimeInfo(true);\n LogUtils.setAutoSave(true);\n LogUtils.setDebug(BuildConfig.LOG_DEBUG);\n }\n\n public static Context getContext(){\n return mContext;\n }\n}", "public class GeneralID {\n\n /**接口根地址*/\n public static final String BASE_SERVER_URL = \"http://is.snssdk.com/\";\n\n /**\n * 页面间参数传递KEY值\n */\n public class Extra {\n public static final String TAB = \"tab\";\n }\n\n public final static int TYPE_PULL_REFRESH = 1;\n public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1;\n\n /**网络请求异常code*/\n public final static int TYPE_NET_UNAVAILABLE_CODE = 1004;\n public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1;\n\n // EventBus Code\n public static final class EventCode {\n public static final int TEST = 0x8858111;\n }\n}", "public class LogUtils {\n private final static int LOG_LENGTH = 3500;\n private static int MAX_DIR_SIZE = 30 * 1024 * 1024; // 30M\n private static int MAX_FILE_SIZE = 10 * 1024 * 1024;// 10M\n private static int MAX_SAVE_DAY = 7;// 7 Day\n private static boolean sDebug = true;// true output log, false not output log\n private static boolean sAutoSave = false;// true auto save log to file\n private static boolean sSaveRuntimeInfo = false;// true auto save process/thread Id to file\n private static final String PATH_DATA_LOGS = \"/data/Logs/\";\n private static final String PATH_DATA_LOGS_COMMON = PATH_DATA_LOGS + \"common/\";\n private static volatile String PATH_LOGS_DIR = null;\n private static volatile String ROOT_TAG = \"LogUtils\";\n private static final String FILE_NAME_SPLIT = \".\";\n private static volatile ExecutorService sExecutorService = Executors.newSingleThreadExecutor();\n\n /**\n * set debug switch.\n *\n * @param debug true output log, false don't output log.\n **/\n public static void setDebug(boolean debug) {\n sDebug = debug;\n }\n\n /**\n * set autoSave switch.\n *\n * @param save true auto to save log msg.\n **/\n public static void setAutoSave(boolean save) {\n sAutoSave = save;\n }\n\n /**\n * set save process/thread ID switch.\n *\n * @param save true save process/thread ID to file.\n **/\n public static void setSaveRuntimeInfo(boolean save) {\n sSaveRuntimeInfo = save;\n }\n\n /**\n * set log root tag.\n *\n * @param rootTag\n **/\n public static void setRootTag(String rootTag) {\n ROOT_TAG = rootTag;\n }\n\n /**\n * set log path.\n *\n * @param path the absolutePath of log.\n **/\n public static void setLogPath(String path) {\n if (null == path) {\n is(ROOT_TAG, \"setLogPath with path null\");\n return;\n }\n\n PATH_LOGS_DIR = path;\n if (!PATH_LOGS_DIR.endsWith(File.separator)) {\n PATH_LOGS_DIR += File.separator;\n }\n\n chmod777(PATH_LOGS_DIR);\n }\n\n /**\n * set log path of /data/Logs/common/xxx.\n *\n * @param path the relative path of log.\n **/\n public static void setLogPath2Data(String path) {\n if (null == path) {\n is(ROOT_TAG, \"setLogPath2Data with path null\");\n return;\n }\n\n PATH_LOGS_DIR = PATH_DATA_LOGS_COMMON + path;\n if (!PATH_LOGS_DIR.endsWith(File.separator)) {\n PATH_LOGS_DIR += File.separator;\n }\n\n chmod777(PATH_LOGS_DIR);\n }\n\n public static String getLogPath() {\n return PATH_LOGS_DIR;\n }\n\n /**\n * set max size of log dir.\n *\n * @param logDirSize log dir size, unit Byte.\n **/\n public static void setLogDirSize(int logDirSize) {\n if (logDirSize > 0 && logDirSize < MAX_DIR_SIZE) {\n MAX_DIR_SIZE = logDirSize;\n is(ROOT_TAG, \"set MAX_DIR_SIZE \" + logDirSize);\n\n if (MAX_FILE_SIZE > logDirSize) {\n MAX_FILE_SIZE = logDirSize;\n is(ROOT_TAG, \"set MAX_FILE_SIZE \" + logDirSize);\n }\n }\n }\n\n /**\n * set max size of single log file.\n *\n * @param logFileSize log file size, unit Byte.\n **/\n public static void setLogFileSize(int logFileSize) {\n if (logFileSize > 0 && logFileSize < MAX_FILE_SIZE) {\n MAX_FILE_SIZE = logFileSize;\n is(ROOT_TAG, \"set MAX_FILE_SIZE \" + logFileSize);\n }\n }\n\n /**\n * set max day of save log.\n *\n * @param day max save day, unit day.\n **/\n public static void setLogSaveDay(int day) {\n if (day > 0 && day < 7) {\n MAX_SAVE_DAY = day;\n is(ROOT_TAG, \"set MAX_SAVE_DAY \" + day);\n }\n }\n\n\n /**\n * Send a VERBOSE log message.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void v(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.v(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n if (sAutoSave) {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send a VERBOSE log message and save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void vs(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.v(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n log2File(tag, msg);\n }\n\n /**\n * Send a VERBOSE log message and log the exception.\n *\n * @param tag model.\n * @param msg The message you would like logged.\n * @param tr An exception to log.\n */\n public static void v(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.v(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (sAutoSave) {\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n }\n\n /**\n * Send a VERBOSE log message and log the exception, save to file.\n *\n * @param tag model.\n * @param msg The message you would like logged.\n * @param tr An exception to log.\n */\n public static void vs(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.v(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send a DEBUG log message.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void d(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.d(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n if (sAutoSave) {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send a DEBUG log message and save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void ds(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.d(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n log2File(tag, msg);\n }\n\n /**\n * Send a DEBUG log message and log the exception.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log.\n */\n public static void d(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.d(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (sAutoSave) {\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n }\n\n /**\n * Send a DEBUG log message and log the exception, save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log.\n */\n public static void ds(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.d(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send an INFO log message.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void i(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n if (sAutoSave) {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send an INFO log message and save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void is(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n log2File(tag, msg);\n }\n\n /**\n * Send an INFO log message and log the exception.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log.\n */\n public static void i(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (sAutoSave) {\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n }\n\n /**\n * Send an INFO log message and log the exception, save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log.\n */\n public static void is(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send a WARN log message.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void w(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.w(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n if (sAutoSave) {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send a WARN log message and save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void ws(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.w(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n log2File(tag, msg);\n }\n\n /**\n * Send a WARN log message and log the exception.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static void w(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.w(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (sAutoSave) {\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n }\n\n /**\n * Send a WARN log message and log the exception, save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static void ws(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n if (sDebug) {\n Log.w(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send a WARN log message and log the exception.\n *\n * @param tag Used to identify the source of a log message.\n * @param tr An exception to log\n */\n public static void w(String tag, Throwable tr) {\n if (sDebug) {\n Log.w(ROOT_TAG, \"[ \"+tag + \" ]\" + tr);\n }\n\n if (sAutoSave) {\n if (null != tr) {\n log2File(tag, tr.getMessage());\n }\n }\n }\n\n /**\n * Send a WARN log message and log the exception, save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param tr An exception to log\n */\n public static void ws(String tag, Throwable tr) {\n if (sDebug) {\n Log.w(ROOT_TAG, \"[ \"+tag + \" ]\" + tr);\n }\n\n if (null != tr) {\n log2File(tag, tr.getMessage());\n }\n }\n\n /**\n * Send an ERROR log message.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void e(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n if (sAutoSave) {\n log2File(tag, msg);\n }\n }\n\n /**\n * Send an ERROR log message and save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n */\n public static void es(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + msg);\n }\n\n log2File(tag, msg);\n }\n\n /**\n * Send a ERROR log message and log the exception.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static void e(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (sAutoSave) {\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr);\n } else {\n log2File(tag, msg);\n }\n }\n }\n\n /**\n * Send a ERROR log message and log the exception, save to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static void es(String tag, String msg, Throwable tr) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n if (sDebug) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + msg, tr);\n }\n\n if (null != tr) {\n log2File(tag, msg + \"\\n\" + tr.getMessage());\n } else {\n log2File(tag, msg);\n }\n }\n\n public static void s(String tag, String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n log2File(tag, msg);\n }\n\n /**\n * save log to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg the message to save.\n **/\n public synchronized static void log2File(final String tag, final String msg) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n final StringBuilder stringBuilder = new StringBuilder();\n if (sSaveRuntimeInfo) {\n stringBuilder.append(getRuntimeInfo());\n }\n stringBuilder.append(tag);\n\n try {\n sExecutorService.execute(new Runnable() {\n @Override\n public void run() {\n if (-1 == handleLog(tag)) {\n return;\n }\n String logDir = getLogDir();\n if (null == logDir) {\n return;\n }\n File logDirFile = new File(logDir);\n if (!logDirFile.exists() || !logDirFile.isDirectory()) {\n return;\n }\n\n String file = getFilePath(logDir);\n if (TextUtils.isEmpty(file)) {\n return;\n }\n\n File f = new File(logDir + file);\n save2File(stringBuilder.toString(), msg, f);\n }\n });\n } catch (Exception ex) {\n Log.i(ROOT_TAG, \"log2File exception \" + ex.getMessage());\n }\n }\n\n /**\n * get the file path to save log.\n *\n * @param dirPath the parent dir of log.\n **/\n private static String getFilePath(String dirPath) {\n if (null == PATH_LOGS_DIR) {\n return null;\n }\n\n Date d = new Date(System.currentTimeMillis());\n String filePath = formatTime(d.getTime(), \"yyyyMMdd\");\n\n File dirFile = new File(dirPath);\n File[] files = dirFile.listFiles();\n List<String> todayLogList = new ArrayList<String>();\n\n for (File file : files) {\n if (file.getName().contains(filePath)) {\n todayLogList.add(file.getName());\n }\n }\n\n if (todayLogList.size() == 0) {// not has log current day\n return filePath;\n } else {// has log\n if (todayLogList.size() == 1) {// has one log\n File file = new File(PATH_LOGS_DIR + todayLogList.get(0));\n File newFile = new File(PATH_LOGS_DIR + filePath);\n\n // if current day has one log but name not match as 20170524. create new file\n if (!file.getName().equals(filePath)) {\n boolean isSuccess = copyFile(file, newFile);\n Log.i(ROOT_TAG, \"copy file \" + file.getAbsolutePath() + \" destFile \" +\n newFile.getAbsolutePath() + \" return \" + isSuccess);\n if (isSuccess) {\n file.delete();\n } else {\n newFile = file;\n }\n }\n\n // if file large than MAX_FILE_SIZE, return a new file\n if (newFile.length() >= MAX_FILE_SIZE) {\n Log.i(ROOT_TAG, \"file size limit, create new file\");\n return filePath + FILE_NAME_SPLIT + \"01\";\n }\n } else {// has more than one log\n // sort log file from small to large\n Collections.sort(todayLogList, new Comparator<String>() {\n @Override\n public int compare(String lhs, String rhs) {\n return lhs.compareTo(rhs);\n }\n });\n\n // more than one log , reName as 20170524 2017052401 2017052402...\n for (int i = 0; i < todayLogList.size(); i++) {\n String oldFilePath = todayLogList.get(i);\n String newFilePath;\n if (i == 0) {\n newFilePath = filePath;\n } else {\n newFilePath = filePath + FILE_NAME_SPLIT + String.format(\"%02d\", i);\n }\n\n File oldFile = new File(PATH_LOGS_DIR + oldFilePath);\n File newFile = new File(PATH_LOGS_DIR + newFilePath);\n\n if (!oldFilePath.equals(newFilePath)) {\n boolean isSuccess = copyFile(oldFile, newFile);\n Log.i(ROOT_TAG, \"copy file \" + oldFile.getAbsolutePath() + \" destFile \"\n + newFile.getAbsolutePath() + \" return \" + isSuccess);\n if (isSuccess) {\n oldFile.delete();\n } else {\n newFile = oldFile;\n }\n }\n\n // return file path for save\n if (todayLogList.size() - 1 == i) {\n if (newFile.length() >= MAX_FILE_SIZE) {\n return filePath + FILE_NAME_SPLIT + String.format(\"%02d\", i + 1);\n } else {\n return newFilePath;\n }\n }\n }\n }\n }\n\n return filePath;\n }\n\n /**\n * save message to file.\n *\n * @param tag Used to identify the source of a log message.\n * @param msg the message to save.\n * @param file the file to save.\n **/\n private static void save2File(String tag, String msg, File file) {\n if (TextUtils.isEmpty(msg)) {\n return;\n }\n\n FileWriter writer = null;\n try {\n if (!file.exists()) {\n boolean isCreated = file.createNewFile();\n if (isCreated) {\n chmod777(file.getPath());\n } else {\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + \"createNewFile() failed:\" + file.getPath());\n return;\n }\n }\n writer = new FileWriter(file, true);\n writer.write(formatTime(System.currentTimeMillis(), \"yyyyMMdd HH:mm:ss.SSS\") + \" \" + tag\n + \", \" + msg + \"\\n\");\n writer.flush();\n } catch (IOException e) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + \"\", e);\n } finally {\n if (null != writer) {\n try {\n writer.close();\n } catch (IOException e) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + \"\", e);\n }\n }\n }\n }\n\n /**\n * pre process the log dir.\n *\n * @param tag Used to identify the source of a log message.\n **/\n private static int handleLog(String tag) {\n String logDir = getLogDir();\n if (null == logDir) {\n return 0;\n }\n File f = new File(logDir);\n if (!f.exists()) {\n return 0;\n }\n if (!f.isDirectory()) {\n f.delete();\n f.mkdirs();\n }\n if (!f.exists() || !f.isDirectory()) {\n return 0;\n }\n\n // 1.date format, if not match, delete it. correct example 20170524 20170524.01 20170524.99\n // 2.if file is old than current time Subtract the max save day, delete it\n File[] files = f.listFiles();\n for (File file : files) {\n String name = file.getName();\n if (null == name || !(8 == name.length() || 11 == name.length())) {\n file.delete();\n continue;\n }\n Date date = parseTime(tag, name.substring(0, 8), \"yyyyMMdd\");\n if (null != date) {\n long time = date.getTime();\n if (0 == time || System.currentTimeMillis() - time >= MAX_SAVE_DAY * 24 * 60 * 60 * 1000) {\n file.delete();\n }\n } else {\n file.delete();\n }\n }\n // dir size limit, if log dir size > MAX_DIR_SIZE, try to delete old file\n long dirSize = getDirSize(f);\n while (dirSize > (MAX_DIR_SIZE / 1024 / 1024)) {\n files = f.listFiles();\n try {\n int index = 0;\n String tmpFileName = files[0].getName();\n for (int i = 0; i < files.length; i++) {\n String tmpFileName1 = files[i].getName();\n if (tmpFileName.compareTo(tmpFileName1) > 0) {\n tmpFileName = tmpFileName1;\n index = i;\n }\n }\n if (files[index].exists()) {\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + \"log dir is too large and delete old files:\"\n + files[index].getAbsolutePath());\n boolean success = files[index].delete();\n Log.i(ROOT_TAG, \"[ \"+tag + \" ]\" + \"delete \" + success);\n if (!success) {\n return -1;\n }\n }\n } catch (NumberFormatException e) {\n e.printStackTrace();\n }\n dirSize = getDirSize(f);\n }\n return 0;\n }\n\n /**\n * get file size.\n *\n * @param file file to get size.\n * @return size of file, unit MB.\n **/\n private static long getDirSize(File file) {\n if (file == null || !file.exists()) {\n return 0;\n }\n\n long size = 0;\n try {\n if (file.isDirectory()) {\n File[] children = file.listFiles();\n for (File f : children)\n size += getDirSize(f);\n } else {\n size = file.length() / 1024 / 1024;\n }\n } catch (ArrayIndexOutOfBoundsException e) {\n Log.i(ROOT_TAG, \"ArrayIndexOutOfBoundsException: \" + e.getMessage());\n } catch (Exception e) {\n Log.i(ROOT_TAG, \"Exception: \" + e.getMessage());\n }\n\n return size;\n }\n\n /**\n * get log dir.\n *\n * @return path of log dir.\n **/\n private static String getLogDir() {\n if (null == PATH_LOGS_DIR) {\n return null;\n }\n\n String path = PATH_LOGS_DIR;\n File pathFile = new File(path);\n boolean isNewCreated = false;\n if (!pathFile.exists()) {\n pathFile.mkdirs();\n isNewCreated = true;\n }\n\n if (pathFile.exists() && !pathFile.isDirectory()) {\n pathFile.delete();\n pathFile.mkdirs();\n isNewCreated = true;\n }\n\n if (!pathFile.exists() || !pathFile.isDirectory()) {\n path = null;\n } else if (isNewCreated) {\n chmod777(PATH_DATA_LOGS);\n chmod777(PATH_DATA_LOGS_COMMON);\n chmod777(PATH_LOGS_DIR);\n }\n return path;\n }\n\n /**\n * format time.\n *\n * @param time time need to be format.\n * @param format time format.\n * @return time string after format.\n **/\n private static String formatTime(long time, String format) {\n return new SimpleDateFormat(format, Locale.getDefault()).format(new Date(time));\n }\n\n /**\n * get date from time string.\n *\n * @param tag Used to identify the source of a log message.\n * @param time time string.\n * @param template time string format.\n * @return date after format.\n **/\n private static Date parseTime(String tag, String time, String template) {\n SimpleDateFormat format = new SimpleDateFormat(template, Locale.getDefault());\n try {\n return format.parse(time);\n } catch (ParseException e) {\n Log.e(ROOT_TAG, \"[ \"+tag + \" ]\" + \"ParseException: \" + e.getMessage(), e);\n }\n return null;\n }\n\n /**\n * chmod of file.\n *\n * @param path the file path need to chmod.\n **/\n private static void chmod777(String path) {\n Log.d(ROOT_TAG, \"chmod -R 777 \" + path);\n Process proc = null;\n BufferedReader in = null;\n BufferedReader err = null;\n PrintWriter out = null;\n try {\n proc = Runtime.getRuntime().exec(\"sh\");\n if (proc != null) {\n in = new BufferedReader(new InputStreamReader(proc.getInputStream()));\n err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));\n out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(\n proc.getOutputStream())), true);\n out.println(\"chmod -R 777 \" + path);\n out.println(\"exit\");\n }\n } catch (IOException e) {\n Log.e(ROOT_TAG, \"chmod() IOException: \" + e.getMessage());\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {\n }\n }\n if (err != null) {\n try {\n err.close();\n } catch (IOException e) {\n }\n }\n if (out != null) {\n out.close();\n }\n if (proc != null) {\n try {\n int exitValue = proc.exitValue();\n Log.d(ROOT_TAG, \"chmod() exitValue :\" + exitValue);\n } catch (IllegalThreadStateException e) {\n }\n proc = null;\n }\n }\n }\n\n /**\n * copy file.\n *\n * @param resFile source file.\n * @param desFile destFile.\n */\n private static boolean copyFile(File resFile, File desFile) {\n FileChannel inc = null;\n FileChannel out = null;\n RandomAccessFile fos = null;\n FileInputStream in = null;\n boolean isSuccess = false;\n try {\n if (!resFile.exists()) {\n Log.i(ROOT_TAG, \"resFile not exist\" + resFile.getAbsolutePath());\n return false;\n }\n if (desFile.exists()) {\n desFile.delete();\n }\n desFile.createNewFile();\n chmod777(desFile.getAbsolutePath());\n\n fos = new RandomAccessFile(desFile, \"rw\");\n in = new FileInputStream(resFile);\n inc = in.getChannel();\n out = fos.getChannel();\n\n ByteBuffer bb = ByteBuffer.allocate(1024 * 100);\n int read = 0;\n int cursum = 0;\n while ((read = inc.read(bb)) != -1) {\n bb.flip();\n out.write(bb);\n bb.clear();\n cursum += read;\n if (cursum >= 1024 * 128) {\n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n cursum = 0;\n }\n }\n if (fos.getFD().valid()) {\n fos.getFD().sync();\n }\n isSuccess = true;\n } catch (FileNotFoundException fileNotFoundException) {\n fileNotFoundException.printStackTrace();\n Log.i(ROOT_TAG, \"FileNotFoundException\" + fileNotFoundException.getMessage());\n } catch (IOException ioException) {\n ioException.printStackTrace();\n Log.i(ROOT_TAG, \"IOException\" + ioException.getMessage());\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (final IOException e) {\n e.printStackTrace();\n }\n }\n if (inc != null) {\n try {\n inc.close();\n } catch (final IOException e) {\n e.printStackTrace();\n }\n }\n if (out != null) {\n try {\n out.close();\n } catch (final IOException e) {\n e.printStackTrace();\n }\n }\n if (fos != null) {\n try {\n fos.close();\n } catch (final IOException e) {\n e.printStackTrace();\n }\n }\n }\n return isSuccess;\n }\n\n /**\n * get runtime Info.\n */\n private static String getRuntimeInfo() {\n return getProcessId() + \"/\" + getThreadId() + \" \";\n }\n\n /**\n * get current process Id.\n *\n * @return processId.\n */\n private static int getProcessId() {\n return android.os.Process.myPid();\n }\n\n /**\n * get current thread Id.\n *\n * @return threadId.\n */\n private static long getThreadId() {\n return Thread.currentThread().getId();\n }\n}", "public class MainActivity extends BaseActivity {\n\n private static final String TAG = \"MainActivity\";\n private long mKeyTime = 0;\n TabManager mTabManager;\n\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n mTabManager.changeTab(intent);\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n }\n\n @Override\n protected void initView() {\n TabLayout tabLayout = findView(R.id.tl_main_tabs);\n // 初始化底部的view\n mTabManager = TabManager.getInstance(getApplicationContext());\n mTabManager.initTabs(this,getIntent(),tabLayout);\n }\n\n @Override\n protected void initData() {\n }\n\n @Override\n protected int getContentView() {\n return R.layout.act_main;\n }\n\n\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n if (KeyEvent.KEYCODE_BACK == keyCode && event.getAction() == KeyEvent.ACTION_DOWN) {\n if ((System.currentTimeMillis() - mKeyTime) > 2000) {\n mKeyTime = System.currentTimeMillis();\n Toast.makeText(getApplicationContext(), \"确定要离开吗?\", Toast.LENGTH_SHORT).show();\n } else {\n finish();\n System.exit(0);\n }\n return true;\n }\n return super.onKeyDown(keyCode, event);\n }\n}", "public class SpacingTextView extends AppCompatTextView {\n private float letterSpacing = LetterSpacing.BIGGEST;\n private CharSequence originalText = \"\";\n\n\n public SpacingTextView(Context context) {\n super(context);\n }\n\n public SpacingTextView(Context context, AttributeSet attrs){\n super(context, attrs);\n originalText = super.getText();\n applyLetterSpacing();\n this.invalidate();\n }\n\n public SpacingTextView(Context context, AttributeSet attrs, int defStyle){\n super(context, attrs, defStyle);\n }\n\n public float getLetterSpacing() {\n return letterSpacing;\n }\n\n public void setLetterSpacing(float letterSpacing) {\n this.letterSpacing = letterSpacing;\n applyLetterSpacing();\n }\n\n @Override\n public void setText(CharSequence text, BufferType type) {\n originalText = text;\n applyLetterSpacing();\n }\n\n @Override\n public CharSequence getText() {\n return originalText;\n }\n\n /**\n * 字距为任何字符串(技术上,一个简单的方法为CharSequence不使用)的TextView\n */\n private void applyLetterSpacing() {\n if (this == null || this.originalText == null) return;\n StringBuilder builder = new StringBuilder();\n for(int i = 0; i < originalText.length(); i++) {\n String c = \"\"+ originalText.charAt(i);\n builder.append(c.toLowerCase());\n if(i+1 < originalText.length()) {\n builder.append(\"\\u00A0\");\n }\n }\n SpannableString finalText = new SpannableString(builder.toString());\n if(builder.toString().length() > 1) {\n for(int i = 1; i < builder.toString().length(); i+=2) {\n finalText.setSpan(new ScaleXSpan((letterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);\n }\n }\n super.setText(finalText, BufferType.SPANNABLE);\n }\n\n public class LetterSpacing {\n public final static float NORMAL = 0;\n public final static float NORMALBIG = (float)0.025;\n public final static float BIG = (float)0.05;\n public final static float BIGGEST = (float)0.2;\n }\n}" ]
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.andfast.app.AndFastApplication; import com.andfast.app.R; import com.andfast.app.constant.GeneralID; import com.andfast.app.util.LogUtils; import com.andfast.app.view.common.activity.MainActivity; import com.andfast.app.view.widget.SpacingTextView; import java.util.ArrayList; import java.util.List;
package com.andfast.app.view.common; /** * Created by mby on 17-8-1. */ public class TabManager { private final static String TAG = "TabManager"; private TabLayout mTabLayout; private Fragment mCurrentFragment; private LayoutInflater mInflater; private int mCurrentIdx; private int mLastIdx; private TextView[] mTabTextView = new TextView[MainTab.values().length]; private List<TabReselectListener> mTabReselectListeners; public interface TabReselectListener { void onTabReselect(); } private TabManager(){ } public static TabManager getInstance(Context context){ return TabMangerHolder.sInstance; } private static class TabMangerHolder{ private static final TabManager sInstance = new TabManager(); } public void initTabs(MainActivity mainActivity,Intent intent,TabLayout tabLayout) { mTabLayout = tabLayout; mInflater = LayoutInflater.from(AndFastApplication.getContext()); tabLayout.addOnTabSelectedListener(getTabSelectedListener(mainActivity)); MainTab[] mainTabs = MainTab.values(); for (int i = 0; i < mainTabs.length; i++) { MainTab mainTab = mainTabs[i]; mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabItemView(i, mainTab)).setTag(new TabInfo(mainTab.getClazz())), false); } changeTab(intent); mTabTextView[mLastIdx].setTextColor(AndFastApplication.getContext().getResources().getColor(R.color.tab_font_red)); } public void changeTab(Intent intent) {
int tab = intent.getIntExtra(GeneralID.Extra.TAB, 0);
1
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/EmptyExchangeChannel.java
[ "public class RequestControl {\n\t/**\n\t * response timeout or write timeout if {@code sent} is true\n\t */\n private int timeout = 2000;\n private short opcode;\n private byte serializeType;\n private byte compressType;\n //wait write success or not\n private boolean sent;\n\n /**\n * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true\n */\n private boolean preferHighPerformanceWriter;\n \n public RequestControl(){\n \tthis(false);\n }\n\tpublic RequestControl(boolean preferHighPerformanceWriter) {\n\t\tthis.preferHighPerformanceWriter = preferHighPerformanceWriter;\n\t}\n\n\tpublic int timeout() {\n return timeout;\n }\n\n public void timeout(int timeout) {\n this.timeout = ParameterChecker.checkPositive(timeout, \"timeout\");\n }\n\n public short opcode() {\n return opcode;\n }\n\n public void opcode(short opcode) {\n this.opcode = opcode;\n }\n\n public byte serializeType() {\n return serializeType;\n }\n\n public void serializeType(byte serializeType) {\n this.serializeType = serializeType;\n }\n\n public byte compressType() {\n return compressType;\n }\n\n public void compressType(byte compressType) {\n this.compressType = compressType;\n }\n\n public boolean sent() {\n return sent;\n }\n\n public void sent(boolean sent) {\n this.sent = sent;\n }\n \n public boolean preferHighPerformanceWriter(){\n \treturn preferHighPerformanceWriter;\n }\n}", "public interface ResponseCallback<T> {\n\t/**\n\t * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory}\n\t */\n Executor getExecutor();\n \n void handleResponse(T resp);\n void handleException(Exception cause);\n} ", "public class Tracer {\n\t\n\tprivate static final Logger logger = LoggerFactory.getLogger(Tracer.class);\n\tprivate static final Object EMPTY_VALUE = new Object();\n\n\tprivate final ConcurrentMap<Integer, TraceContext> traces = new ConcurrentHashMap<>();\n\tprivate final ConcurrentMap<ExchangeChannel, ConcurrentMap<Integer, Object>> singleChannelTraces = new ConcurrentHashMap<>();\n\n\tpublic Map<Integer, Object> popPendingRequests(ExchangeChannel channel) {\n\t\treturn singleChannelTraces.remove(channel);\n\t}\n\n\tpublic Map<Integer, Object> peekPendingRequests(ExchangeChannel channel) {\n\t\treturn singleChannelTraces.get(channel);\n\t}\n\n\tpublic void trace(ExchangeChannel channel, int packageId, ResponseFuture<byte[]> future) {\n\t\ttraces.putIfAbsent(packageId, new TraceContext(channel, future));\n\n\t\tConcurrentMap<Integer, Object> packetIds = singleChannelTraces.get(channel);\n\t\tif (null == packetIds) {\n\t\t\tConcurrentMap<Integer, Object> old = singleChannelTraces.putIfAbsent(channel,\n\t\t\t\t\tpacketIds = new ConcurrentHashMap<>());\n\t\t\tif (null != old) {\n\t\t\t\tpacketIds = old;\n\t\t\t}\n\t\t}\n\t\tpacketIds.put(packageId, EMPTY_VALUE);\n\t}\n\n\tpublic void erase(ResponseProtocol protocol) {\n\t\tif (protocol.heartbeat()) {\n\t\t\tprotocol.recycle();\n\t\t\treturn;\n\t\t}\n\t\tTraceContext traceContext = traces.remove(protocol.packetId());\n\t\tif (null == traceContext) {\n\t\t\tlogger.info(\"trace no exist for packageId[{}]\", protocol.packetId());\n\t\t\tprotocol.recycle();\n\t\t\treturn;\n\t\t}\n\t\ttraceContext.respFuture.putResponse(protocol.body(), protocol.result(), protocol.cause());\n\t\tConcurrentMap<Integer, Object> packetIds = singleChannelTraces.get(traceContext.channel);\n\t\tif (CollectionUtils.isNotEmpty(packetIds)) {\n\t\t\tpacketIds.remove(protocol.packetId());\n\t\t}\n\t\tprotocol.recycle();\n\t}\n\t\n\tpublic void remove(int packetId){\n\t\tTraceContext traceContext = traces.remove(packetId);\n\t\tif(null != traceContext){\n\t\t\tConcurrentMap<Integer, Object> packetIds = singleChannelTraces.get(traceContext.channel);\n\t\t\tif (CollectionUtils.isNotEmpty(packetIds)) {\n\t\t\t\tpacketIds.remove(packetId);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tstatic class TraceContext {\n\t\tExchangeChannel channel;\n\t\tResponseFuture<byte[]> respFuture;\n\n\t\tpublic TraceContext(ExchangeChannel channel, ResponseFuture<byte[]> respFuture) {\n\t\t\tthis.channel = ParameterChecker.checkNotNull(channel, \"channel\");\n\t\t\tthis.respFuture = ParameterChecker.checkNotNull(respFuture, \"respFuture\");\n\t\t}\n\t}\n}", "public class SailfishException extends Exception {\n\n /** */\n private static final long serialVersionUID = 1L;\n private ExceptionCode errorCode;\n\n public SailfishException(String message) {\n super(message);\n }\n \n public SailfishException(Throwable cause){\n super(cause);\n }\n\n public SailfishException(ExceptionCode errorCode, String message) {\n super(message(errorCode, message));\n this.errorCode = errorCode;\n }\n\n public SailfishException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public SailfishException(ExceptionCode errorCode, String message, Throwable cause) {\n super(message(errorCode, message), cause);\n this.errorCode = errorCode;\n }\n\n private static String message(ExceptionCode errorCode, String message) {\n if(null == errorCode){\n errorCode = ExceptionCode.DEFAULT;\n }\n String prefix = \"[errorCode:\" + errorCode.toString() + \"]\";\n return StrUtils.isBlank(message) ? prefix : prefix + \", \"+ message;\n }\n\n public ExceptionCode code() {\n return errorCode;\n }\n\n public RemoteSailfishException toRemoteException() {\n return new RemoteSailfishException(errorCode, getMessage(), getCause());\n }\n \n /**\n * exception for remote peer\n */\n class RemoteSailfishException extends SailfishException{\n private static final long serialVersionUID = 1L;\n public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) {\n super(errorCode, message, cause);\n }\n }\n}", "public interface ResponseFuture<T>{\n void putResponse(T resp, byte result, SailfishException cause);\n boolean isDone();\n void setCallback(ResponseCallback<T> callback, int timeout);\n T get() throws SailfishException, InterruptedException;\n T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException;\n}", "public interface MsgHandler<I extends Protocol> {\n /**\n * I is request or response\n */\n void handle(ExchangeChannelGroup channelGroup, I msg);\n}", "public interface Protocol {\n /**\n * request or response direction\n */\n boolean request();\n \n /**\n * heartbeat request/response\n */\n boolean heartbeat();\n\n /**\n * serialize bytes data to channel\n */\n void serialize(ByteBuf output) throws SailfishException;\n \n /**\n * deserialize bytes data from channel\n */\n void deserialize(ByteBuf input, int totalLength) throws SailfishException;\n}", "public class ResponseProtocol implements Protocol{\n\t\n\tprivate static final Recycler<ResponseProtocol> RECYCLER = new Recycler<ResponseProtocol>(){\n\t\t@Override\n\t\tprotected ResponseProtocol newObject(Recycler.Handle<ResponseProtocol> handle) {\n\t\t\treturn new ResponseProtocol(handle);\n\t\t}\n\t};\n\t\n private static final int HEADER_LENGTH = 6;\n private static final int RESPONSE_FLAG = 0;\n private static final int HEARTBEAT_FLAG = 0x20;\n \n public static ResponseProtocol newInstance(){\n \treturn RECYCLER.get();\n }\n \n private final Recycler.Handle<ResponseProtocol> handle;\n \n //response direction\n private boolean heartbeat;\n private byte serializeType = SerializeType.NON_SERIALIZE;\n \n private int packetId;\n \n private byte result;\n private byte compressType = CompressType.NON_COMPRESS;\n\n private byte[] body;\n \n private SailfishException cause;\n \n\tpublic ResponseProtocol(Recycler.Handle<ResponseProtocol> handle) {\n\t\tthis.handle = handle;\n\t}\n \n\tpublic void recycle(){\n\t\tif(null == handle){//some objects don't need recycle\n\t\t\treturn;\n\t\t}\n\t\t\n\t\theartbeat = false;\n\t\tserializeType = SerializeType.NON_SERIALIZE;\n\t\tpacketId = 0;\n\t\tresult = 0;\n\t\tcompressType = CompressType.NON_COMPRESS;\n\t\tbody = null;\n\t\tcause = null;\n\t\thandle.recycle(this);\n\t}\n\t\n @Override\n public void serialize(ByteBuf output) throws SailfishException {\n try{\n //write magic first\n output.writeShort(RemotingConstants.SAILFISH_MAGIC);\n //write package length(not contain current length field(4 bytes))\n if(this.heartbeat){\n output.writeInt(1);\n }else{\n output.writeInt(HEADER_LENGTH + bodyLength());\n }\n\n byte compactByte = (byte)RESPONSE_FLAG; \n if(heartbeat){\n compactByte = (byte)(compactByte | HEARTBEAT_FLAG);\n output.writeByte(compactByte);\n return;\n }\n output.writeByte(compactByte | serializeType);\n \n output.writeInt(packetId);\n output.writeByte(result << 4 | compressType);\n \n if(bodyLength() != 0){\n output.writeBytes(body);\n }\n }catch(Throwable cause){\n throw new SailfishException(cause);\n }finally {\n\t\t\trecycle();\n\t\t}\n }\n\n @Override\n public void deserialize(ByteBuf input, int totalLength) throws SailfishException {\n try{\n byte compactByte = input.readByte();\n this.heartbeat = ((compactByte & HEARTBEAT_FLAG) != 0);\n if(this.heartbeat){\n return;\n }\n this.serializeType = (byte)(compactByte & 0x1F);\n \n this.packetId = input.readInt(); \n \n byte tmp = input.readByte();\n\n this.result = (byte)(tmp >> 4 & 0xF);\n this.compressType = (byte)(tmp >> 0 & 0xF);\n \n //read body\n int bodyLength = totalLength - HEADER_LENGTH;\n if(bodyLength > 0){\n this.body = new byte[bodyLength];\n input.readBytes(this.body);\n }\n }catch(Throwable cause){\n throw new SailfishException(cause);\n }\n }\n\n public void heartbeat(boolean heartbeat) {\n this.heartbeat = heartbeat;\n }\n\n public byte serializeType() {\n return serializeType;\n }\n\n public void serializeType(byte serializeType) {\n this.serializeType = ProtocolParameterChecker.checkSerializeType(serializeType);\n }\n\n public int packetId() {\n return packetId;\n }\n\n public void packetId(int packetId) {\n this.packetId = packetId;\n }\n\n public byte result() {\n return result;\n }\n\n public void result(byte result) {\n this.result = ProtocolParameterChecker.checkResult(result);\n }\n\n public byte compressType() {\n return compressType;\n }\n\n public void compressType(byte compressType) {\n this.compressType = ProtocolParameterChecker.checkCompressType(compressType);\n }\n\n public byte[] body() {\n return body;\n }\n\n public void body(byte[] body) {\n this.body = body;\n }\n\n public void errorStack(String errorStack) {\n if(StrUtils.isNotBlank(errorStack)){\n this.body = errorStack.getBytes(CharsetUtil.UTF_8);\n }\n }\n \n public void cause(SailfishException cause){\n \tthis.cause = cause;\n }\n \n public SailfishException cause(){\n \treturn this.cause;\n }\n \n private int bodyLength(){\n if(null == body){\n return 0;\n }\n return body.length;\n }\n\n @Override\n public boolean request() {\n return false;\n }\n \n public boolean heartbeat() {\n return this.heartbeat;\n }\n \n\t@Override\n\tpublic String toString() {\n\t\treturn \"ResponseProtocol [heartbeat=\" + heartbeat + \", serializeType=\" + serializeType + \", packetId=\"\n\t\t\t\t+ packetId + \", result=\" + result + \", compressType=\" + compressType + \", body=\" + Arrays.toString(body)\n\t\t\t\t+ \"]\";\n\t}\n\n\t//less objects, don't need recycle\n\tpublic static ResponseProtocol newHeartbeat(){\n ResponseProtocol heartbeat = new ResponseProtocol(null);\n heartbeat.heartbeat(true);\n return heartbeat;\n }\n \n\t//less objects, don't need recycle\n public static ResponseProtocol newErrorResponse(int packetId, SailfishException cause){\n ResponseProtocol error = new ResponseProtocol(null);\n error.packetId(packetId);\n error.cause(cause);\n error.result(RemotingConstants.RESULT_FAIL);\n return error;\n }\n}" ]
import java.net.SocketAddress; import java.util.UUID; import io.netty.channel.Channel; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.Tracer; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture; import sailfish.remoting.handler.MsgHandler; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.protocol.ResponseProtocol;
/** * * Copyright 2016-2016 spccold * * 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 sailfish.remoting.channel; /** * for test or something else * @author spccold * @version $Id: EmptyExchangeChannel.java, v 0.1 2016年11月25日 下午8:37:47 spccold Exp $ */ public class EmptyExchangeChannel implements ExchangeChannel{ @Override public UUID id() { return null; } @Override public boolean isAvailable() { return false; } @Override
public MsgHandler<Protocol> getMsgHander() {
6
Kesshou/Kesshou-Android
app/src/main/java/kesshou/android/daanx/views/regist/SchoolFragment.java
[ "public class ToastUtils {\n\n\tprivate static Toast toast;\n\n\tpublic static void makeTextAndShow(Context context,String text, int duration) {\n\t\tif (toast == null) {\n\t\t\t//如果還沒有用過makeText方法,才使用\n\t\t\ttoast = new Toast(context);\n\t\t\tLayoutInflater inflater = LayoutInflater.from(context);\n\t\t\tView view = inflater.inflate(R.layout.toast_layout,null);\n\t\t\ttoast.setView(view);\n\t\t}\n\t\t((TextView)toast.getView().findViewById(R.id.noti_text)).setText(text);\n\t\ttoast.setDuration(duration);\n\t\ttoast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP,0,100);\n\t\ttoast.show();\n\t}\n\n\tpublic static void makeTextAndShow(Context context,int text, int duration) {\n\t\tif (toast == null) {\n\t\t\t//如果還沒有用過makeText方法,才使用\n\t\t\ttoast = new Toast(context);\n\t\t\tLayoutInflater inflater = LayoutInflater.from(context);\n\t\t\tView view = inflater.inflate(R.layout.toast_layout,null);\n\t\t\ttoast.setView(view);\n\t\t}\n\t\t((TextView)toast.getView().findViewById(R.id.noti_text)).setText(context.getString(text));\n\t\ttoast.setDuration(duration);\n\t\ttoast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP,0,100);\n\t\ttoast.show();\n\t}\n\n\tpublic static void makeTextAndShow(Context context,String text, int duration,int gravity) {\n\t\tif (toast == null) {\n\t\t\t//如果還沒有用過makeText方法,才使用\n\t\t\ttoast = new Toast(context);\n\t\t\tLayoutInflater inflater = LayoutInflater.from(context);\n\t\t\tView view = inflater.inflate(R.layout.toast_layout,null);\n\t\t\ttoast.setView(view);\n\t\t}\n\t\t((TextView)toast.getView().findViewById(R.id.noti_text)).setText(text);\n\t\ttoast.setDuration(duration);\n\t\ttoast.setGravity(gravity,0,0);\n\t\ttoast.show();\n\t}\n\n\tpublic static void makeTextAndShow(Context context,int text, int duration,int gravity) {\n\t\tif (toast == null) {\n\t\t\t//如果還沒有用過makeText方法,才使用\n\t\t\ttoast = new Toast(context);\n\t\t\tLayoutInflater inflater = LayoutInflater.from(context);\n\t\t\tView view = inflater.inflate(R.layout.toast_layout,null);\n\t\t\ttoast.setView(view);\n\t\t}\n\t\t((TextView)toast.getView().findViewById(R.id.noti_text)).setText(context.getString(text));\n\t\ttoast.setDuration(duration);\n\t\ttoast.setGravity(gravity,0,0);\n\t\ttoast.show();\n\t}\n\n\tpublic static void makeTextAndShow(Context context,String text, int duration,int gravity,int textSize) {\n\t\tif (toast == null) {\n\t\t\t//如果還沒有用過makeText方法,才使用\n\t\t\ttoast = new Toast(context);\n\t\t\tLayoutInflater inflater = LayoutInflater.from(context);\n\t\t\tView view = inflater.inflate(R.layout.toast_layout,null);\n\t\t\ttoast.setView(view);\n\t\t}\n\t\tTextView textView = (TextView) toast.getView().findViewById(R.id.noti_text);\n\t\ttextView.setText(text);\n\t\ttextView.setTextSize(textSize);\n\t\ttoast.setDuration(duration);\n\t\ttoast.setGravity(gravity,0,0);\n\t\ttoast.show();\n\t}\n\n}", "public abstract class MyCallBack<t> implements Callback<t> {\n\n\tprivate Context context;\n\n\tprotected MyCallBack(Context mContext){\n\t\tcontext=mContext.getApplicationContext();\n\t}\n\n\n\tprivate void onError(Call<t> call,Response<t> response){\n\t\tError error = ErrorUtils.parseError(response,context);\n\t\tErrorUtils.logError(error);\n\n\t\tswitch (error.code){\n\t\t\tcase 103:\n\t\t\t\tbreak;\n\t\t\tcase 500:\n\t\t\t\tbreak;\n\t\t\tcase 501:\n\t\t\t\tbreak;\n\t\t\tcase 100:\n\t\t\t\tbreak;\n\t\t\tcase 102:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tToastUtils.makeTextAndShow(context,error.message,Toast.LENGTH_LONG,Gravity.CENTER);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tonErr(error,call);\n\n\t}\n\n\n\n\t@Override\n\tpublic void onResponse(Call<t> call, Response<t> response) {\n\t\tif(response.isSuccessful()){\n\t\t\tLog.d(\"OkHttp\",response.raw().toString());\n\t\t\tonSuccess(response);\n\t\t}else{\n\t\t\tonError(call,response);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onFailure(Call<t> call, Throwable t) {\n\t\tLog.e(\"network error\",t.getMessage());\n\t\tToastUtils.makeTextAndShow(context,\"網路錯誤或無網路\",Toast.LENGTH_SHORT, Gravity.CENTER);\n\t}\n\n\tpublic abstract void onSuccess(Response<t> response);\n\n\tpublic abstract void onErr(Error error, Call<t> call);\n}", "public class NetworkingClient {\n\n private AccountApi accountApi;\n private InforApi inforApi;\n private NewsApi newsApi;\n\tprivate MenuApi menuApi;\n\n\n public NetworkingClient(Context context) {\n\t Retrofit retrofit = RetrofitClient.getInstance(context.getApplicationContext());\n\n accountApi = retrofit.create(AccountApi.class);\n inforApi = retrofit.create(InforApi.class);\n newsApi = retrofit.create(NewsApi.class);\n\t menuApi = retrofit.create(MenuApi.class);\n }\n\n // Account System\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with login api\n Usage:\n parameter:\n Login usr: login information\n Callback<Token> callback: Callback\n */\n\tpublic void login(Login login,Callback<Token> callback) {\n\n\t\tCall<Token> call = accountApi.login(login);\n\t\tcall.enqueue(callback);\n\t}\n\n /*\n Author: Charles Lien( lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with login api\n Usage:\n parameter:\n Login usr: login information\n Callback<Token> callback: Callback\n */\n public void login() {\n\t Realm realm = Realm.getDefaultInstance();\n\t Setting setting = realm.where(Setting.class).findFirst();\n\t Login usr = new Login();\n\t usr.usr_account = setting.email;\n\t usr.usr_password = setting.password;\n Call<Token> call = accountApi.login(usr);\n\t String token = \"\";\n\t try {\n\t\t token = call.execute().body().token;\n\t }catch (Exception e){}\n\n\t realm.beginTransaction();\n\t setting.token = token;\n\t\trealm.commitTransaction();\n\t realm.close();\n }\n\n /*\n Author: Charles Lien( lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with register api\n Usage:\n parameter:\n Register register: register information\n\t Callback<Token> callback: Callback\n\n */\n public void register(Register register,Callback<Token> callback) {\n Call<Token> call = accountApi.create(register);\n call.enqueue(callback);\n }\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with checkAccount api\n Usage:\n parameter:\n\n\n */\n\tpublic void checkAccount(CheckRegist checkAccount, Callback<StatusResponse> callback) {\n\t\tCall<StatusResponse> call = accountApi.checkAccount(checkAccount);\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with checkNick api\n Usage:\n parameter:\n\n\n */\n\tpublic void checkNick(CheckRegist checkNick, Callback<StatusResponse> callback) {\n\t\tCall<StatusResponse> call = accountApi.checkNick(checkNick);\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with checkNick api\n Usage:\n parameter:\n\n\n */\n\tpublic void checkSchool(CheckRegist checkSchool, Callback<StatusResponse> callback) {\n\t\tCall<StatusResponse> call = accountApi.checkSchool(checkSchool);\n\t\tcall.enqueue(callback);\n\t}\n\n /*\n Author: Charles Lien( lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with update api\n Usage:\n parameter:\n Update usr: update information\n\t Callback<Object> callback: Callback\n */\n public void update(Update usr,Callback<StatusResponse> callback) {\n\t Call<StatusResponse> call = accountApi.update(usr);\n\t call.enqueue(callback);\n }\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with get user's information api\n Usage:\n parameter:\n\n\n */\n\tpublic void getUserInfo(Callback<UserInfoResponse> callback) {\n\t\tCall<UserInfoResponse> call = accountApi.getUserInfo();\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with set noti info api\n Usage:\n parameter:\n\n\n */\n\tpublic void setNoti(String fcm_token,boolean is_noti,Callback<StatusResponse> callback) {\n\t\tCall<StatusResponse> call = accountApi.setNoti(fcm_token,is_noti);\n\t\tcall.enqueue(callback);\n\t}\n\n\n\n // Infor System\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with api\n Usage:\n parameter:\n\n\n */\n\tpublic void queryTimeTable(Callback<TimeTableResponse> callback) {\n\t\tCall<TimeTableResponse> call = inforApi.getTimeTable();\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with api\n Usage:\n parameter:\n\n\n */\n\tpublic void getABS(Callback<List<AbsentstateResponse>> callback) {\n\t\tCall<List<AbsentstateResponse>> call = inforApi.getABS();\n\t\tcall.enqueue(callback);\n\t}\n\n\n /*\n Author: Charles Lien( lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with history score query api\n Usage:\n parameter:\n HistoryScore score : Query Information:\n\t Callback<SectionalExamResponse> callback: Callback\n */\n public void queryHScore(int grade,int semester,Callback<List<HistoryScoreResponse>> callback) {\n\t Call<List<HistoryScoreResponse>> call = inforApi.queryHScore(grade,semester);\n call.enqueue(callback);\n }\n\n\n /*\n Author: Charles Lien(lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with sectional exam score query api\n Usage:\n parameter:\n SectionalExamScore score : Query Information:\n Callback<SectionalExamResponse> callback: Callback\n */\n public void querySEScore(int semester,Callback<List<SectionalExamResponse>> callback) {\n Call<List<SectionalExamResponse>> call = inforApi.querySEScore(semester);\n call.enqueue(callback);\n }\n\n /*\n Author: Charles Lien(lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with attitude status query api\n Usage:\n parameter:\n SectionalExamScore score : Query Information:\n\t Callback<List<AttitudeStatusResponse>> callback: Callback\n */\n public void getATS(Callback<AttitudeStatusResponse> callback) {\n Call<AttitudeStatusResponse> call = inforApi.getATS();\n call.enqueue(callback);\n }\n\n // Calender\n\n /*\n Author: Charles Lien(lienching),IU(yoyo930021)\n Description:\n This function's purpose is to communicate with calender query api\n Usage:\n parameter:\n\t Callback<List<CalenderResponse>> callback: Callback\n */\n public void getCalender(Callback<List<CalenderResponse>> callback) {\n Call<List<CalenderResponse>> call = newsApi.getCalender();\n call.enqueue(callback);\n }\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with Announce query api\n Usage:\n parameter:\n String sort : Query Information:\n\t Callback<List<AnnounceResponse>> callback: Callback\n */\n\tpublic void getAnnounce(String sort,Callback<List<AnnounceResponse>> callback) {\n\t\tCall<List<AnnounceResponse>> call = newsApi.getAnnounce(sort);\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with QandA query api\n Usage:\n parameter:\n\t Callback<List<QandaResponse>> callback: Callback\n */\n\tpublic void getQanda(Callback<List<QandaResponse>> callback) {\n\t\tCall<List<QandaResponse>> call = newsApi.getQandA();\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with relatedlink query api\n Usage:\n parameter:\n\t Callback<List<RelatedlinkResponse>> callback: Callback\n */\n\tpublic void getLink(Callback<List<RelatedlinkResponse>> callback) {\n\t\tCall<List<RelatedlinkResponse>> call = newsApi.getLink();\n\t\tcall.enqueue(callback);\n\t}\n\n\t/*\n Author: IU(yoyo930021)\n Description:\n This function's purpose is to communicate with feedback api\n Usage:\n\t feedClass : feed class\n\t commit : feed body\n\t system : mobile info\n parameter:\n\n */\n\tpublic void postFB(String feedClass,String commit,String system,Callback<StatusResponse> callback) {\n\t\tCall<StatusResponse> call = menuApi.postFB(feedClass,commit,system);\n\t\tcall.enqueue(callback);\n\t}\n\n}", "public class CheckRegist {\n\n\t@SerializedName(\"account\")\n\tpublic String account;\n\n\t@SerializedName(\"nick\")\n\tpublic String nick;\n\n\t@SerializedName(\"schoolAccount\")\n\tpublic String schoolAccount;\n\n\t@SerializedName(\"schoolPwd\")\n\tpublic String schoolPwd;\n}", "public class Error {\n\n\t@SerializedName(\"error\")\n\tpublic String message;\n\n\t@SerializedName(\"code\")\n\tpublic int code;\n\n}", "public class Register {\n\n @SerializedName(\"email\")\n public String usr_email;\n\n @SerializedName(\"password\")\n public String usr_passwd;\n\n @SerializedName(\"user_group\")\n public String usr_group;\n\n @SerializedName(\"school_account\")\n public String school_account;\n\n @SerializedName(\"school_pwd\")\n public String school_pwd;\n\n @SerializedName(\"nick\")\n public String nickname;\n\n\t@SerializedName(\"name\")\n\tpublic String name;\n\n}", "public class StatusResponse extends RealmObject {\n\n\t@SerializedName(\"success\")\n\tpublic String status;\n\n}", "public class StartActivity extends BaseActivity {\n\n\tpublic Register register;\n\tpublic FirebaseAnalytics mFirebaseAnalytics;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\n\t\t// Obtain the FirebaseAnalytics instance.\n\t\tmFirebaseAnalytics = FirebaseAnalytics.getInstance(this);\n\n\t\tBundle bundle = new Bundle();\n\t\tbundle.putString(FirebaseAnalytics.Param.ITEM_ID, \"App open\");\n\t\tbundle.putString(FirebaseAnalytics.Param.ITEM_NAME, \"App open\");\n\t\tbundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, \"doing\");\n\t\tmFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.APP_OPEN, bundle);\n\n\t\tRealm realm=Realm.getDefaultInstance();\n\n\t\tRealmResults<Setting> settings = realm.where(Setting.class).findAll();\n\t\tif(settings.size()==0||!settings.first().logined){\n\t\t\tsetContentView(R.layout.activity_login);\n\t\t\tToolbar toolbar=(Toolbar)findViewById(R.id.toolbar);\n\t\t\tsetSupportActionBar(toolbar);\n\n\t\t\tregister = new Register();\n\n\t\t\tFragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n\t\t\tFragment fg= new LoginFragment();\n\t\t\tft.replace(R.id.fm, fg, \"f_m\");\n\t\t\tft.commit();\n\t\t}else{\n\t\t\tsetContentView(R.layout.activity_start);\n\t\t\tnew NetworkingClient(getApplicationContext()).getUserInfo(new MyCallBack<UserInfoResponse>(getApplicationContext()) {\n\t\t\t\t@Override\n\t\t\t\tpublic void onSuccess(final Response<UserInfoResponse> response) {\n\t\t\t\t\tRealm realm = Realm.getDefaultInstance();\n\n\t\t\t\t\trealm.executeTransaction(new Realm.Transaction() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void execute(Realm realm) {\n\t\t\t\t\t\t\tSetting setting=realm.where(Setting.class).findFirst();\n\t\t\t\t\t\t\tsetting.nick=response.body().nick;\n\t\t\t\t\t\t\tsetting.usr_group=response.body().group;\n\t\t\t\t\t\t\tsetting.classX=response.body().classX;\n\t\t\t\t\t\t\tsetting.name=response.body().name;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\trealm.close();\n\n\t\t\t\t\ttoMainActivity();\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onErr(Error error, Call<UserInfoResponse> call) {\n\t\t\t\t\ttoMainActivity();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\trealm.close();\n\t}\n\n\tpublic void toMainActivity(){\n\t\tRealm realm=Realm.getDefaultInstance();\n\t\tif(realm.where(NetWorkCache.class).findAll().size()==0){\n\t\t\trealm.executeTransaction(new Realm.Transaction() {\n\t\t\t\t@Override\n\t\t\t\tpublic void execute(Realm realm) {\n\t\t\t\t\tNetWorkCache netWorkCache = realm.createObject(NetWorkCache.class);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\trealm.close();\n\t\tIntent intent = new Intent();\n\t\tintent.setClass(StartActivity.this, MainActivity.class);\n\t\tstartActivity(intent);\n\t\tStartActivity.this.finish();\n\t}\n\n\t@Override\n\tprotected void onDestroy() {\n\t\tsuper.onDestroy();\n\t}\n}" ]
import android.os.Bundle; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.AppCompatButton; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import kesshou.android.daanx.R; import kesshou.android.daanx.util.component.ToastUtils; import kesshou.android.daanx.util.network.MyCallBack; import kesshou.android.daanx.util.network.NetworkingClient; import kesshou.android.daanx.util.network.api.holder.CheckRegist; import kesshou.android.daanx.util.network.api.holder.Error; import kesshou.android.daanx.util.network.api.holder.Register; import kesshou.android.daanx.util.network.api.holder.StatusResponse; import kesshou.android.daanx.views.StartActivity; import retrofit2.Call; import retrofit2.Response;
package kesshou.android.daanx.views.regist; /** * A simple {@link Fragment} subclass. */ public class SchoolFragment extends Fragment { @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment final View view = inflater.inflate(R.layout.fragment_school, container, false); final TextInputLayout tilInputAccount=(TextInputLayout)view.findViewById(R.id.til_input_account); final TextInputEditText inputAccount=(TextInputEditText)view.findViewById(R.id.input_account); TextViewCheckEmpty(tilInputAccount,inputAccount); final TextInputLayout tilInputPassword=(TextInputLayout)view.findViewById(R.id.til_input_password); final TextInputEditText inputPassword=(TextInputEditText) view.findViewById(R.id.input_password); TextViewCheckEmpty(tilInputPassword,inputPassword);
final Register register=((StartActivity) getActivity()).register;
7
Belgabor/AMTweaker
src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Evaporator.java
[ "public class AMTListAddition extends BaseListAddition {\n private Object amt_recipe = null;\n\n public AMTListAddition(String description, List list, AMTRecipeWrapper recipe) {\n super(description, list, recipe);\n }\n\n @Override\n public void apply() {\n if (amt_recipe == null) {\n AMTRecipeWrapper my_recipe = (AMTRecipeWrapper) recipe;\n my_recipe.register();\n\n for (Object r : list) {\n if (my_recipe.matches(r)) {\n amt_recipe = r;\n break;\n }\n }\n if (amt_recipe == null) {\n MineTweakerAPI.getLogger().logError(\"Failed to locate AMT recipe for \" + description);\n }\n } else {\n list.add(amt_recipe);\n }\n }\n\n @Override\n public void undo() {\n if (amt_recipe == null) {\n MineTweakerAPI.getLogger().logError(\"Failed to undo AMT recipe for \" + description);\n } else {\n list.remove(amt_recipe);\n }\n }\n\n @Override\n public String getRecipeInfo() {\n return ((AMTRecipeWrapper) recipe).getRecipeInfo();\n }\n\n}", "public abstract class AMTRecipeWrapper {\n public abstract void register();\n public abstract boolean matches(Object o);\n public abstract String getRecipeInfo();\n}", "public abstract class BaseListRemoval implements IUndoableAction {\n protected final String description;\n protected final List list;\n protected final FluidStack fluid;\n protected final ItemStack stack;\n protected Object recipe;\n\n public BaseListRemoval(String description, List list, ItemStack stack, FluidStack fluid) {\n this.list = list;\n this.stack = stack;\n this.description = description;\n this.fluid = fluid;\n }\n\n public BaseListRemoval(String description, List list, ItemStack stack) {\n this(description, list, stack, null);\n }\n\n public BaseListRemoval(String description, List list, FluidStack fluid) {\n this(description, list, null, fluid);\n }\n\n public BaseListRemoval(List list, ItemStack stack) {\n this(null, list, stack);\n }\n\n public BaseListRemoval(List list, FluidStack stack) {\n this(null, list, stack);\n }\n\n public BaseListRemoval(String description, List list) {\n this(description, list, null, null);\n }\n\n @Override\n public boolean canUndo() {\n return list != null;\n }\n\n @Override\n public void undo() {\n if (recipe != null) {\n list.add(recipe);\n }\n }\n\n public String getRecipeInfo() {\n return \"Unknown Item\";\n }\n\n @Override\n public String describe() {\n if (recipe instanceof ItemStack) return \"Removing \" + description + \" Recipe for :\" + ((ItemStack) recipe).getDisplayName();\n else if (recipe instanceof FluidStack) return \"Removing \" + description + \" Recipe for :\" + ((FluidStack) recipe).getFluid().getLocalizedName((FluidStack) recipe);\n else return \"Removing \" + description + \" Recipe for :\" + getRecipeInfo();\n }\n\n @Override\n public String describeUndo() {\n if (recipe instanceof ItemStack) return \"Restoring \" + description + \" Recipe for :\" + ((ItemStack) recipe).getDisplayName();\n else if (recipe instanceof FluidStack) return \"Restoring \" + description + \" Recipe for :\" + ((FluidStack) recipe).getFluid().getLocalizedName((FluidStack) recipe);\n else return \"Restoring \" + description + \" Recipe for :\" + getRecipeInfo();\n }\n\n @Override\n public Object getOverrideKey() {\n return null;\n }\n}", "public static FluidStack toFluid(ILiquidStack iStack) {\n if (iStack == null) {\n return null;\n } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());\n}", "public static ItemStack toStack(IItemStack iStack) {\n return toStack(iStack, false);\n}", "public static boolean areEqual(ItemStack stack, ItemStack stack2) {\n return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);\n}", "public static boolean areEqualNull(ItemStack stack, ItemStack stack2) {\n return (stack == null ? stack2 == null : stack.isItemEqual(stack2));\n}" ]
import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import minetweaker.api.liquid.ILiquidStack; import mods.belgabor.amtweaker.mods.amt.util.AMTListAddition; import mods.belgabor.amtweaker.mods.amt.util.AMTRecipeWrapper; import mods.belgabor.amtweaker.util.BaseListRemoval; import mods.defeatedcrow.api.recipe.IEvaporatorRecipe; import mods.defeatedcrow.api.recipe.RecipeRegisterManager; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid; import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; import static mods.belgabor.amtweaker.helpers.StackHelper.areEqualNull;
package mods.belgabor.amtweaker.mods.amt.handlers; @ZenClass("mods.amt.Evaporator") public class Evaporator { // Adding a new cooking recipe for the iron plate @ZenMethod public static void addRecipe(IItemStack output, ILiquidStack secondary, IItemStack input, boolean returnContainer) { doAddRecipe(output, secondary, input, returnContainer); } @ZenMethod public static void addRecipe(IItemStack output, ILiquidStack secondary, IItemStack input) { doAddRecipe(output, secondary, input, true); } @ZenMethod public static void addRecipe(IItemStack output, IItemStack input, boolean returnContainer) { doAddRecipe(output, null, input, returnContainer); } @ZenMethod public static void addRecipe(ILiquidStack secondary, IItemStack input, boolean returnContainer) { doAddRecipe(null, secondary, input, returnContainer); } @ZenMethod public static void addRecipe(IItemStack output, IItemStack input) { doAddRecipe(output, null, input, true); } @ZenMethod public static void addRecipe(ILiquidStack secondary, IItemStack input) { doAddRecipe(null, secondary, input, true); } private static void doAddRecipe(IItemStack output, ILiquidStack secondary, IItemStack input, boolean returnContainer) { if (input == null) { MineTweakerAPI.getLogger().logError("Evaporator: Input item must not be null!"); return; } if ((output == null) && (secondary == null)) { MineTweakerAPI.getLogger().logError("Evaporator: Primary and secondary output must not both be null!"); return; } MineTweakerAPI.apply(new Add(new EvaporatorRecipeWrapper(output, secondary, input, returnContainer))); } private static class EvaporatorRecipeWrapper extends AMTRecipeWrapper { private final ItemStack output; private final FluidStack secondary; private final ItemStack input; private final boolean returnContainer; public EvaporatorRecipeWrapper(IItemStack output, ILiquidStack secondary, IItemStack input, boolean returnContainer) { this.output = toStack(output); this.secondary = toFluid(secondary); this.input = toStack(input); this.returnContainer = returnContainer; } @Override public void register() { RecipeRegisterManager.evaporatorRecipe.addRecipe(output, secondary, input, returnContainer); } @Override public boolean matches(Object o) { IEvaporatorRecipe r = (IEvaporatorRecipe) o; return (r.returnContainer() == returnContainer) && (areEqualNull(r.getInput(), input)) && (areEqualNull(r.getOutput(), output)) && (areEqualNull(r.getSecondary(), secondary)); } @Override public String getRecipeInfo() { String s = ""; if (output != null) { s += output.getDisplayName(); } if (secondary != null) { if (output != null) { s += " + "; } s += this.secondary.getLocalizedName(); } return s; } } //Passes the list to the base list implementation, and adds the recipe
private static class Add extends AMTListAddition {
0
ragnraok/JParserUtil
src/main/java/com/ragnarok/jparseutil/memberparser/TypeParser.java
[ "public class SourceInfo {\n \n public static final String TAG = \"JParserUtil.SourceInfo\";\n \n private String fileName;\n private List<String> importClassNames = new ArrayList<>();\n private String packageName = null;\n \n private List<String> asteriskImports = new ArrayList<>();\n \n private Map<String, AnnotationInfo> annotationInfos = new TreeMap<>();\n \n /**\n * all class informations\n */\n private Map<String, ClassInfo> classInfos = new TreeMap<>();\n \n public void setFilename(String filename) {\n this.fileName = filename;\n }\n \n public String getFilename() {\n return this.fileName;\n }\n \n public void addImports(String importClass) {\n this.importClassNames.add(importClass);\n if (importClass.endsWith(\".*\")) {\n this.asteriskImports.add(importClass);\n }\n }\n \n public List<String> getImports() {\n return this.importClassNames;\n }\n \n public List<String> getAsteriskImports() {\n return this.asteriskImports;\n }\n \n public void setPackageName(String packageName) {\n this.packageName = packageName;\n }\n \n public String getPackageName() {\n return this.packageName;\n }\n \n public void addClassInfo(ClassInfo clazz) {\n if (clazz != null) {\n// Log.d(TAG, \"addClassInfo, name: %s, size: %d\", clazz.getSimpleName(), this.classInfos.size());\n this.classInfos.put(clazz.getQualifiedName(), clazz);\n }\n }\n \n public boolean isContainClass(String simpleClassName) {\n for (ClassInfo clazz : classInfos.values()) {\n if (clazz.getSimpleName().equals(simpleClassName)) {\n return true;\n }\n }\n return false;\n }\n \n public ClassInfo getClassInfoByQualifiedName(String qualifiedName) {\n return classInfos.get(qualifiedName);\n }\n \n public ClassInfo getClassInfoBySimpleName(String simpleName) {\n for (ClassInfo clazz : classInfos.values()) {\n if (clazz.getSimpleName().equals(simpleName)) {\n return clazz;\n }\n }\n return null;\n }\n \n public ClassInfo getClassInfoBySuffixName(String suffixName) {\n for (ClassInfo clazz : classInfos.values()) {\n if (clazz.getQualifiedName().endsWith(\".\" + suffixName)) {\n return clazz;\n }\n }\n return null;\n }\n \n public void updateClassInfoByQualifiedName(String qualifiedName, ClassInfo newClazz) {\n if (classInfos.containsKey(qualifiedName)) {\n classInfos.put(qualifiedName, newClazz);\n }\n }\n \n public List<ClassInfo> getAllClass() {\n List<ClassInfo> result = new ArrayList<>(this.classInfos.size());\n result.addAll(classInfos.values());\n return result;\n }\n \n public String dumpClazz() {\n String result = \"\";\n for (ClassInfo clazz : classInfos.values()) {\n result += clazz.getSimpleName() + \", \";\n }\n return result; \n }\n \n public void putAnnotaiotn(AnnotationInfo annotationInfo) {\n this.annotationInfos.put(annotationInfo.getQualifiedName(), annotationInfo);\n }\n \n public List<AnnotationInfo> getAllAnnotations() {\n List<AnnotationInfo> result = new ArrayList<>(this.annotationInfos.size());\n result.addAll(annotationInfos.values());\n return result;\n }\n \n public AnnotationInfo getAnnotationInfoByQualifiedName(String qualifiedName) {\n return annotationInfos.get(qualifiedName);\n }\n \n public void updateAnnotationByQualifiedName(String qualifiedName, AnnotationInfo annotationInfo) {\n if (annotationInfos.containsKey(qualifiedName)) {\n annotationInfos.put(qualifiedName, annotationInfo);\n }\n }\n\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder();\n result.append(String.format(\"{SourceInfo, filename: %s, packageName: %s\", fileName, packageName));\n result.append(\"\\n\");\n if (importClassNames.size() > 0) {\n for (String className : importClassNames) {\n result.append(String.format(\"importClass: %s, \", className));\n }\n }\n result.append(\"\\n\");\n if (annotationInfos.size() > 0) {\n for (AnnotationInfo annotationInfo : annotationInfos.values()) {\n result.append(annotationInfo.toString());\n result.append(\"\\n\");\n }\n }\n if (classInfos.size() > 0) {\n for (ClassInfo classInfo : classInfos.values()) {\n result.append(classInfo.toString());\n result.append(\"\\n\");\n }\n }\n result.append(\"}\");\n return result.toString();\n }\n}", "public class Type {\n \n public static final String TAG = \"JParserUtil.Type\";\n \n private String typeName; // fully qualified\n private boolean isPrimitive = false;\n private boolean isArray = false;\n private Type arrayElementType = null; // not null if isArray is true\n \n private boolean isUpdatedToQualifiedTypeName = false;\n \n private SourceInfo containedSourceInfo;\n \n public void setTypeName(String typeName) {\n this.typeName = typeName;\n }\n \n public String getTypeName() {\n if (CodeInfo.isParseFinish() && \n !isUpdatedToQualifiedTypeName && !Util.isPrimitive(typeName) && !Util.isVoidType(typeName) && !isArray) {\n if (this.typeName != null) {\n typeName = Util.parseTypeFromSourceInfo(containedSourceInfo, typeName);\n if (typeName != null && typeName.contains(\".\")) {\n isUpdatedToQualifiedTypeName = true;\n } else {\n if (!isUpdatedToQualifiedTypeName) { // not in import, sample package of this containedSourceInfo\n typeName = containedSourceInfo.getPackageName() + \".\" + typeName;\n isUpdatedToQualifiedTypeName = true;\n }\n }\n }\n }\n return this.typeName;\n }\n \n public void setPrimitive(boolean isPrimitive) {\n this.isPrimitive = isPrimitive;\n }\n \n public boolean isPrimitive() {\n return this.isPrimitive;\n }\n \n public void setArray(boolean isArray) {\n this.isArray = isArray;\n }\n \n public boolean isArray() {\n return this.isArray;\n }\n \n public void setArrayElementType(Type elemType) {\n this.arrayElementType = elemType;\n }\n \n public Type getArrayElementType() {\n return this.arrayElementType;\n }\n \n public void setContainedSourceInfo(SourceInfo sourceInfo) {\n this.containedSourceInfo = sourceInfo;\n }\n\n @Override\n public String toString() {\n if (!isArray) {\n return String.format(\"{type: %s, isPrimitive: %b, isArray: %b}\", getTypeName(), isPrimitive(), isArray());\n } else {\n return String.format(\"{type: %s, isPrimitive: %b, isArray: %b, arrayElemType: %s}\", getTypeName(), isPrimitive(), isArray(), arrayElementType);\n }\n }\n \n \n}", "public class Log {\n\n /**\n * log level definitions\n */\n public static final int VERBOSE = 1;\n public static final int DEBUG = 2;\n public static final int INFO = 3;\n public static final int WARNING = 4;\n public static final int ERROR = 5;\n \n private static final String VERBOSE_COLOR = \"\\u001B[37m\";\n private static final String DEBUG_COLOR = \"\\u001B[34m\";\n private static final String INFO_COLOR = \"\\u001B[32m\";\n private static final String WARNING_COLOR = \"\\u001B[36m\";\n private static final String ERROR_COLOR = \"\\u001B[31m\";\n private static final String[] LOG_TEXT_COLOR = new String[] {VERBOSE_COLOR, DEBUG_COLOR, INFO_COLOR, WARNING_COLOR, ERROR_COLOR};\n private static final String ANSI_RESET = \"\\u001B[0m\";\n \n private static final String LOG_FORMAT = \"[%s/%s:%s] %s\"; // time/level: TAG content\n \n public static int MAX_SHOW_LOG_LEVEL = DEBUG;\n \n public static Set<String> SHOW_LOG_TAG = new HashSet<>();\n \n static {\n SHOW_LOG_TAG.add(SimpleJavaFileScanner.TAG);\n }\n \n public static void setMaxLogLevel(int maxLogLevel) {\n MAX_SHOW_LOG_LEVEL = maxLogLevel;\n }\n \n public static void addShowLogTAG(String TAG) {\n SHOW_LOG_TAG.add(TAG);\n }\n \n public static void v(String TAG, String format, Object... args) {\n println(VERBOSE, TAG, String.format(format, args));\n }\n \n public static void d(String TAG, String format, Object... args) {\n println(DEBUG, TAG, String.format(format, args));\n }\n \n public static void i(String TAG, String format, Object... args) {\n println(INFO, TAG, String.format(format, args));\n }\n \n public static void w(String TAG, String format, Object... args) {\n println(WARNING, TAG, String.format(format, args));\n }\n \n public static void e(String TAG, String format, Object... args) {\n println(ERROR, TAG, String.format(format, args));\n } \n \n private static String getCurrentLogTime() {\n return new SimpleDateFormat(\"K:mm:ss:SSS\").format(new Date());\n }\n \n private static String logLevelToString(int level) {\n switch (level) {\n case VERBOSE:\n return \"V\";\n case DEBUG:\n return \"D\";\n case INFO:\n return \"I\";\n case WARNING:\n return \"W\";\n case ERROR:\n return \"E\";\n }\n return \"\";\n }\n \n private static void println(int level, String tag, String content) {\n if (level >= MAX_SHOW_LOG_LEVEL && SHOW_LOG_TAG.contains(tag)) {\n System.out.println(String.format(LOG_TEXT_COLOR[level - 1] + LOG_FORMAT + ANSI_RESET, getCurrentLogTime(), logLevelToString(level), tag, content));\n }\n }\n}", "public class Primitive {\n public static String INT_TYPE = \"int\";\n public static String INTEGER_TYPE = \"Integer\";\n public static String STRING_TYPE = \"String\";\n public static String FLOAT_TYPE = \"float\";\n public static String FLOAT_PKG_TYPE = \"Float\";\n public static String DOUBLE_TYPE = \"double\";\n public static String DOUBLE_PKG_TYPE = \"Double\";\n public static String CHAR_TYPE = \"char\";\n public static String CHARACTER_TYPE = \"Character\";\n public static String LONG_TYPE = \"long\";\n public static String LONG_PKG_TYPE = \"Long\";\n public static String BOOLEAN_TYPE = \"boolean\";\n public static String BOOLEAN_PKG_TYPE = \"Boolean\";\n public static String NUMBER_TYPE = \"Number\";\n\n public static String[] PrimitiveTypes = new String[] {INT_TYPE, INTEGER_TYPE, STRING_TYPE,\n FLOAT_TYPE, FLOAT_PKG_TYPE, DOUBLE_TYPE, DOUBLE_PKG_TYPE, CHAR_TYPE, CHARACTER_TYPE,\n LONG_TYPE, LONG_PKG_TYPE, BOOLEAN_TYPE, BOOLEAN_PKG_TYPE, NUMBER_TYPE};\n \n public static String VOID_TYPE = \"void\";\n}", "public class Util {\n \n public static final String JAVA_FILE_SUFFIX = \".java\";\n \n public static boolean isPrimitive(String variableTypeName) {\n if (variableTypeName == null) {\n return false;\n }\n for (String type : Primitive.PrimitiveTypes) {\n if (type.equals(variableTypeName)) {\n return true;\n }\n }\n return false;\n }\n \n public static boolean isVoidType(String type) {\n if (type == null) {\n return false;\n }\n return type.equalsIgnoreCase(Primitive.VOID_TYPE);\n }\n\n // parse type from source imports\n public static String parseTypeFromSourceInfo(SourceInfo sourceInfo, String type) {\n if (isPrimitive(type)) {\n return type;\n }\n \n\n for (String className : sourceInfo.getImports()) {\n// String simpleClassName = className.substring(className.lastIndexOf(\".\") + 1);\n// if (simpleClassName.equals(type)) {\n// return className;\n// }\n if (!className.endsWith(\"*\")) {\n String simpleClassName = className.substring(className.lastIndexOf(\".\") + 1);\n if (simpleClassName.equals(type)) {\n return className;\n }\n } else {\n // import *\n String fullQualifiedClassName = ReferenceSourceMap.getInstance().searchClassNameByPrefixAndSimpleClassName(className, type);\n if (fullQualifiedClassName != null) {\n return fullQualifiedClassName;\n }\n }\n }\n \n // parse for annotation type\n for (AnnotationInfo annotationInfo : sourceInfo.getAllAnnotations()) {\n String name = annotationInfo.getQualifiedName();\n if (name != null && name.endsWith(type)) {\n return name;\n }\n }\n\n // for inner class variable, currently may not add in sourceInfo, so we will\n // update type later\n ClassInfo classInfo = sourceInfo.getClassInfoBySuffixName(type);\n if (classInfo != null) {\n return classInfo.getQualifiedName();\n }\n\n return type; // is import from java.lang\n }\n \n public static Object getValueFromLiteral(LiteralExpr literal) {\n if (literal instanceof BooleanLiteralExpr) {\n return ((BooleanLiteralExpr) literal).getValue();\n } else if (literal instanceof IntegerLiteralExpr) {\n return ((IntegerLiteralExpr) literal).getValue();\n } else if (literal instanceof LongLiteralExpr) {\n return ((LongLiteralExpr) literal).getValue();\n } else if (literal instanceof DoubleLiteralExpr) {\n return ((DoubleLiteralExpr) literal).getValue();\n } else if (literal instanceof CharLiteralExpr) {\n return ((CharLiteralExpr) literal).getValue();\n } else if (literal instanceof NullLiteralExpr) {\n return null;\n } else if (literal instanceof StringLiteralExpr) {\n return ((StringLiteralExpr) literal).getValue();\n } else {\n return literal.toString();\n }\n }\n \n public static String buildClassName(String prefix, String simpleName) {\n simpleName = simpleName.replace(\".\", \"\");\n if (prefix.endsWith(\".\")) {\n return prefix + simpleName;\n } else {\n return prefix + \".\" + simpleName;\n }\n }\n \n public static boolean isStringInFile(String filename, List<String> stringList) {\n String content = getFileContent(filename);\n if (content == null) {\n return false;\n }\n for (String str : stringList) {\n if (content.contains(str)) {\n return true;\n }\n }\n return false;\n }\n \n public static String getFileContent(String filename) {\n File file;\n FileChannel channel;\n MappedByteBuffer buffer;\n\n file = new File(filename);\n FileInputStream fin = null;\n try {\n fin = new FileInputStream(file);\n channel = fin.getChannel();\n buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());\n byte[] contentBytes = new byte[buffer.remaining()];\n buffer.get(contentBytes);\n String content = new String(contentBytes);\n return content;\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if (fin != null) {\n try {\n fin.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n return null;\n }\n}" ]
import com.github.javaparser.ast.type.ReferenceType; import com.ragnarok.jparseutil.dataobject.SourceInfo; import com.ragnarok.jparseutil.dataobject.Type; import com.ragnarok.jparseutil.util.Log; import com.ragnarok.jparseutil.util.Primitive; import com.ragnarok.jparseutil.util.Util; import com.sun.source.tree.Tree; import com.sun.tools.javac.tree.JCTree;
package com.ragnarok.jparseutil.memberparser; /** * Created by ragnarok on 15/6/28. * parser for the variable type */ public class TypeParser { public static final String TAG = "JParserUtil.TypeParser";
public static Type parseType(SourceInfo sourceInfo, com.github.javaparser.ast.type.Type typeElement, String typeName) {
0
njustesen/hero-aicademy
src/ai/NmSearchAI.java
[ "public class GameState {\n\t\n\tpublic static int TURN_LIMIT = 100;\n\tpublic static boolean RANDOMNESS = false;\n\tpublic static int STARTING_AP = 3;\n\tpublic static int ACTION_POINTS = 5;\n\t\n\tprivate static final int ASSAULT_BONUS = 300;\n\tprivate static final double INFERNO_DAMAGE = 350;\n\tprivate static final int REQUIRED_UNITS = 3;\n\tprivate static final int POTION_REVIVE = 100;\n\tprivate static final int POTION_HEAL = 1000;\n\tpublic static final boolean OPEN_HANDS = false;\n\n\tpublic HaMap map;\n\tpublic boolean p1Turn;\n\tpublic int turn;\n\tpublic int APLeft;\n\tpublic Unit[][] units;\n\tpublic CardSet p1Deck;\n\tpublic CardSet p2Deck;\n\tpublic CardSet p1Hand;\n\tpublic CardSet p2Hand;\n\tpublic boolean isTerminal;\n\n\tpublic List<Position> chainTargets;\n\n\tpublic GameState(HaMap map) {\n\t\tsuper();\n\t\tisTerminal = false;\n\t\tthis.map = map;\n\t\tp1Turn = true;\n\t\tturn = 1;\n\t\tAPLeft = STARTING_AP;\n\t\tp1Hand = new CardSet();\n\t\tp2Hand = new CardSet();\n\t\tp1Deck = new CardSet();\n\t\tp2Deck = new CardSet();\n\t\tchainTargets = new ArrayList<Position>();\n\t\tif (map != null)\n\t\t\tunits = new Unit[map.width][map.height];\n\t\telse\n\t\t\tunits = new Unit[0][0];\n\t}\n\n\tpublic GameState(HaMap map, boolean p1Turn, int turn, int APLeft,\n\t\t\tUnit[][] units, CardSet p1Hand, CardSet p2Hand, CardSet p1Deck,\n\t\t\tCardSet p2Deck, List<Position> chainTargets, boolean isTerminal) {\n\t\tsuper();\n\t\tthis.map = map;\n\t\tthis.p1Turn = p1Turn;\n\t\tthis.turn = turn;\n\t\tthis.APLeft = APLeft;\n\t\tthis.units = units;\n\t\tthis.p1Hand = p1Hand;\n\t\tthis.p2Hand = p2Hand;\n\t\tthis.p1Deck = p1Deck;\n\t\tthis.p2Deck = p2Deck;\n\t\tthis.chainTargets = chainTargets;\n\t\tthis.isTerminal = isTerminal;\n\t\t\n\t}\n\n\tpublic void init(DECK_SIZE deckSize) {\n\t\tp1Hand = new CardSet();\n\t\tp2Hand = new CardSet();\n\t\tp1Deck = new CardSet();\n\t\tp2Deck = new CardSet();\n\t\tshuffleDecks(deckSize);\n\t\tdealCards();\n\t\tfor (final Position pos : map.p1Crystals) {\n\t\t\tunits[pos.x][pos.y] = new Unit(Card.CRYSTAL, true);\n\t\t\tunits[pos.x][pos.y].init(Card.CRYSTAL, true);\n\t\t}\n\t\tfor (final Position pos : map.p2Crystals) {\n\t\t\tunits[pos.x][pos.y] = new Unit(Card.CRYSTAL, false);\n\t\t\tunits[pos.x][pos.y].init(Card.CRYSTAL, false);\n\t\t}\n\t}\n\n\tprivate void shuffleDecks(DECK_SIZE deckSize) {\n\t\tfor (final Card type : Council.deck(deckSize)) {\n\t\t\tp1Deck.add(type);\n\t\t\tp2Deck.add(type);\n\t\t}\n\t}\n\n\tpublic void possibleActions(List<Action> actions) {\n\n\t\tactions.clear();\n\n\t\tif (APLeft == 0) {\n\t\t\tactions.add(SingletonAction.endTurnAction);\n\t\t\treturn;\n\t\t}\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tpossibleActions(units[x][y], SingletonAction.positions[x][y], actions);\n\n\t\tfinal List<Card> visited = new ArrayList<Card>();\n\t\tfor (final Card card : Card.values())\n\t\t\tif (currentHand().contains(card)) {\n\t\t\t\tpossibleActions(card, actions);\n\t\t\t\tvisited.add(card);\n\t\t\t}\n\n\t}\n\n\tpublic void possibleActions(Card card, List<Action> actions) {\n\n\t\tif (APLeft == 0)\n\t\t\treturn;\n\n\t\tif (card.type == CardType.ITEM) {\n\t\t\tfor (int x = 0; x < map.width; x++)\n\t\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\t\tif (units[x][y] != null\n\t\t\t\t\t\t\t&& units[x][y].unitClass.card != Card.CRYSTAL) {\n\t\t\t\t\t\tif (units[x][y].equipment.contains(card))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (units[x][y].p1Owner == p1Turn) {\n\t\t\t\t\t\t\tif (card == Card.REVIVE_POTION\n\t\t\t\t\t\t\t\t\t&& units[x][y].fullHealth())\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif (card != Card.REVIVE_POTION\n\t\t\t\t\t\t\t\t\t&& units[x][y].hp == 0)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[x][y]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t} else if (card.type == CardType.SPELL)\n\t\t\tfor (int x = 0; x < map.width; x++)\n\t\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[x][y]));\n\t\telse if (card.type == CardType.UNIT)\n\t\t\tif (p1Turn) {\n\t\t\t\tfor (final Position pos : map.p1DeploySquares)\n\t\t\t\t\tif (units[pos.x][pos.y] == null\n\t\t\t\t\t\t\t|| units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[pos.x][pos.y]));\n\t\t\t} else\n\t\t\t\tfor (final Position pos : map.p2DeploySquares)\n\t\t\t\t\tif (units[pos.x][pos.y] == null\n\t\t\t\t\t\t\t|| units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[pos.x][pos.y]));\n\n\t\tif (!currentDeck().isEmpty())\n\t\t\tactions.add(SingletonAction.swapActions.get(card));\n\n\t}\n\n\tpublic void possibleActions(Unit unit, Position from, List<Action> actions) {\n\n\t\tif (unit.unitClass.card == Card.CRYSTAL)\n\t\t\treturn;\n\n\t\tif (APLeft == 0 || unit.hp == 0 || APLeft == 0\n\t\t\t\t|| unit.p1Owner != p1Turn)\n\t\t\treturn;\n\n\t\t// Movement and attack\n\t\tint d = unit.unitClass.speed;\n\t\tif (unit.unitClass.heal != null && unit.unitClass.heal.range > d)\n\t\t\td = unit.unitClass.heal.range;\n\t\tif (unit.unitClass.attack != null && unit.unitClass.attack.range > d)\n\t\t\td = unit.unitClass.attack.range;\n\t\tif (unit.unitClass.swap)\n\t\t\td = Math.max(map.width, map.height);\n\t\tfor (int x = d * (-1); x <= d; x++)\n\t\t\tfor (int y = d * (-1); y <= d; y++) {\n\t\t\t\tif (from.x + x >= map.width || from.x + x < 0 || from.y + y >= map.height || from.y + y < 0)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfinal Position to = SingletonAction.positions[from.x + x][from.y +y];\n\t\t\t\t\n\t\t\t\tif (to.equals(from))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (units[to.x][to.y] != null) {\n\n\t\t\t\t\tif (units[to.x][to.y].hp == 0) {\n\n\t\t\t\t\t\tif ((map.squares[to.x][to.y] == SquareType.DEPLOY_1 && !p1Turn)\n\t\t\t\t\t\t\t\t|| (map.squares[to.x][to.y] == SquareType.DEPLOY_2 && p1Turn)) {\n\t\t\t\t\t\t\t// NOT ALLOWED!\n\t\t\t\t\t\t} else if (unit.unitClass.heal != null\n\t\t\t\t\t\t\t\t&& from.distance(to) <= unit.unitClass.heal.range)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.HEAL));\n\t\t\t\t\t\telse if (from.distance(to) <= unit.unitClass.speed)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.MOVE));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfinal int distance = from.distance(to);\n\t\t\t\t\t\tif (unit.p1Owner != units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& distance <= unit.unitClass.attack.range) {\n\t\t\t\t\t\t\tif (!(distance > 1 && losBlocked(p1Turn, from, to)))\n\t\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\t\tUnitActionType.ATTACK));\n\t\t\t\t\t\t} else if (unit.p1Owner == units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& unit.unitClass.heal != null\n\t\t\t\t\t\t\t\t&& from.distance(to) <= unit.unitClass.heal.range\n\t\t\t\t\t\t\t\t&& !units[to.x][to.y].fullHealth()\n\t\t\t\t\t\t\t\t&& units[to.x][to.y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.HEAL));\n\t\t\t\t\t\telse if (unit.p1Owner == units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& unit.unitClass.swap\n\t\t\t\t\t\t\t\t&& units[to.x][to.y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.SWAP));\n\t\t\t\t\t}\n\n\t\t\t\t} else if (from.distance(to) <= unit.unitClass.speed)\n\t\t\t\t\tif ((map.squares[to.x][to.y] == SquareType.DEPLOY_1 && !p1Turn)\n\t\t\t\t\t\t\t|| (map.squares[to.x][to.y] == SquareType.DEPLOY_2 && p1Turn)) {\n\t\t\t\t\t\t// NOT ALLOWED!\n\t\t\t\t\t} else\n\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\tUnitActionType.MOVE));\n\t\t\t}\n\t}\n\n\tpublic void update(List<Action> actions) {\n\t\tfor (final Action action : actions)\n\t\t\tupdate(action);\n\t}\n\n\tpublic void update(Action action) {\n\n\t\ttry {\n\t\t\tchainTargets.clear();\n\n\t\t\tif (action instanceof EndTurnAction || APLeft <= 0)\n\t\t\t\tendTurn();\n\n\t\t\tif (action instanceof DropAction) {\n\n\t\t\t\tfinal DropAction drop = (DropAction) action;\n\n\t\t\t\t// Not a type in current players hand\n\t\t\t\tif (!currentHand().contains(drop.type))\n\t\t\t\t\treturn;\n\n\t\t\t\t// Unit\n\t\t\t\tif (drop.type.type == CardType.UNIT) {\n\n\t\t\t\t\t// Not current players deploy square\n\t\t\t\t\tif (map.squares[drop.to.x][drop.to.y] == SquareType.DEPLOY_1\n\t\t\t\t\t\t\t&& !p1Turn)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tif (map.squares[drop.to.x][drop.to.y] == SquareType.DEPLOY_2\n\t\t\t\t\t\t\t&& p1Turn)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tdeploy(drop.type, drop.to);\n\n\t\t\t\t}\n\n\t\t\t\t// Equipment\n\t\t\t\tif (drop.type.type == CardType.ITEM) {\n\n\t\t\t\t\t// Not a unit square or crystal\n\t\t\t\t\tif (units[drop.to.x][drop.to.y] == null\n\t\t\t\t\t\t\t|| units[drop.to.x][drop.to.y].unitClass.card == Card.CRYSTAL)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (units[drop.to.x][drop.to.y].p1Owner != p1Turn)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (drop.type == Card.REVIVE_POTION\n\t\t\t\t\t\t\t&& (units[drop.to.x][drop.to.y].unitClass.card == Card.CRYSTAL || units[drop.to.x][drop.to.y]\n\t\t\t\t\t\t\t\t\t.fullHealth()))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (drop.type != Card.REVIVE_POTION\n\t\t\t\t\t\t\t&& units[drop.to.x][drop.to.y].hp == 0)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (units[drop.to.x][drop.to.y].equipment\n\t\t\t\t\t\t\t.contains(drop.type))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tequip(drop.type, drop.to);\n\n\t\t\t\t}\n\n\t\t\t\t// Spell\n\t\t\t\tif (drop.type.type == CardType.SPELL)\n\t\t\t\t\tdropInferno(drop.to);\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tif (action instanceof UnitAction) {\n\n\t\t\t\tfinal UnitAction ua = (UnitAction) action;\n\n\t\t\t\tif (units[ua.from.x][ua.from.y] == null)\n\t\t\t\t\treturn;\n\n\t\t\t\tfinal Unit unit = units[ua.from.x][ua.from.y];\n\n\t\t\t\tif (unit == null)\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tif (unit.p1Owner != p1Turn)\n\t\t\t\t\treturn;\n\n\t\t\t\tif (unit.hp == 0)\n\t\t\t\t\treturn;\n\n\t\t\t\t// Move\n\t\t\t\tif (units[ua.to.x][ua.to.y] == null\n\t\t\t\t\t\t|| (unit.p1Owner == units[ua.to.x][ua.to.y].p1Owner\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].hp == 0 && unit.unitClass.heal == null)\n\t\t\t\t\t\t|| (unit.p1Owner != units[ua.to.x][ua.to.y].p1Owner && units[ua.to.x][ua.to.y].hp == 0)) {\n\n\t\t\t\t\tif (ua.from.distance(ua.to) > units[ua.from.x][ua.from.y].unitClass.speed)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (map.squares[ua.to.x][ua.to.y] == SquareType.DEPLOY_1\n\t\t\t\t\t\t\t&& !unit.p1Owner)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (map.squares[ua.to.x][ua.to.y] == SquareType.DEPLOY_2\n\t\t\t\t\t\t\t&& unit.p1Owner)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tmove(unit, ua.from, ua.to);\n\t\t\t\t\treturn;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tfinal Unit other = units[ua.to.x][ua.to.y];\n\n\t\t\t\t\t// Swap and heal\n\t\t\t\t\tif (unit.p1Owner == other.p1Owner) {\n\t\t\t\t\t\tif (unit.unitClass.swap\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].unitClass.card != Card.CRYSTAL\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].hp != 0) {\n\t\t\t\t\t\t\tswap(unit, ua.from, other, ua.to);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (unit.unitClass.heal == null)\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\tif (ua.from.distance(ua.to) > unit.unitClass.heal.range)\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\tif (other.fullHealth())\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\theal(unit, ua.from, other);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Attack\n\t\t\t\t\tfinal int distance = ua.from.distance(ua.to);\n\t\t\t\t\tif (unit.unitClass.attack != null\n\t\t\t\t\t\t\t&& distance > unit.unitClass.attack.range)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (distance > 1 && losBlocked(p1Turn, ua.from, ua.to))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (other == null)\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\n\t\t\t\t\tattack(unit, ua.from, other, ua.to);\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (action instanceof SwapCardAction) {\n\n\t\t\t\tfinal Card card = ((SwapCardAction) action).card;\n\n\t\t\t\tif (currentHand().contains(card)) {\n\n\t\t\t\t\tcurrentDeck().add(card);\n\t\t\t\t\tcurrentHand().remove(card);\n\t\t\t\t\tAPLeft--;\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t} catch (final Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t/**\n\t * Using the Bresenham-based super-cover line algorithm\n\t * \n\t * @param from\n\t * @param to\n\t * @return\n\t */\n\tpublic boolean losBlocked(boolean p1, Position from, Position to) {\n\n\t\tif (from.distance(to) == 1\n\t\t\t\t|| (from.getDirection(to).isDiagonal() && from.distance(to) == 2))\n\t\t\treturn false;\n\n\t\tfor (final Position pos : CachedLines.supercover(from, to)) {\n\t\t\tif (pos.equals(from) || pos.equals(to))\n\t\t\t\tcontinue;\n\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].p1Owner != p1\n\t\t\t\t\t&& units[pos.x][pos.y].hp != 0)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tprivate void dropInferno(Position to) throws Exception {\n\n\t\tfor (int x = -1; x <= 1; x++)\n\t\t\tfor (int y = -1; y <= 1; y++) {\n\t\t\t\tif (to.x + x < 0 || to.x + x >= map.width || to.y + y < 0 || to.y + y >= map.height)\n\t\t\t\t\tcontinue;\n\t\t\t\tfinal Position pos = SingletonAction.positions[to.x + x][to.y + y];\n\t\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t\t&& units[pos.x][pos.y].p1Owner != p1Turn) {\n\t\t\t\t\tif (units[pos.x][pos.y].hp == 0) {\n\t\t\t\t\t\tunits[pos.x][pos.y] = null;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdouble damage = INFERNO_DAMAGE;\n\t\t\t\t\tif (units[pos.x][pos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\t\tfinal int bonus = assaultBonus();\n\t\t\t\t\t\tdamage += bonus;\n\t\t\t\t\t}\n\t\t\t\t\tfinal double resistance = units[pos.x][pos.y].resistance(\n\t\t\t\t\t\t\tthis, pos, AttackType.Magical);\n\t\t\t\t\tdamage = damage * ((100d - resistance) / 100d);\n\t\t\t\t\tunits[pos.x][pos.y].hp -= damage;\n\t\t\t\t\tif (units[pos.x][pos.y].hp <= 0)\n\t\t\t\t\t\tif (units[pos.x][pos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t\t\t\tunits[pos.x][pos.y] = null;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tunits[pos.x][pos.y].hp = 0;\n\t\t\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcurrentHand().remove(Card.INFERNO);\n\t\tAPLeft--;\n\n\t}\n\n\tprivate void attack(Unit attacker, Position attPos, Unit defender, Position defPos) throws Exception {\n\t\tif (attacker.unitClass.attack == null)\n\t\t\treturn;\n\t\tif (defender.hp == 0) {\n\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t\tmove(attacker, attPos, defPos);\n\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t} else {\n\t\t\tint damage = attacker.damage(this, attPos, defender, defPos);\n\t\t\tif (defender.unitClass.card == Card.CRYSTAL) {\n\t\t\t\tfinal int bonus = assaultBonus();\n\t\t\t\tdamage += bonus;\n\t\t\t}\n\t\t\tdefender.hp -= damage;\n\t\t\tif (defender.hp <= 0) {\n\t\t\t\tdefender.hp = 0;\n\t\t\t\tif (defender.unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t} else {\n\t\t\t\t\tunits[defPos.x][defPos.y].hp = 0;\n\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (attacker.unitClass.attack.push)\n\t\t\t\tpush(defender, attPos, defPos);\n\t\t\tif (attacker.unitClass.attack.chain)\n\t\t\t\tchain(attacker,\n\t\t\t\t\t\tattPos,\n\t\t\t\t\t\tdefPos,\n\t\t\t\t\t\tDirection.direction(defPos.x - attPos.x, defPos.y\n\t\t\t\t\t\t\t\t- attPos.y), 1);\n\t\t}\n\t\tattacker.equipment.remove(Card.SCROLL);\n\t\tAPLeft--;\n\t}\n\n\tprivate void chain(Unit attacker, Position attPos, Position from,\n\t\t\tDirection dir, int jump) throws Exception {\n\n\t\tif (jump >= 3)\n\t\t\treturn;\n\n\t\tfinal Position bestPos = nextJump(from, dir);\n\n\t\t// Attack\n\t\tif (bestPos != null) {\n\t\t\tchainTargets.add(bestPos);\n\t\t\tint damage = attacker.damage(this, attPos,\n\t\t\t\t\tunits[bestPos.x][bestPos.y], bestPos);\n\t\t\tif (jump == 1)\n\t\t\t\tdamage = (int) (damage * 0.75);\n\t\t\telse if (jump == 2)\n\t\t\t\tdamage = (int) (damage * 0.56);\n\t\t\telse\n\t\t\t\tSystem.out.println(\"Illegal number of jumps!\");\n\n\t\t\tif (units[bestPos.x][bestPos.y].unitClass.card == Card.CRYSTAL)\n\t\t\t\tdamage += assaultBonus();\n\n\t\t\tunits[bestPos.x][bestPos.y].hp -= damage;\n\t\t\tif (units[bestPos.x][bestPos.y].hp <= 0) {\n\t\t\t\tunits[bestPos.x][bestPos.y].hp = 0;\n\t\t\t\tif (units[bestPos.x][bestPos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t\tunits[bestPos.x][bestPos.y] = null;\n\t\t\t\t} else {\n\t\t\t\t\tunits[bestPos.x][bestPos.y].hp = 0;\n\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tchain(attacker, attPos, bestPos, from.getDirection(bestPos),\n\t\t\t\t\tjump + 1);\n\t\t}\n\n\t}\n\n\tprivate Position nextJump(Position from, Direction dir) {\n\n\t\tint bestValue = 0;\n\t\tPosition bestPos = null;\n\n\t\t// Find best target\n\t\tfor (int newDirX = -1; newDirX <= 1; newDirX++)\n\t\t\tfor (int newDirY = -1; newDirY <= 1; newDirY++) {\n\t\t\t\tif (newDirX == 0 && newDirY == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (from.x + newDirX < 0 || from.x + newDirX >= map.width || from.y + newDirY < 0 || from.y + newDirY >= map.height)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfinal Position newPos = SingletonAction.positions[from.x + newDirX][from.y + newDirY];\n\t\t\t\t\n\t\t\t\tif (units[newPos.x][newPos.y] != null\n\t\t\t\t\t\t&& units[newPos.x][newPos.y].p1Owner != p1Turn\n\t\t\t\t\t\t&& units[newPos.x][newPos.y].hp > 0) {\n\n\t\t\t\t\tfinal Direction newDir = Direction.direction(newDirX,\n\t\t\t\t\t\t\tnewDirY);\n\n\t\t\t\t\tif (newDir.opposite(dir))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfinal int chainValue = chainValue(dir, newDir);\n\n\t\t\t\t\tif (chainValue > bestValue) {\n\t\t\t\t\t\tbestPos = newPos;\n\t\t\t\t\t\tbestValue = chainValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\treturn bestPos;\n\t}\n\n\tprivate int chainValue(Direction dir, Direction newDir) {\n\n\t\tif (dir.equals(newDir))\n\t\t\treturn 10;\n\n\t\tint value = 1;\n\n\t\tif (!newDir.isDiagonal())\n\t\t\tvalue += 4;\n\n\t\tif (newDir.isNorth())\n\t\t\tvalue += 2;\n\n\t\tif (newDir.isEast())\n\t\t\tvalue += 1;\n\n\t\treturn value;\n\n\t}\n\n\tprivate int assaultBonus() {\n\t\tint bonus = 0;\n\t\tfor (final Position pos : map.assaultSquares)\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].p1Owner == p1Turn\n\t\t\t\t\t&& units[pos.x][pos.y].hp != 0)\n\t\t\t\tbonus += ASSAULT_BONUS;\n\t\treturn bonus;\n\t}\n\n\tprivate void checkWinOnUnits(int p) {\n\n\t\tif (!aliveOnUnits(p))\n\t\t\tisTerminal = true;\n\n\t}\n\n\tprivate void checkWinOnCrystals(int p) {\n\n\t\tif (!aliveOnCrystals(p))\n\t\t\tisTerminal = true;\n\n\t}\n\n\tpublic int getWinner() {\n\n\t\tif (turn >= TURN_LIMIT)\n\t\t\treturn 0;\n\t\t\n\t\tboolean p1Alive = true;\n\t\tboolean p2Alive = true;\n\n\t\tif (!aliveOnCrystals(1) || !aliveOnUnits(1))\n\t\t\tp1Alive = false;\n\n\t\tif (!aliveOnCrystals(2) || !aliveOnUnits(2))\n\t\t\tp2Alive = false;\n\n\t\tif (p1Alive == p2Alive)\n\t\t\treturn 0;\n\n\t\tif (p1Alive)\n\t\t\treturn 1;\n\n\t\tif (p2Alive)\n\t\t\treturn 2;\n\n\t\treturn 0;\n\n\t}\n\n\tprivate boolean aliveOnCrystals(int player) {\n\n\t\tfor (final Position pos : crystals(player))\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].unitClass.card == Card.CRYSTAL\n\t\t\t\t\t&& units[pos.x][pos.y].hp > 0)\n\t\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate List<Position> crystals(int player) {\n\t\tif (player == 1)\n\t\t\treturn map.p1Crystals;\n\t\tif (player == 2)\n\t\t\treturn map.p2Crystals;\n\t\treturn null;\n\t}\n\n\tprivate boolean aliveOnUnits(int player) {\n\n\t\tif (deck(player).hasUnits() || hand(player).hasUnits())\n\t\t\treturn true;\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null && units[x][y].p1Owner == (player == 1)\n\t\t\t\t\t\t&& units[x][y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate CardSet deck(int player) {\n\t\tif (player == 1)\n\t\t\treturn p1Deck;\n\t\tif (player == 2)\n\t\t\treturn p2Deck;\n\t\treturn null;\n\t}\n\n\tprivate CardSet hand(int player) {\n\t\tif (player == 1)\n\t\t\treturn p1Hand;\n\t\tif (player == 2)\n\t\t\treturn p2Hand;\n\t\treturn null;\n\t}\n\n\tprivate void push(Unit defender, Position attPos, Position defPos)\n\t\t\tthrows Exception {\n\n\t\tif (defender.unitClass.card == Card.CRYSTAL)\n\t\t\treturn;\n\n\t\tint x = 0;\n\t\tint y = 0;\n\n\t\tif (attPos.x > defPos.x)\n\t\t\tx = -1;\n\t\tif (attPos.x < defPos.x)\n\t\t\tx = 1;\n\t\tif (attPos.y > defPos.y)\n\t\t\ty = -1;\n\t\tif (attPos.y < defPos.y)\n\t\t\ty = 1;\n\n\t\tif (defPos.x + x >= map.width || defPos.x + x < 0 || defPos.y + y >= map.height || defPos.y + y < 0)\n\t\t\treturn;\n\n\t\tfinal Position newPos = SingletonAction.positions[defPos.x + x][defPos.y + y];\n\t\t\n\t\tif (units[newPos.x][newPos.y] != null\n\t\t\t\t&& units[newPos.x][newPos.y].hp > 0)\n\t\t\treturn;\n\n\t\tif (map.squareAt(newPos) == SquareType.DEPLOY_1 && !defender.p1Owner)\n\t\t\treturn;\n\n\t\tif (map.squareAt(newPos) == SquareType.DEPLOY_2 && defender.p1Owner)\n\t\t\treturn;\n\n\t\tif (units[defPos.x][defPos.y] != null) {\n\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t}\n\n\t\tunits[newPos.x][newPos.y] = defender;\n\n\t}\n\n\tprivate void heal(Unit healer, Position pos, Unit unitTo) {\n\n\t\tint power = healer.power(this, pos);\n\n\t\tif (unitTo.hp == 0)\n\t\t\tpower *= healer.unitClass.heal.revive;\n\t\telse\n\t\t\tpower *= healer.unitClass.heal.heal;\n\t\t\n\t\tunitTo.heal(power);\n\t\thealer.equipment.remove(Card.SCROLL);\n\t\t\n\t\tAPLeft--;\n\n\t}\n\n\tprivate void swap(Unit unitFrom, Position from, Unit unitTo, Position to) {\n\t\tunits[from.x][from.y] = unitTo;\n\t\tunits[to.x][to.y] = unitFrom;\n\t\tAPLeft--;\n\t}\n\n\tprivate void move(Unit unit, Position from, Position to) throws Exception {\n\t\tunits[from.x][from.y] = null;\n\t\tunits[to.x][to.y] = unit;\n\t\tAPLeft--;\n\t}\n\n\tprivate void equip(Card card, Position pos) {\n\t\tif (card == Card.REVIVE_POTION) {\n\t\t\tif (units[pos.x][pos.y].hp == 0)\n\t\t\t\tunits[pos.x][pos.y].heal(POTION_REVIVE);\n\t\t\telse\n\t\t\t\tunits[pos.x][pos.y].heal(POTION_HEAL);\n\t\t} else\n\t\t\tunits[pos.x][pos.y].equip(card, this);\n\t\tcurrentHand().remove(card);\n\t\tAPLeft--;\n\t}\n\n\tprivate void deploy(Card card, Position pos) {\n\t\tunits[pos.x][pos.y] = new Unit(card, p1Turn);\n\t\tcurrentHand().remove(card);\n\t\tAPLeft--;\n\t}\n\n\tprivate void endTurn() throws Exception {\n\t\tremoveDying(p1Turn);\n\t\tcheckWinOnUnits(1);\n\t\tcheckWinOnUnits(2);\n\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\tif (turn >= TURN_LIMIT)\n\t\t\tisTerminal = true;\n\t\tif (!isTerminal) {\n\t\t\tdrawCards();\n\t\t\tp1Turn = !p1Turn;\n\t\t\tdrawCards();\n\t\t\tAPLeft = ACTION_POINTS;\n\t\t\tturn++;\n\t\t}\n\t\t\n\t}\n\n\tpublic void dealCards() {\n\t\twhile (!legalStartingHand(p1Hand))\n\t\t\tdealCards(1);\n\n\t\twhile (!legalStartingHand(p2Hand))\n\t\t\tdealCards(2);\n\t}\n\n\tprivate void dealCards(int player) {\n\t\tif (player == 1) {\n\t\t\tp1Deck.addAll(p1Hand);\n\t\t\tp1Hand.clear();\n\t\t\t// Collections.shuffle(p1Deck);\n\t\t\tdrawHandFrom(p1Deck, p1Hand);\n\t\t} else if (player == 2) {\n\t\t\tp2Deck.addAll(p2Hand);\n\t\t\tp2Hand.clear();\n\t\t\t// Collections.shuffle(p2Hand);\n\t\t\tdrawHandFrom(p2Deck, p2Hand);\n\t\t}\n\n\t}\n\n\tprivate boolean legalStartingHand(CardSet hand) {\n\t\tif (hand.size != 6)\n\t\t\treturn false;\n\n\t\tif (hand.units() == REQUIRED_UNITS)\n\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate void drawHandFrom(CardSet deck, CardSet hand) {\n\n\t\tCard card = null;\n\t\twhile (!deck.isEmpty() && hand.size < 6) {\n\t\t\tif (RANDOMNESS)\n\t\t\t\tcard = deck.random();\n\t\t\telse\n\t\t\t\tcard = deck.determined();\n\t\t\thand.add(card);\n\t\t\tdeck.remove(card);\n\t\t}\n\n\t}\n\n\tprivate void drawCards() {\n\n\t\tdrawHandFrom(currentDeck(), currentHand());\n\n\t}\n\n\tpublic CardSet currentHand() {\n\t\tif (p1Turn)\n\t\t\treturn p1Hand;\n\t\treturn p2Hand;\n\t}\n\n\tpublic CardSet currentDeck() {\n\t\tif (p1Turn)\n\t\t\treturn p1Deck;\n\t\treturn p2Deck;\n\t}\n\n\tpublic void removeDying(boolean p1) throws Exception {\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null && units[x][y].p1Owner == p1\n\t\t\t\t\t\t&& units[x][y].hp == 0) {\n\t\t\t\t\tunits[x][y] = null;\n\t\t\t\t}\n\t}\n\n\tpublic GameState copy() {\n\t\tfinal Unit[][] un = new Unit[map.width][map.height];\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tun[x][y] = units[x][y].copy();\n\t\tfinal CardSet p1h = new CardSet(p1Hand.seed);\n\t\tp1h.imitate(p1Hand);\n\t\tfinal CardSet p2h = new CardSet(p2Hand.seed);\n\t\tp2h.imitate(p2Hand);\n\t\tfinal CardSet p1d = new CardSet(p1Deck.seed);\n\t\tp1d.imitate(p1Deck);\n\t\tfinal CardSet p2d = new CardSet(p2Deck.seed);\n\t\tp2d.imitate(p2Deck);\n\n\t\treturn new GameState(map, p1Turn, turn, APLeft, un, p1h, p2h, p1d, p2d,\n\t\t\t\tchainTargets, isTerminal);\n\t}\n\n\tpublic void imitate(GameState state) {\n\n\t\tmap = state.map;\n\t\tif (units.length != state.units.length\n\t\t\t\t|| (state.units.length > 0 && units[0].length != state.units[0].length))\n\t\t\tunits = new Unit[map.width][map.height];\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++) {\n\t\t\t\tif (units[x][y] != null) \n\t\t\t\t\tunits[x][y] = null;\n\t\t\t\tif (state.units[x][y] != null) {\n\t\t\t\t\tunits[x][y] = new Unit(null, false);\n\t\t\t\t\tunits[x][y].imitate(state.units[x][y]);\n\t\t\t\t}\n\t\t\t}\n\t\tp1Hand.imitate(state.p1Hand);\n\t\tp2Hand.imitate(state.p2Hand);\n\t\tp1Deck.imitate(state.p1Deck);\n\t\tp2Deck.imitate(state.p2Deck);\n\t\tisTerminal = state.isTerminal;\n\t\tp1Turn = state.p1Turn;\n\t\tturn = state.turn;\n\t\tAPLeft = state.APLeft;\n\t\tmap = state.map;\n\t\t// chainTargets.clear();\n\t\t// chainTargets.addAll(state.chainTargets); // NOT NECESSARY\n\n\t}\n\t\n\tpublic long simpleHash() {\n\t\tfinal int prime = 1193;\n\t\tlong result = 1;\n\t\tresult = prime * result + (isTerminal ? 0 : 1);\n\t\tresult = prime * result + p1Hand.hashCode();\n\t\tresult = prime * result + p2Deck.hashCode();\n\t\tresult = prime * result + p2Hand.hashCode();\n\t\tresult = prime * result + p1Deck.hashCode();\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tresult = prime * result + units[x][y].hash(x, y);\n\n\t\treturn result;\n\t}\n\n\tpublic long hash() {\n\t\tfinal int prime = 1193;\n\t\tlong result = 1;\n\t\tresult = prime * result + APLeft;\n\t\tresult = prime * result + turn;\n\t\tresult = prime * result + (isTerminal ? 0 : 1);\n\t\tresult = prime * result + p1Hand.hashCode();\n\t\tresult = prime * result + p2Deck.hashCode();\n\t\tresult = prime * result + p2Hand.hashCode();\n\t\tresult = prime * result + p1Deck.hashCode();\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tresult = prime * result + units[x][y].hash(x, y);\n\n\t\treturn result;\n\t}\n\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\tfinal GameState other = (GameState) obj;\n\t\tif (APLeft != other.APLeft)\n\t\t\treturn false;\n\t\tif (isTerminal != other.isTerminal)\n\t\t\treturn false;\n\t\tif (map == null) {\n\t\t\tif (other.map != null)\n\t\t\t\treturn false;\n\t\t} else if (!map.equals(other.map))\n\t\t\treturn false;\n\t\tif (p1Deck == null) {\n\t\t\tif (other.p1Deck != null)\n\t\t\t\treturn false;\n\t\t} else if (!p1Deck.equals(other.p1Deck))\n\t\t\treturn false;\n\t\tif (p1Hand == null) {\n\t\t\tif (other.p1Hand != null)\n\t\t\t\treturn false;\n\t\t} else if (!p1Hand.equals(other.p1Hand))\n\t\t\treturn false;\n\t\tif (p1Turn != other.p1Turn)\n\t\t\treturn false;\n\t\tif (p2Deck == null) {\n\t\t\tif (other.p2Deck != null)\n\t\t\t\treturn false;\n\t\t} else if (!p2Deck.equals(other.p2Deck))\n\t\t\treturn false;\n\t\tif (p2Hand == null) {\n\t\t\tif (other.p2Hand != null)\n\t\t\t\treturn false;\n\t\t} else if (!p2Hand.equals(other.p2Hand))\n\t\t\treturn false;\n\t\tif (!Arrays.deepEquals(units, other.units))\n\t\t\treturn false;\n\t\tif (turn != other.turn)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic void print() {\n\t\tfinal List<Unit> p1Units = new ArrayList<Unit>();\n\t\tfinal List<Unit> p2Units = new ArrayList<Unit>();\n\t\tfor (int y = 0; y < units[0].length; y++) {\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor (int x = 0; x < units.length; x++)\n\t\t\t\tif (units[x][y] == null)\n\t\t\t\t\tSystem.out.print(\"__|\");\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.print(units[x][y].unitClass.card.name()\n\t\t\t\t\t\t\t.substring(0, 2) + \"|\");\n\t\t\t\t\tif (units[x][y].p1Owner)\n\t\t\t\t\t\tp1Units.add(units[x][y]);\n\t\t\t\t\telse\n\t\t\t\t\t\tp2Units.add(units[x][y]);\n\t\t\t\t}\n\t\t\tSystem.out.print(\"\\n\");\n\t\t}\n\t\tSystem.out.println(p1Hand);\n\t\tfor (final Unit unit : p1Units)\n\t\t\tSystem.out.println(unit);\n\t\tSystem.out.println(p2Hand);\n\t\tfor (final Unit unit : p2Units)\n\t\t\tSystem.out.println(unit);\n\n\t}\n\n\tpublic SquareType squareAt(Position pos) {\n\t\treturn map.squares[pos.x][pos.y];\n\t}\n\n\tpublic Unit unitAt(Position pos) {\n\t\treturn units[pos.x][pos.y];\n\t}\n\n\tpublic Unit unitAt(int x, int y) {\n\t\treturn units[x][y];\n\t}\n\n\tpublic int cardsLeft(int p) {\n\t\tif (p == 1)\n\t\t\treturn p1Deck.size + p1Hand.size;\n\t\telse if (p == 2)\n\t\t\treturn p2Deck.size + p2Hand.size;\n\t\treturn -1;\n\t}\n\n\tpublic void returnUnits() {\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null) \n\t\t\t\t\tunits[x][y] = null;\n\t}\n\n\tpublic void hideCards(boolean p1) {\n\t\tif (p1){\n\t\t\tfor(Card card : Card.values())\n\t\t\t\tfor(int i = 0; i < p1Hand.count(card); i++)\n\t\t\t\t\tp1Deck.add(card);\n\t\t\tp1Hand.clear();\n\t\t} else {\n\t\t\tfor(Card card : Card.values())\n\t\t\t\tfor(int i = 0; i < p2Hand.count(card); i++)\n\t\t\t\t\tp2Deck.add(card);\n\t\t\tp2Hand.clear();\n\t\t}\n\t}\n\n}", "public enum Card {\n\n\tKNIGHT(CardType.UNIT), \n\tARCHER(CardType.UNIT), \n\tCLERIC(CardType.UNIT), \n\tWIZARD(CardType.UNIT), \n\tNINJA(CardType.UNIT),\n\tINFERNO(CardType.SPELL), \n\tREVIVE_POTION(CardType.ITEM), \n\tRUNEMETAL(CardType.ITEM), \n\tSCROLL(CardType.ITEM), \n\tDRAGONSCALE(CardType.ITEM), \n\tSHINING_HELM(CardType.ITEM), \n\tCRYSTAL(CardType.UNIT);\n\t\n\tpublic final CardType type;\n\t\n\tCard(CardType type) {\n\t\tthis.type = type;\n\t}\n\t\n}", "public abstract class Action {\n\t\n}", "public class EndTurnAction extends Action {\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"EndTurnAction []\";\n\t}\n\t\n}", "public class HeuristicEvaluator implements IStateEvaluator {\n\n\tprivate static final double MAX_VAL = 60000;\n\tprivate boolean winVal;\n\tprivate List<Position> p1Healers;\n\tprivate List<Position> p2Healers;\n\tpublic boolean positional = false;\n\tpublic int healMultiplier = 150;\n\tpublic int spreadMultiplier = 50;\n\t\n\tpublic HeuristicEvaluator(boolean winVal) {\n\t\tthis.winVal = winVal;\n\t\tthis.p1Healers = new ArrayList<Position>();\n\t\tthis.p2Healers = new ArrayList<Position>();\n\t}\n\n\tpublic double eval(GameState state, boolean p1) {\n\t\t\n\t\t//findHealers(state);\n\t\t\n\t\tif (state.isTerminal){\n\t\t\tint winner = state.getWinner();\n\t\t\tif (!winVal && winner == 1)\n\t\t\t\treturn p1 ? MAX_VAL : -MAX_VAL;\n\t\t\telse if (!winVal && winner == 2)\n\t\t\t\treturn p1 ? -MAX_VAL : MAX_VAL;\n\t\t\telse if (winVal && winner == 1)\n\t\t\t\treturn p1 ? 1 : 0;\n\t\t\telse if (winVal && winner == 2)\n\t\t\t\treturn p1 ? 0 : 1;\n\t\t\t\n\t\t\tif (winVal)\n\t\t\t\treturn 0.5;\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tint hpDif = hpDif(state, p1);\n\t\t\n\t\tif (!winVal)\n\t\t\treturn hpDif;\n\t\t\n\t\treturn NormUtil.normalize(hpDif, -MAX_VAL, MAX_VAL, 1, 0);\n\n\t}\n\n\tprivate void findHealers(GameState state) {\n\t\tp1Healers.clear();\n\t\tp2Healers.clear();\n\t\tfor (int x = 0; x < state.map.width; x++)\n\t\t\tfor (int y = 0; y < state.map.height; y++)\n\t\t\t\tif (state.units[x][y] != null && state.units[x][y].hp != 0 && state.units[x][y].unitClass.card == Card.CLERIC)\n\t\t\t\t\tif (state.units[x][y].p1Owner)\n\t\t\t\t\t\tp1Healers.add(SingletonAction.positions[x][y]);\n\t\t\t\t\telse\n\t\t\t\t\t\tp2Healers.add(SingletonAction.positions[x][y]);\n\t}\n\n\tprivate int hpDif(GameState state, boolean p1) {\n\t\tint p1Units = 0;\n\t\tint p2Units = 0;\n\t\tboolean up = true;\n\t\tfor (int x = 0; x < state.map.width; x++){\n\t\t\tfor (int y = 0; y < state.map.height; y++){\n\t\t\t\tif (state.units[x][y] != null){\n\t\t\t\t\tup = (state.units[x][y].hp > 0);\n\t\t\t\t\tif (state.units[x][y].p1Owner){\n\t\t\t\t\t\tp1Units += \n\t\t\t\t\t\t\t\tstate.units[x][y].hp\n\t\t\t\t\t\t\t\t+ state.units[x][y].unitClass.maxHP * (up ? 2 : 1)\n\t\t\t\t\t\t\t\t+ squareVal(state.map.squares[x][y], state.units[x][y].unitClass.card) * (up ? 1: 0)\n\t\t\t\t\t\t\t\t//- healDistance(state, x, y) * healMultiplier\n\t\t\t\t\t\t\t\t+ equipmentValue(state.units[x][y]) * (up ? 2 : 1)\n\t\t\t\t\t\t\t\t;\n\t\t\t\t\t\t\t\t//- spread(state, x, y) * spreadMultiplier;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp2Units += \n\t\t\t\t\t\t\t\tstate.units[x][y].hp\n\t\t\t\t\t\t\t\t+ state.units[x][y].unitClass.maxHP * (up ? 2 : 1)\n\t\t\t\t\t\t\t\t+ squareVal(state.map.squares[x][y], state.units[x][y].unitClass.card) * (up ? 1: 0)\n\t\t\t\t\t\t\t\t//- healDistance(state, x, y) * healMultiplier\n\t\t\t\t\t\t\t\t+ equipmentValue(state.units[x][y]) * (up ? 2 : 1)\n\t\t\t\t\t\t\t\t;\n\t\t\t\t\t\t\t\t//- spread(state, x, y) * spreadMultiplier;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// DECK AND HAND UNITS\n\t\tint p1Inferno = 0;\n\t\tint p2Inferno = 0;\n\t\tint p1Potions = 0;\n\t\tint p2Potions = 0;\n\t\tfor (final Card card : Card.values()){\n\t\t\tif (card.type != CardType.UNIT){\n\t\t\t\tif (card == Card.INFERNO){\n\t\t\t\t\tp1Inferno = state.p1Hand.count(card) + state.p1Deck.count(card);\n\t\t\t\t\tp2Inferno = state.p2Hand.count(card) + state.p2Deck.count(card);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tp1Units += state.p1Deck.count(card) * UnitClassLib.lib.get(card).maxHP * 1.75;\n\t\t\tp2Units += state.p2Deck.count(card) * UnitClassLib.lib.get(card).maxHP * 1.75;\n\t\t\tp1Units += state.p1Hand.count(card) * UnitClassLib.lib.get(card).maxHP * 1.75;\n\t\t\tp2Units += state.p2Hand.count(card) * UnitClassLib.lib.get(card).maxHP * 1.75;\n\t\t}\n\t\t\n\t\t// INFERNO + POTIONS\n\t\tint sp1 = p1Inferno * 750 + p1Potions * 600;\n\t\tint sp2 = p2Inferno * 750 + p2Potions * 600;\n\t\t\n\t\tif (p1)\n\t\t\treturn (p1Units + sp1) - (p2Units + sp2);\n\t\treturn (p2Units + sp1) - (p1Units + sp2);\n\t}\n\n\tprivate int spread(GameState state, int x, int y) {\n\t\tif (!positional || state.units[x][y].unitClass.card == Card.CRYSTAL)\n\t\t\treturn 0;\n\t\tint c = 0;\n\t\tboolean p1 = state.units[x][y].p1Owner;\n\t\tif (x+1 < state.map.width){\n\t\t\tif (y+1 < state.map.height)\n\t\t\t\tif (state.units[x+1][y+1] != null && state.units[x+1][y+1].p1Owner == p1)\n\t\t\t\t\tif (state.units[x+1][y+1].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\tc+=1;\n\t\t\tif (y-1 >= 0)\n\t\t\t\tif (state.units[x+1][y-1] != null && state.units[x+1][y-1].p1Owner == p1)\n\t\t\t\t\tif (state.units[x+1][y-1].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\tc+=1;\n\t\t\tif (state.units[x+1][y] != null && state.units[x+1][y].p1Owner == p1)\n\t\t\t\tif (state.units[x+1][y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\tc+=1;\n\t\t}\n\t\tif (x-1 >= 0){\n\t\t\tif (y+1 < state.map.height)\n\t\t\t\tif (state.units[x-1][y+1] != null && state.units[x-1][y+1].p1Owner == p1)\n\t\t\t\t\tif (state.units[x-1][y+1].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\tc+=1;\n\t\t\tif (y-1 >= 0)\n\t\t\t\tif (state.units[x-1][y-1] != null && state.units[x-1][y-1].p1Owner == p1)\n\t\t\t\t\tif (state.units[x-1][y-1].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\tc+=1;\n\t\t\tif (state.units[x-1][y] != null && state.units[x-1][y].p1Owner == p1)\n\t\t\t\tif (state.units[x-1][y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\tc+=1;\n\t\t}\n\t\tif (y+1 < state.map.height)\n\t\t\tif (state.units[x][y+1] != null && state.units[x][y+1].p1Owner == p1)\n\t\t\t\tif (state.units[x][y+1].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\tc+=1;\n\t\tif (y-1 >= 0)\n\t\t\tif (state.units[x][y-1] != null && state.units[x][y-1].p1Owner == p1)\n\t\t\t\tif (state.units[x][y-1].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\tc+=1;\n\t\t\n\t\tif (x == 0 || x == state.map.width-1)\n\t\t\tc+=8;\n\t\t\n\t\treturn c;\n\t}\n\n\tprivate int equipmentValue(Unit unit) {\n\t\tint val = 0;\n\t\tfor(Card card : unit.equipment){\n\t\t\tif (card == Card.DRAGONSCALE){\n\t\t\t\tif (unit.unitClass.card == Card.KNIGHT)\n\t\t\t\t\tval += 30;\n\t\t\t\telse if (unit.unitClass.card == Card.ARCHER)\n\t\t\t\t\tval += 30;\n\t\t\t\telse if (unit.unitClass.card == Card.WIZARD)\n\t\t\t\t\tval += 20;\n\t\t\t\tval += 30;\n\t\t\t} else if (card == Card.RUNEMETAL){\n\t\t\t\tif (unit.unitClass.card == Card.KNIGHT)\n\t\t\t\t\tval -= 50;\n\t\t\t\telse if (unit.unitClass.card == Card.ARCHER)\n\t\t\t\t\tval += 40;\n\t\t\t\telse if (unit.unitClass.card == Card.WIZARD)\n\t\t\t\t\tval += 40;\n\t\t\t\tval += 20;\n\t\t\t} else if (card == Card.SHINING_HELM){\n\t\t\t\tif (unit.unitClass.card == Card.NINJA)\n\t\t\t\t\tval += 10;\n\t\t\t\telse if (unit.unitClass.card == Card.ARCHER)\n\t\t\t\t\tval += 20;\n\t\t\t\telse if (unit.unitClass.card == Card.WIZARD)\n\t\t\t\t\tval += 20;\n\t\t\t\tval += 20;\n\t\t\t} else if (card == Card.SCROLL){\n\t\t\t\tif (unit.unitClass.card == Card.NINJA)\n\t\t\t\t\tval += 40;\n\t\t\t\telse if (unit.unitClass.card == Card.KNIGHT)\n\t\t\t\t\tval -= 40;\n\t\t\t\telse if (unit.unitClass.card == Card.ARCHER)\n\t\t\t\t\tval += 50;\n\t\t\t\telse if (unit.unitClass.card == Card.WIZARD)\n\t\t\t\t\tval += 50;\n\t\t\t\tval += 30;\n\t\t\t}\n\t\t}\n\t\treturn val;\n\t}\n\n\tprivate double healDistance(GameState state, int x, int y) {\n\t\t\n\t\tif (!positional || state.units[x][y].unitClass.card == Card.CRYSTAL)\n\t\t\treturn 0;\n\t\tboolean p1 = state.units[x][y].p1Owner;\n\t\t\n\t\tdouble shortest = 10000;\n\t\tdouble dis = 0;\n\t\tif (p1){\n\t\t\tfor(Position pos : p1Healers){\n\t\t\t\tdis = pos.distance(SingletonAction.positions[x][y]);\n\t\t\t\tif (dis < shortest)\n\t\t\t\t\tshortest = dis;\n\t\t\t}\n\t\t} else {\n\t\t\tfor(Position pos : p2Healers){\n\t\t\t\tdis = pos.distance(SingletonAction.positions[x][y]);\n\t\t\t\tif (dis < shortest)\n\t\t\t\t\tshortest = dis;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (p1){\n\t\t\tfor(Position pos : state.map.p1DeploySquares)\n\t\t\t\tdis = pos.distance(SingletonAction.positions[x][y]);\n\t\t\t\tif (dis+2 < shortest)\n\t\t\t\t\tshortest = dis;\n\t\t}else{ \n\t\t\tfor(Position pos : state.map.p2DeploySquares)\n\t\t\t\tdis = pos.distance(SingletonAction.positions[x][y]);\n\t\t\t\tif (dis+2 < shortest)\n\t\t\t\t\tshortest = dis;\n\t\t}\n\t\t\n\t\treturn Math.max(0, shortest-2);\n\t\t\n\t}\n\n\tprivate int squareVal(SquareType square, Card card) {\n\t\t\n\t\tswitch(square){\n\t\tcase ASSAULT : return assultValue(card);\n\t\tcase DEPLOY_1 : return -75;\n\t\tcase DEPLOY_2 : return -75;\n\t\tcase DEFENSE : return defenseValue(card);\n\t\tcase POWER : return powerValue(card);\n\t\tcase NONE : return 0;\n\t\t}\n\t\t\n\t\treturn 0;\n\t\t\n\t}\n\t\n\tprivate int defenseValue(Card card) {\n\t\tswitch(card){\n\t\tcase ARCHER : return 80;\n\t\tcase WIZARD : return 70;\n\t\tcase CLERIC : return 20;\n\t\tcase KNIGHT : return 30;\n\t\tcase NINJA : return 60;\n\t\tdefault : return 0;\n\t\t}\n\t}\n\t\n\tprivate int powerValue(Card card) {\n\t\tswitch(card){\n\t\tcase ARCHER : return 120;\n\t\tcase WIZARD : return 100;\n\t\tcase CLERIC : return 40;\n\t\tcase KNIGHT : return 30;\n\t\tcase NINJA : return 70;\n\t\tdefault : return 0;\n\t\t}\n\t}\n\n\tprivate int assultValue(Card card) {\n\t\tswitch(card){\n\t\tcase ARCHER : return 40;\n\t\tcase WIZARD : return 40;\n\t\tcase CLERIC : return 10;\n\t\tcase KNIGHT : return 120;\n\t\tcase NINJA : return 50;\n\t\tdefault : return 0;\n\t\t}\n\t}\n\n\t@Override\n\tpublic double normalize(double delta) {\n\t\treturn NormUtil.normalize(delta, -MAX_VAL, MAX_VAL, 1, 0);\n\t}\n\n\t@Override\n\tpublic String title() {\n\t\treturn \"Heuristic Evaluator [positional=\" + positional + \", heal=\"+healMultiplier+\", spread=\"+spreadMultiplier+\"]\";\n\t}\n\n\t@Override\n\tpublic IStateEvaluator copy() {\n\t\treturn new HeuristicEvaluator(winVal);\n\t}\n}", "public interface IStateEvaluator {\n\n\tpublic double eval(GameState state, boolean p1);\n\n\tpublic double normalize(double delta);\n\n\tpublic String title();\n\n\tpublic IStateEvaluator copy();\n\t\n}", "public class AiStatistics {\n\n\tpublic Map<String, Double> stats;\n\tpublic Map<String, List<Double>> statsLists;\n\n\tpublic AiStatistics() {\n\t\tsuper();\n\t\tthis.stats = new HashMap<String, Double>();\n\t\tthis.statsLists = new HashMap<String, List<Double>>();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString str = \"\";\n\t\tfor(String key : stats.keySet())\n\t\t\tstr += key + \" = \"+ stats.get(key) + \"\\n\";\n\t\tfor(String key : statsLists.keySet()){\n\t\t\tif (statsLists.get(key) == null || statsLists.get(key).isEmpty())\n\t\t\t\tcontinue;\n\t\t\tstr += key + \" (avg) = \"+ Statistics.avgDouble(statsLists.get(key)) + \"\\n\";\n\t\t\tstr += key + \" (std.dev) = \"+ Statistics.stdDevDouble(statsLists.get(key)) + \"\\n\";\n\t\t\tstr += key + \" (min) = \"+ Collections.min(statsLists.get(key)) + \"\\n\";\n\t\t\tstr += key + \" (max) = \"+ Collections.max(statsLists.get(key)) + \"\\n\";\n\t\t\tstr += key + \" (datapoints) = \"+ statsLists.get(key).size() + \"\\n\";\n\t\t}\n\t\treturn str + \"\\n\";\n\t}\n\t\n}", "public enum RAND_METHOD {\n\n\tBRUTE, \t// Find all possible actions and select one\n\tTREE \t// Make tree of action types and pick on type until action found\n\n}" ]
import game.GameState; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import model.Card; import action.Action; import action.EndTurnAction; import ai.evaluation.HeuristicEvaluator; import ai.evaluation.IStateEvaluator; import ai.util.AiStatistics; import ai.util.RAND_METHOD;
package ai; public class NmSearchAI implements AI { public boolean p1; private final AI p1Ai; private final AI p2Ai; private List<Action> foundActions; private final int n; private final int m; private IStateEvaluator evaluator; public NmSearchAI(boolean p1, int n, int m, IStateEvaluator evaluator) { this.p1 = p1;
p1Ai = new RandomAI(RAND_METHOD.TREE);
7
BFergerson/Chronetic
src/test/java/io/chronetic/data/ChronoSeriesTest.java
[ "public class ChronoRange {\n\n /**\n * Create a ChronoRange for the given ChronoSeries and sequence of ChronoGenes.\n *\n * @param chronoSeries ChronoSeries to create ChronoRange for\n * @param genes ChronoGene sequence containing ChronoPattern(s) to use for creating ChronoRange\n * @return ChronoRange for given ChronoSeries and ChronoGene sequence\n */\n @NotNull\n public static ChronoRange getChronoRange(@NotNull ChronoSeries chronoSeries, @NotNull ISeq<ChronoGene> genes) {\n ChronoRange range = new ChronoRange(requireNonNull(chronoSeries), requireNonNull(genes));\n Cache<ISeq<ChronoPattern>, ChronoRange> cacheChronoRange = cacheMap.get(chronoSeries);\n if (cacheChronoRange == null) {\n cacheChronoRange = CacheBuilder.newBuilder().build();\n cacheMap.put(chronoSeries, cacheChronoRange);\n }\n\n ChronoRange cacheRange = cacheChronoRange.getIfPresent(range.chronoPatternSeq);\n if (cacheRange != null) {\n return cacheRange;\n } else {\n if (range.validRange) {\n range.calculateTimestampRanges();\n }\n\n cacheChronoRange.put(range.chronoPatternSeq, range);\n return range;\n }\n }\n\n private final static Logger logger = LoggerFactory.getLogger(ChronoRange.class);\n\n private static final Map<ChronoSeries, Cache<ISeq<ChronoPattern>, ChronoRange>> cacheMap = new IdentityHashMap<>();\n private final ChronoSeries chronoSeries;\n private final ChronoScale chronoScale;\n private final ArrayList<Instant[]> timestampRanges;\n private final ISeq<ChronoPattern> chronoPatternSeq;\n private final ChronoPattern smallestPattern;\n private LocalDateTime patternStartLocalDateTime;\n private LocalDateTime patternEndLocalDateTime;\n private boolean includeEndingTimestamp;\n private boolean fullyConceptual;\n private boolean searchRange = true;\n private Duration rangeDuration = Duration.ZERO;\n private final ChronoScaleUnit limitScaleUnit;\n private ChronoScaleUnit tempSkipUnit;\n private boolean validRange = true;\n\n private ChronoRange(@NotNull ChronoSeries chronoSeries, @NotNull ISeq<ChronoGene> genes) {\n this.chronoSeries = requireNonNull(chronoSeries);\n chronoPatternSeq = requireNonNull(genes).stream()\n .filter(g -> g.getAllele() instanceof ChronoPattern)\n .map(g -> (ChronoPattern) g.getAllele())\n .sorted((o1, o2) -> o2.getChronoScaleUnit().getChronoUnit().compareTo(o1.getChronoScaleUnit().getChronoUnit()))\n .collect(ISeq.toISeq());\n\n timestampRanges = new ArrayList<>();\n chronoScale = chronoSeries.getChronoScale();\n limitScaleUnit = chronoScale.getParentChronoScaleUnitLimit(chronoSeries.getDuration());\n fullyConceptual = chronoPatternSeq.stream()\n .noneMatch(chronoPattern -> chronoPattern.getTemporalValue().isPresent());\n\n if (chronoPatternSeq.isEmpty()) {\n validRange = false;\n smallestPattern = null;\n rangeDuration = chronoSeries.getDuration();\n addRange(chronoSeries.getBeginLocalDateTime(), chronoSeries.getEndLocalDateTime());\n } else {\n smallestPattern = chronoPatternSeq.get(chronoPatternSeq.size() - 1);\n }\n }\n\n private void calculateTimestampRanges() {\n LocalDateTime endTime = chronoSeries.getEndLocalDateTime();\n LocalDateTime itrTime = chronoSeries.getBeginLocalDateTime();\n\n logger.debug(\"Starting range determine loop\");\n while (searchRange && (itrTime.isEqual(endTime) || itrTime.isBefore(endTime))) {\n for (ChronoPattern chronoPattern : chronoPatternSeq) {\n if (tempSkipUnit != null && chronoPattern != smallestPattern\n && chronoPattern.getChronoScaleUnit().getChronoUnit() == tempSkipUnit.getChronoUnit()) {\n continue;\n } else {\n tempSkipUnit = null;\n }\n\n LocalDateTime startItrTime = itrTime;\n logger.trace(\"Start itrTime: \" + startItrTime);\n itrTime = progressTime(endTime, itrTime, chronoPattern);\n logger.trace(\"End itrTime: \" + itrTime);\n }\n }\n logger.debug(\"Finished range determine loop\");\n\n if (patternStartLocalDateTime != null && patternStartLocalDateTime.isBefore(chronoSeries.getBeginLocalDateTime())) {\n patternStartLocalDateTime = chronoSeries.getBeginLocalDateTime();\n }\n if (patternEndLocalDateTime != null && patternEndLocalDateTime.isAfter(chronoSeries.getEndLocalDateTime())) {\n patternEndLocalDateTime = chronoSeries.getEndLocalDateTime();\n }\n\n for (Instant[] instants : timestampRanges) {\n rangeDuration = rangeDuration.plus(Duration.between(instants[0], instants[1]));\n }\n logger.debug(\"Range duration: \" + rangeDuration);\n }\n\n @NotNull\n private LocalDateTime progressTime(@NotNull LocalDateTime endTime, @NotNull LocalDateTime itrTime,\n @NotNull ChronoPattern chronoPattern) {\n ChronoScaleUnit chronoScaleUnit = chronoPattern.getChronoScaleUnit();\n ChronoUnit chronoUnit = chronoScaleUnit.getChronoUnit();\n\n LocalDateTime startItrTime = itrTime;\n try {\n itrTime = itrTime.truncatedTo(chronoUnit);\n } catch (UnsupportedTemporalTypeException ex) {\n //do nothing\n } finally {\n if (itrTime.isBefore(startItrTime)) {\n itrTime = startItrTime;\n }\n }\n\n LocalDateTime itrStartTime = itrTime;\n if (!allMatch(itrTime)) {\n if (isMultiUnit(chronoPattern.getChronoScaleUnit().getChronoUnit())) {\n if (anyUnitMatch(itrTime, chronoPattern.getChronoScaleUnit().getChronoUnit())) {\n tempSkipUnit = chronoPattern.getChronoScaleUnit();\n return itrTime;\n } else if (pastPatternMatch(itrTime, chronoPattern) && !allPastPatternMatch(itrTime, chronoUnit)) {\n return itrTime;\n }\n }\n\n if (chronoPattern.getTemporalValue().isPresent()) {\n int patternValue = chronoPattern.getTemporalValue().getAsInt();\n LocalDateTime asTime = chronoScaleUnit.getChronoField().adjustInto(itrTime, patternValue);\n try {\n asTime = asTime.truncatedTo(chronoUnit);\n } catch (UnsupportedTemporalTypeException ex) {\n if (chronoUnit == ChronoUnit.YEARS) {\n //truncate to beginning of year\n asTime = asTime.with(firstDayOfYear()).truncatedTo(ChronoUnit.DAYS);\n } else if (chronoUnit == ChronoUnit.MONTHS) {\n //truncate to beginning of month\n asTime = asTime.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);\n } else {\n //throw new UnsupportedOperationException();\n }\n } finally {\n if (asTime.isBefore(startItrTime)) {\n asTime = chronoScaleUnit.getChronoField().adjustInto(itrTime, patternValue);\n }\n }\n\n if (asTime.isBefore(itrTime)) {\n //skip to next occurrence\n ChronoScaleUnit parentScaleUnit = chronoScale.getParentChronoScaleUnit(chronoUnit);\n LocalDateTime desiredTime = asTime.plus(1, parentScaleUnit.getChronoUnit());\n\n try {\n desiredTime = desiredTime.truncatedTo(chronoUnit);\n } catch (UnsupportedTemporalTypeException ex) {\n if (chronoUnit == ChronoUnit.YEARS) {\n //truncate to beginning of year\n desiredTime = desiredTime.with(firstDayOfYear()).truncatedTo(ChronoUnit.DAYS);\n } else if (chronoUnit == ChronoUnit.MONTHS) {\n //truncate to beginning of month\n desiredTime = desiredTime.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);\n } else {\n //throw new UnsupportedOperationException();\n }\n } finally {\n if (desiredTime.isBefore(startItrTime)) {\n desiredTime = asTime.plus(1, parentScaleUnit.getChronoUnit());\n }\n }\n\n long until = itrTime.until(desiredTime, chronoUnit);\n if (until == 0) {\n itrTime = desiredTime;\n } else {\n itrTime = itrTime.plus(until, chronoUnit);\n }\n } else {\n //after itrTime. make itrTime asTime\n itrTime = asTime;\n }\n }\n\n if (isMultiUnit(chronoPattern.getChronoScaleUnit().getChronoUnit())\n && anyUnitMatch(itrTime, chronoPattern.getChronoScaleUnit().getChronoUnit())) {\n tempSkipUnit = chronoPattern.getChronoScaleUnit();\n return itrTime;\n }\n\n return itrTime;\n }\n\n OptionalInt temporalValue = chronoPattern.getTemporalValue();\n if (temporalValue.isPresent()) {\n if (chronoPattern.getChronoScaleUnit().getChronoUnit() == smallestPattern.getChronoScaleUnit().getChronoUnit()) {\n int patternValue = temporalValue.getAsInt();\n if (itrTime.get(chronoScaleUnit.getChronoField()) == patternValue) {\n if (patternStartLocalDateTime == null) {\n patternStartLocalDateTime = itrTime;\n }\n }\n\n itrTime = itrTime.plus(1, chronoUnit);\n try {\n itrTime = itrTime.truncatedTo(chronoUnit);\n } catch (UnsupportedTemporalTypeException ex) {\n if (chronoUnit == ChronoUnit.MONTHS) {\n //truncate to beginning of month\n itrTime = itrTime.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);\n } else {\n //throw new UnsupportedOperationException();\n }\n } finally {\n if (itrTime.isBefore(startItrTime)) {\n itrTime = itrTime.plus(1, chronoUnit);\n }\n }\n\n if (itrTime.isAfter(endTime)) {\n includeEndingTimestamp = !itrTime.isEqual(endTime);\n }\n addRange(itrStartTime, itrTime);\n patternEndLocalDateTime = itrTime;\n }\n } else {\n if (patternStartLocalDateTime == null) {\n patternStartLocalDateTime = itrTime;\n }\n\n if (chronoPattern.getChronoScaleUnit().getChronoUnit() == smallestPattern.getChronoScaleUnit().getChronoUnit()) {\n if (fullyConceptual) {\n //short circuit\n addRange(itrTime, endTime);\n patternEndLocalDateTime = endTime;\n includeEndingTimestamp = true;\n searchRange = false;\n } else {\n ChronoScaleUnit parentScaleUnit = getLocalParent(chronoUnit);\n LocalDateTime desiredTime = itrTime.plus(1, parentScaleUnit.getChronoUnit());\n if (desiredTime.isAfter(endTime)) {\n desiredTime = endTime;\n includeEndingTimestamp = !desiredTime.isEqual(endTime);\n searchRange = false;\n }\n long until = itrTime.until(desiredTime, chronoUnit);\n\n itrTime = itrTime.plus(until, chronoUnit);\n addRange(itrStartTime, itrTime);\n patternEndLocalDateTime = itrTime;\n }\n }\n }\n return itrTime;\n }\n\n @NotNull\n private ChronoScaleUnit getLocalParent(@NotNull ChronoUnit chronoUnit) {\n ChronoScaleUnit parentScaleUnit = chronoScale.getParentChronoScaleUnit(requireNonNull(chronoUnit));\n if (chronoUnit == limitScaleUnit.getChronoUnit()) {\n return limitScaleUnit;\n }\n\n //find limit\n while (true) {\n boolean match = false;\n for (ChronoPattern chronoPattern : chronoPatternSeq) {\n if (chronoPattern.getChronoScaleUnit().getChronoUnit() == parentScaleUnit.getChronoUnit()\n && chronoPattern.getTemporalValue().isPresent()) {\n match = true;\n break;\n }\n }\n if (match || parentScaleUnit == limitScaleUnit) {\n return parentScaleUnit;\n } else {\n parentScaleUnit = chronoScale.getParentChronoScaleUnit(parentScaleUnit.getChronoUnit());\n }\n }\n }\n\n private void addRange(@NotNull LocalDateTime start, @NotNull LocalDateTime end) {\n if (requireNonNull(start).isBefore(chronoSeries.getBeginLocalDateTime())) {\n start = chronoSeries.getBeginLocalDateTime();\n }\n if (requireNonNull(end).isAfter(chronoSeries.getEndLocalDateTime())) {\n end = chronoSeries.getEndLocalDateTime();\n }\n\n Instant startEpoch = start.atZone(ZoneOffset.UTC).toInstant();\n Instant endEpoch = end.atZone(ZoneOffset.UTC).toInstant();\n\n boolean updatedRange = false;\n if (!timestampRanges.isEmpty()) {\n Instant[] range = timestampRanges.get(timestampRanges.size() - 1);\n if (range[1].equals(startEpoch)) {\n timestampRanges.set(timestampRanges.size() - 1, new Instant[]{range[0], endEpoch});\n updatedRange = true;\n }\n }\n\n if (!updatedRange) {\n timestampRanges.add(new Instant[]{startEpoch, endEpoch});\n }\n }\n\n /**\n * Returns validity of ChronoRange.\n *\n * @return whether or not ChronoRange is valid\n */\n public boolean isValidRange() {\n return validRange;\n }\n\n /**\n * Returns list of the being/end timestamps of this ChronoRange.\n *\n * @return list Instant[] (begin/end timestamp)\n */\n @NotNull\n public List<Instant[]> getTimestampRanges() {\n return timestampRanges;\n }\n\n /**\n * Determines whether the given timestamp is within this ChronoRange.\n *\n * @param timestamp Instant to consider\n * @return whether or not this ChronoRange includes the given timestamp\n */\n public boolean containsTime(Instant timestamp) {\n if (fullyConceptual) {\n return true;\n }\n\n for (Instant[] longArr : timestampRanges) {\n if ((timestamp.isAfter(longArr[0]) || timestamp.equals(longArr[0])) && (timestamp.isBefore(longArr[1]))) {\n return true;\n }\n if (timestamp.equals(longArr[1]) && patternEndLocalDateTime != null &&\n timestamp.equals(patternEndLocalDateTime.toInstant(ZoneOffset.UTC)) && includeEndingTimestamp) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Earliest appearance of this ChronoRange's pattern sequence.\n *\n * @return earliest appearance of this ChronoRange's pattern sequence, if present\n */\n @NotNull\n public Optional<LocalDateTime> getPatternStartLocalDateTime() {\n if (patternStartLocalDateTime == null) {\n return Optional.empty();\n }\n return Optional.of(patternStartLocalDateTime);\n }\n\n /**\n * Latest appearance of this ChronoRange's pattern sequence.\n *\n * @return latest appearance of this ChronoRange's pattern sequence, if present\n */\n @NotNull\n public Optional<LocalDateTime> getPatternEndLocalDateTime() {\n if (patternEndLocalDateTime == null) {\n return Optional.empty();\n }\n return Optional.of(patternEndLocalDateTime);\n }\n\n /**\n * Returns Duration of this ChronoRange.\n *\n * @return Duration of ChronoRange\n */\n @NotNull\n public Duration getRangeDuration() {\n return rangeDuration;\n }\n\n /**\n * Returns the ChronoPattern sequence of this ChronoRange.\n *\n * @return current ChronoPattern sequence\n */\n @NotNull\n public ISeq<ChronoPattern> getChronoPatternSeq() {\n return chronoPatternSeq;\n }\n\n boolean isIncludeEndingTimestamp() {\n return includeEndingTimestamp;\n }\n\n /**\n * Determines if this ChronoRange only contains ChronoPattern(s) without temporal values.\n *\n * @return fully conceptual ChronoPattern sequence or not\n */\n public boolean isFullyConceptual() {\n return fullyConceptual;\n }\n\n /**\n * Determines if this ChronoRange and the given ChronoRange overlap.\n *\n * @param chronoRange other ChronoRange to consider\n * @return whether or not ChronoRanges share temporal inclusion\n */\n public boolean isSameChronoRange(@NotNull ChronoRange chronoRange) {\n if (!validRange || !requireNonNull(chronoRange).validRange) {\n return true;\n }\n\n ISeq<ChronoPattern> chronoPatterns = getChronoPatternSeq();\n ISeq<ChronoPattern> otherChronoPatterns = chronoRange.getChronoPatternSeq();\n\n //single gene compare\n if (chronoPatterns.size() == 1 && otherChronoPatterns.size() == 1) {\n ChronoPattern pattern = chronoPatterns.get(0);\n ChronoUnit unit = pattern.getChronoScaleUnit().getChronoUnit();\n\n ChronoPattern otherPattern = otherChronoPatterns.get(0);\n ChronoUnit otherUnit = otherPattern.getChronoScaleUnit().getChronoUnit();\n\n if (unit == otherUnit) {\n if (pattern.getTemporalValue().isPresent() && otherPattern.getTemporalValue().isPresent()) {\n if (pattern.getTemporalValue().getAsInt() == otherPattern.getTemporalValue().getAsInt()) {\n return true;\n } else {\n return false;\n }\n } else if (pattern.getTemporalValue().isPresent() || otherPattern.getTemporalValue().isPresent()) {\n return true;\n }\n } else {\n return true;\n }\n }\n\n //exact gene compare\n if (chronoPatterns.equals(otherChronoPatterns)) {\n return true;\n }\n\n //distinct gene compare\n ISeq<ChronoUnit> units = chronoPatterns.stream()\n .map(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit())\n .distinct().collect(ISeq.toISeq());\n ISeq<ChronoUnit> otherUnits = otherChronoPatterns.stream()\n .map(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit())\n .distinct().collect(ISeq.toISeq());\n\n boolean hasRelatedUnits = false;\n for (ChronoUnit unit : units) {\n for (ChronoUnit otherUnit : otherUnits) {\n if (unit == otherUnit) {\n hasRelatedUnits = true;\n break;\n }\n }\n\n if (hasRelatedUnits) {\n break;\n }\n }\n\n if (!hasRelatedUnits) {\n return true;\n }\n\n //duplicate gene compare\n Map<ChronoUnit, Set<Integer>> temporalMap = new HashMap<>();\n for (int i = 0; i < chronoPatterns.size(); i++) {\n ChronoPattern pattern = chronoPatterns.get(i);\n ChronoUnit unit = pattern.getChronoScaleUnit().getChronoUnit();\n temporalMap.put(unit, new HashSet<>());\n\n if (pattern.getTemporalValue().isPresent()) {\n temporalMap.get(unit).add(pattern.getTemporalValue().getAsInt());\n }\n }\n for (int i = 0; i < otherChronoPatterns.size(); i++) {\n ChronoPattern otherPattern = otherChronoPatterns.get(i);\n ChronoUnit otherUnit = otherPattern.getChronoScaleUnit().getChronoUnit();\n\n if (otherPattern.getTemporalValue().isPresent()) {\n if (temporalMap.get(otherUnit) != null\n && temporalMap.get(otherUnit).contains(otherPattern.getTemporalValue().getAsInt())) {\n return true;\n }\n }\n }\n\n //more precise gene compare\n int z = 0;\n for (int i = 0; i < chronoPatterns.size(); i++) {\n ChronoPattern pattern = chronoPatterns.get(i);\n ChronoUnit unit = pattern.getChronoScaleUnit().getChronoUnit();\n\n ChronoPattern otherPattern = otherChronoPatterns.get(z++);\n ChronoUnit otherUnit = otherPattern.getChronoScaleUnit().getChronoUnit();\n\n if (unit == otherUnit) {\n if (pattern.getTemporalValue().isPresent() && otherPattern.getTemporalValue().isPresent()) {\n if (pattern.getTemporalValue().getAsInt() == otherPattern.getTemporalValue().getAsInt()) {\n return true;\n } else {\n return false;\n }\n } else if (pattern.getTemporalValue().isPresent() || otherPattern.getTemporalValue().isPresent()) {\n return true;\n } else if (!pattern.getTemporalValue().isPresent() && !otherPattern.getTemporalValue().isPresent()) {\n return true;\n }\n } else if (unit.compareTo(otherUnit) > 0) {\n z--;\n } else {\n i--;\n }\n }\n\n return false;\n }\n\n private boolean allMatch(@NotNull LocalDateTime itrTime) {\n //do 'all match' by unit, do 'any match' on units\n Stream<ChronoUnit> chronoUnitStream = chronoPatternSeq.stream()\n .map(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit())\n .distinct();\n\n AtomicBoolean allMatch = new AtomicBoolean(true);\n chronoUnitStream.forEach(\n chronoUnit -> {\n boolean match = chronoPatternSeq.stream()\n .filter(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit().equals(chronoUnit))\n .anyMatch(chronoPattern -> !chronoPattern.getTemporalValue().isPresent() ||\n itrTime.get(chronoPattern.getChronoScaleUnit().getChronoField()) ==\n chronoPattern.getTemporalValue().getAsInt());\n if (!match) {\n allMatch.set(false);\n }\n }\n );\n return allMatch.get();\n }\n\n private boolean isMultiUnit(@NotNull ChronoUnit chronoUnit) {\n return chronoPatternSeq.stream()\n .map(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit())\n .filter(unit -> unit.equals(chronoUnit))\n .count() > 1;\n }\n\n private boolean anyUnitMatch(@NotNull LocalDateTime itrTime, @NotNull ChronoUnit currentChronoUnit) {\n return chronoPatternSeq.stream()\n .filter(chronoPattern -> chronoPattern.getChronoScaleUnit().getChronoUnit().equals(currentChronoUnit))\n .anyMatch(chronoPattern -> !chronoPattern.getTemporalValue().isPresent() ||\n itrTime.get(chronoPattern.getChronoScaleUnit().getChronoField()) ==\n chronoPattern.getTemporalValue().getAsInt());\n }\n\n private boolean pastPatternMatch(@NotNull LocalDateTime itrTime, @NotNull ChronoPattern chronoPattern) {\n return !requireNonNull(chronoPattern).getTemporalValue().isPresent() ||\n requireNonNull(itrTime).get(chronoPattern.getChronoScaleUnit().getChronoField()) >\n chronoPattern.getTemporalValue().getAsInt();\n }\n\n private boolean allPastPatternMatch(@NotNull LocalDateTime itrTime, @NotNull ChronoUnit chronoUnit) {\n AtomicBoolean allPast = new AtomicBoolean(true);\n chronoPatternSeq.stream()\n .filter(pattern -> pattern.getChronoScaleUnit().getChronoUnit().equals(chronoUnit))\n .forEach(\n chronoPattern -> {\n if (itrTime.get(chronoPattern.getChronoScaleUnit().getChronoField()) < chronoPattern.getTemporalValue().getAsInt()) {\n allPast.set(false);\n }\n }\n );\n return allPast.get();\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 ChronoRange that = (ChronoRange) o;\n\n return chronoPatternSeq.equals(that.chronoPatternSeq);\n }\n\n @Override\n public int hashCode() {\n return chronoPatternSeq.hashCode();\n }\n\n}", "public class ChronoScaleUnit {\n\n private static final Map<ChronoSeries, Set<ChronoScaleUnit>> cacheMap = new IdentityHashMap<>();\n private final ChronoUnit chronoUnit;\n private final long actualMinimum;\n private final long actualMaximum;\n private Long observedMinimum;\n private Long observedMaximum;\n private Set<Long> observedDistinctSet;\n\n private ChronoScaleUnit(ChronoUnit chronoUnit, long actualMinimum, long actualMaximum,\n Long observedMinimum, Long observedMaximum) {\n this.chronoUnit = requireNonNull(chronoUnit);\n this.actualMinimum = actualMinimum;\n this.actualMaximum = actualMaximum;\n this.observedMinimum = observedMinimum;\n this.observedMaximum = observedMaximum;\n this.observedDistinctSet = new HashSet<>();\n\n if (actualMinimum > actualMaximum || actualMaximum < actualMinimum) {\n throw new IllegalArgumentException(\"Invalid actual minimum and actual maximum combination\");\n }\n }\n\n public boolean isValid(long temporalValue) {\n return !isDisabled() && (temporalValue < actualMaximum && temporalValue > actualMinimum);\n }\n\n public boolean isDisabled() {\n return actualMinimum == -1 || actualMaximum == -1;\n }\n\n @NotNull\n public ChronoUnit getChronoUnit() {\n return chronoUnit;\n }\n\n /**\n * Returns the actual minimum for this ChronoScaleUnit.\n *\n * @return actual minimum\n */\n public long getActualMinimum() {\n return actualMinimum;\n }\n\n /**\n * Returns the actual maximum for this ChronoScaleUnit.\n *\n * @return actual maximum\n */\n public long getActualMaximum() {\n return actualMaximum;\n }\n\n /**\n * Returns the observed minimum for this ChronoScaleUnit.\n * If nothing has been observed, returns empty Optional.\n *\n * @return observed minimum, if present\n */\n @NotNull\n public OptionalLong getObservedMinimum() {\n if (observedMinimum == null) {\n return OptionalLong.empty();\n }\n return OptionalLong.of(observedMinimum);\n }\n\n /**\n * Returns the observed maximum for this ChronoScaleUnit.\n * If nothing has been observed, returns empty Optional.\n *\n * @return observed maximum, if present\n */\n @NotNull\n public OptionalLong getObservedMaximum() {\n if (observedMaximum == null) {\n return OptionalLong.empty();\n }\n return OptionalLong.of(observedMaximum);\n }\n\n /**\n * Observes the given temporal value.\n *\n * @param temporalValue temporal value to observe\n */\n public void observeValue(long temporalValue) {\n if (temporalValue > actualMaximum || temporalValue < actualMinimum) {\n throw new IllegalArgumentException(\"Invalid temporal value: \" + temporalValue);\n }\n\n if (observedMinimum == null || temporalValue < observedMinimum) {\n this.observedMinimum = temporalValue;\n observedDistinctSet.add(temporalValue);\n }\n if (observedMaximum == null || temporalValue > observedMaximum) {\n this.observedMaximum = temporalValue;\n observedDistinctSet.add(temporalValue);\n }\n }\n\n /**\n * Returns a set of the distinct observed values for this ChronoScaleUnit.\n *\n * @return set of observed temporal values\n */\n @NotNull\n public Set<Long> getObservedDistinctSet() {\n return observedDistinctSet;\n }\n\n /**\n * Returns the factual minimum for this ChronoScaleUnit.\n *\n * @return factual minimum\n */\n public long getFactualMinimum() {\n return ChronoScale.getFactualMinimum(chronoUnit);\n }\n\n /**\n * Returns the factual maximum for this ChronoScaleUnit.\n *\n * @return factual maximum\n */\n public long getFactualMaximum() {\n return ChronoScale.getFactualMaximum(chronoUnit);\n }\n\n /**\n * Create a disabled ChronoScaleUnit from the given ChronoUnit.\n *\n * @param chronoUnit desired ChronoUnit\n * @return disabled ChronoScaleUnit for the given ChronoUnit\n */\n @NotNull\n public static ChronoScaleUnit asDisabled(@NotNull ChronoUnit chronoUnit) {\n return new ChronoScaleUnit(requireNonNull(chronoUnit), -1, -1, null, null);\n }\n\n /**\n * Create a factual ChronoScaleUnit from the given ChronoUnit.\n * Factual ChronoScaleUnits are stored in cache with ChronoSeries as the key.\n *\n * @param chronoUnit desired ChronoUnit\n * @return factual ChronoScaleUnit for the given ChronoUnit\n */\n @NotNull\n public static ChronoScaleUnit asFactual(@NotNull ChronoSeries chronoSeries, @NotNull ChronoUnit chronoUnit) {\n Set<ChronoScaleUnit> chronoScaleUnits = cacheMap.get(requireNonNull(chronoSeries));\n if (chronoScaleUnits == null) {\n cacheMap.put(chronoSeries, chronoScaleUnits = new HashSet<>());\n }\n ChronoScaleUnit cacheScaleUnit = null;\n for (ChronoScaleUnit scaleUnit : chronoScaleUnits) {\n if (scaleUnit.getChronoUnit() == requireNonNull(chronoUnit)) {\n cacheScaleUnit = scaleUnit;\n break;\n }\n }\n\n if (cacheScaleUnit == null) {\n ChronoScaleUnit scaleUnit = new ChronoScaleUnit(chronoUnit,\n ChronoScale.getFactualMinimum(chronoUnit), ChronoScale.getFactualMaximum(chronoUnit),\n null, null);\n cacheMap.get(requireNonNull(chronoSeries)).add(scaleUnit);\n return scaleUnit;\n } else {\n return cacheScaleUnit;\n }\n }\n\n /**\n * Returns the equivalent ChronoField for this ChronoScaleUnit.\n *\n * @return equivalent ChronoField\n */\n @NotNull\n public ChronoField getChronoField() {\n return ChronoScale.getChronoField(chronoUnit);\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 ChronoScaleUnit that = (ChronoScaleUnit) o;\n\n if (actualMinimum != that.actualMinimum) return false;\n if (actualMaximum != that.actualMaximum) return false;\n return chronoUnit == that.chronoUnit;\n }\n\n @Override\n public int hashCode() {\n int result = chronoUnit.hashCode();\n result = 31 * result + (int) (actualMinimum ^ (actualMinimum >>> 32));\n result = 31 * result + (int) (actualMaximum ^ (actualMaximum >>> 32));\n return result;\n }\n\n @Override\n public String toString() {\n return String.format(\"ChronoScaleUnit {Unit: %s; Min: %d - Max: %d}\", chronoUnit, actualMinimum, actualMaximum);\n }\n\n}", "public class ChronoGene implements Gene<ChronoAllele, ChronoGene> {\n\n private final ChronoAllele allele;\n\n public ChronoGene(@NotNull ChronoAllele allele) {\n this.allele = requireNonNull(allele);\n }\n\n @NotNull\n @Override\n public ChronoAllele getAllele() {\n return allele;\n }\n\n @NotNull\n @Override\n public ChronoGene newInstance() {\n return newInstance(allele);\n }\n\n @NotNull\n @Override\n public ChronoGene newInstance(@NotNull ChronoAllele allele) {\n return new ChronoGene(allele);\n }\n\n @Override\n public boolean isValid() {\n return allele.isValid();\n }\n\n @NotNull\n @Override\n public String toString() {\n return \"ChronoGene: {\" + allele + \"}\";\n }\n\n}", "public abstract class ChronoAllele {\n\n final int seriesPosition;\n\n ChronoAllele(int seriesPosition) {\n this.seriesPosition = seriesPosition;\n }\n\n @NotNull\n public abstract ChronoAllele mutate(@NotNull ChronoSeries chronoSeries);\n\n public abstract boolean isValid();\n\n}", "public class ChronoFrequency extends ChronoAllele {\n\n private final ChronoUnit chronoUnit;\n private final SummaryStatistics frequencyStatistics;\n private final Instant lastOccurrenceTimestamp;\n\n public ChronoFrequency(@NotNull ChronoUnit chronoUnit, int chronoSeriesPosition,\n long exactFrequency, @NotNull Instant lastOccurrenceTimestamp) {\n this(requireNonNull(chronoUnit), chronoSeriesPosition, exactFrequency, exactFrequency,\n requireNonNull(lastOccurrenceTimestamp));\n }\n\n public ChronoFrequency(@NotNull ChronoUnit chronoUnit, int chronoSeriesPosition,\n long minimumFrequency, long maximumFrequency, @NotNull Instant lastOccurrenceTimestamp) {\n super(chronoSeriesPosition);\n this.chronoUnit = requireNonNull(chronoUnit);\n this.frequencyStatistics = new SummaryStatistics();\n this.frequencyStatistics.addValue(minimumFrequency);\n if (minimumFrequency != maximumFrequency) {\n this.frequencyStatistics.addValue(maximumFrequency);\n }\n this.lastOccurrenceTimestamp = requireNonNull(lastOccurrenceTimestamp);\n\n if (minimumFrequency < 0 || maximumFrequency < 0) {\n throw new IllegalArgumentException(\"Minimum and maximum frequency must be greater than zero\");\n } else if (minimumFrequency > maximumFrequency || maximumFrequency < minimumFrequency) {\n throw new IllegalArgumentException(\"Invalid minimum and maximum frequency combination\");\n }\n }\n\n public ChronoFrequency(@NotNull ChronoUnit chronoUnit, int chronoSeriesPosition,\n @NotNull SummaryStatistics frequencyStatistics, @NotNull Instant lastOccurrenceTimestamp) {\n super(chronoSeriesPosition);\n this.chronoUnit = requireNonNull(chronoUnit);\n this.frequencyStatistics = new SummaryStatistics(requireNonNull(frequencyStatistics));\n this.lastOccurrenceTimestamp = requireNonNull(lastOccurrenceTimestamp);\n }\n\n /**\n * Creates a new ChronoFrequency which has progressed in the ChronoSeries by one step.\n *\n * @param chronoSeries time series data to traverse\n * @return new ChronoFrequency with latest frequency from traversing time series data\n */\n @NotNull\n @Override\n public ChronoFrequency mutate(@NotNull ChronoSeries chronoSeries) {\n if (seriesPosition >= requireNonNull(chronoSeries).getSize()) {\n //start from beginning of series\n return new ChronoFrequency(chronoUnit, 0, getMinimumFrequency(), getMaximumFrequency(),\n chronoSeries.getTimestamp(0));\n }\n\n Instant nextTimestamp = chronoSeries.getTimestamp(seriesPosition);\n LocalDateTime firstDateTime = getLastOccurrenceTimestamp().atZone(ZoneOffset.UTC).toLocalDateTime();\n LocalDateTime secondDateTime = nextTimestamp.atZone(ZoneOffset.UTC).toLocalDateTime();\n\n if (secondDateTime.isBefore(firstDateTime)) {\n throw new RuntimeException(\"first: \" + firstDateTime + \"; second: \" + secondDateTime);\n }\n\n //update chrono frequency gene\n long frequency = getChronoUnit().between(firstDateTime, secondDateTime);\n LocalDateTime addedDateTime = firstDateTime.plus(frequency, getChronoUnit());\n if (addedDateTime.isBefore(secondDateTime) && isWithinRange(frequency)) {\n frequency++;\n } else if (frequency == 0) {\n //no point in a frequency of nothing\n frequency++;\n }\n return mutateChronoFrequency(frequency, nextTimestamp);\n }\n\n @Override\n public boolean isValid() {\n //must have a frequency of 1 or more\n return !(getMinimumFrequency() < 1 || getMaximumFrequency() < 1);\n }\n\n @NotNull\n public ChronoUnit getChronoUnit() {\n return chronoUnit;\n }\n\n public long getMinimumFrequency() {\n return (long) frequencyStatistics.getMin();\n }\n\n public long getMaximumFrequency() {\n return (long) frequencyStatistics.getMax();\n }\n\n @NotNull\n public SummaryStatistics getFrequencyStatistics() {\n return frequencyStatistics;\n }\n\n @NotNull\n @Contract(pure = true)\n private Instant getLastOccurrenceTimestamp() {\n return lastOccurrenceTimestamp;\n }\n\n @NotNull\n private ChronoFrequency mutateChronoFrequency(long actualFrequency, @NotNull Instant lastOccurrenceTimestamp) {\n if (actualFrequency < 0) {\n throw new IllegalArgumentException(\"Invalid frequency: \" + actualFrequency);\n }\n\n frequencyStatistics.addValue(actualFrequency);\n return new ChronoFrequency(chronoUnit, seriesPosition + 1,\n frequencyStatistics, requireNonNull(lastOccurrenceTimestamp));\n }\n\n private boolean isWithinRange(long frequency) {\n return frequency >= getMinimumFrequency() && frequency <= getMaximumFrequency();\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 ChronoFrequency that = (ChronoFrequency) o;\n\n if (getMinimumFrequency() != that.getMinimumFrequency()) return false;\n if (getMaximumFrequency() != that.getMaximumFrequency()) return false;\n if (chronoUnit != that.chronoUnit) return false;\n return lastOccurrenceTimestamp.equals(that.lastOccurrenceTimestamp);\n }\n\n @Override\n public int hashCode() {\n int result = chronoUnit.hashCode();\n result = 31 * result + (int) (getMinimumFrequency() ^ (getMinimumFrequency() >>> 32));\n result = 31 * result + (int) (getMaximumFrequency() ^ (getMaximumFrequency() >>> 32));\n result = 31 * result + lastOccurrenceTimestamp.hashCode();\n return result;\n }\n\n @NotNull\n @Override\n public String toString() {\n return String.format(\"ChronoFrequency: {%d -> %d; Unit: %s}\",\n getMinimumFrequency(), getMaximumFrequency(), chronoUnit);\n }\n\n}", "public class ChronoPattern extends ChronoAllele {\n\n private final ChronoScaleUnit chronoScaleUnit;\n private int temporalValue;\n\n public ChronoPattern(@NotNull ChronoScaleUnit chronoScaleUnit, int seriesPosition, int temporalValue) {\n super(seriesPosition);\n this.chronoScaleUnit = requireNonNull(chronoScaleUnit);\n this.temporalValue = temporalValue;\n\n if (temporalValue != 0) {\n chronoScaleUnit.observeValue(temporalValue);\n }\n }\n\n /**\n * Create a new ChronoPattern instance with the given temporal pattern value.\n *\n * @param temporalValue temporal pattern value, 0 signifies for every chrono scale unit\n * @return ChronoPattern with the given temporal pattern value\n */\n @NotNull\n public ChronoPattern newInstance(int temporalValue) {\n return new ChronoPattern(chronoScaleUnit, seriesPosition, temporalValue);\n }\n\n /**\n * Creates a new ChronoPattern which has progressed in the ChronoSeries by one step.\n *\n * @param chronoSeries time series data to traverse\n * @return new ChronoPattern of the same chrono scale unit with updated temporal pattern value\n */\n @NotNull\n @Override\n public ChronoPattern mutate(@NotNull ChronoSeries chronoSeries) {\n if (seriesPosition >= requireNonNull(chronoSeries).getSize()) {\n //start from beginning of series\n return new ChronoPattern(chronoScaleUnit, 0, temporalValue);\n }\n\n Instant nextTimestamp = chronoSeries.getTimestamp(seriesPosition);\n LocalDateTime nextDateTime = nextTimestamp.atZone(ZoneOffset.UTC).toLocalDateTime();\n\n int temporalValue = nextDateTime.get(getChronoScaleUnit().getChronoField());\n return new ChronoPattern(chronoScaleUnit, seriesPosition + 1, temporalValue);\n }\n\n @Override\n public boolean isValid() {\n return !getTemporalValue().isPresent() || chronoScaleUnit.isValid(temporalValue);\n }\n\n /**\n * Returns the ChronoScale unit of this ChronoPattern.\n *\n * @return current chrono scale unit\n */\n @NotNull\n public ChronoScaleUnit getChronoScaleUnit() {\n return chronoScaleUnit;\n }\n\n /**\n * Returns the temporal pattern value of this ChronoPattern.\n * A missing temporal patter value means \"every\" of the unit.\n *\n * For example, with a chrono scale unit of SECONDS and a missing temporal value\n * this translates to: every second.\n *\n * @return temporal pattern value, if present\n */\n @NotNull\n public OptionalInt getTemporalValue() {\n if (temporalValue == 0) {\n return OptionalInt.empty();\n }\n return OptionalInt.of(temporalValue);\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 ChronoPattern that = (ChronoPattern) o;\n\n if (temporalValue != that.temporalValue) return false;\n return chronoScaleUnit.equals(that.chronoScaleUnit);\n }\n\n @Override\n public int hashCode() {\n int result = chronoScaleUnit.hashCode();\n result = 31 * result + temporalValue;\n return result;\n }\n\n @NotNull\n @Override\n public String toString() {\n return String.format(\"ChronoPattern: {Unit: %s; Value: %d}\", chronoScaleUnit.getChronoUnit(), temporalValue);\n }\n\n}" ]
import io.chronetic.data.measure.ChronoRange; import io.chronetic.data.measure.ChronoScaleUnit; import io.chronetic.evolution.pool.ChronoGene; import io.chronetic.evolution.pool.allele.ChronoAllele; import io.chronetic.evolution.pool.allele.ChronoFrequency; import io.chronetic.evolution.pool.allele.ChronoPattern; import org.jenetics.util.ISeq; import org.junit.Test; import java.time.DayOfWeek; import java.time.Instant; import java.time.Month; import java.time.temporal.ChronoUnit; import static org.junit.Assert.assertTrue;
package io.chronetic.data; public class ChronoSeriesTest { @Test public void chronoSeriesTest1() { ChronoSeries chronoSeries = ChronoSeries.of( Instant.parse("2011-11-25T08:48:11Z"), Instant.parse("2012-11-30T09:23:16Z"), Instant.parse("2013-11-29T09:51:49Z"), Instant.parse("2014-11-28T08:43:00Z"), Instant.parse("2015-11-27T08:22:25Z") ); ISeq<ChronoAllele> alleleSeq = ISeq.of( new ChronoFrequency(ChronoUnit.YEARS, 0, 1, 1, Instant.now()),
new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.HOURS), 0, 8),
5
andrzejchm/DroidMVP
sample/src/main/java/io/appflate/droidvmp/androidsample/ui/fragments/RepositoriesFragment.java
[ "public enum ApiManager {\n INSTANCE;\n\n private static final String BASE_URL = \"https://api.github.com/\";\n private GithubApi api;\n\n ApiManager() {\n Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)\n .addConverterFactory(\n GsonConverterFactory.create())\n .build();\n\n api = retrofit.create(GithubApi.class);\n }\n\n public GithubApi getApiService() {\n return api;\n }\n\n public static ApiManager getInstance() {\n return INSTANCE;\n }\n}", "public class Repository implements Serializable, Parcelable {\n public static final Parcelable.Creator<Repository> CREATOR =\n new Parcelable.Creator<Repository>() {\n @Override public Repository createFromParcel(Parcel source) {\n return new Repository(source);\n }\n\n @Override public Repository[] newArray(int size) {return new Repository[size];}\n };\n @SerializedName(\"id\") public int id;\n @SerializedName(\"name\") public String name;\n @SerializedName(\"full_name\") public String fullName;\n @SerializedName(\"owner\") public Owner owner;\n @SerializedName(\"private\") public boolean _private;\n @SerializedName(\"html_url\") public String htmlUrl;\n @SerializedName(\"description\") public String description;\n @SerializedName(\"fork\") public boolean fork;\n @SerializedName(\"url\") public String url;\n @SerializedName(\"forks_url\") public String forksUrl;\n @SerializedName(\"keys_url\") public String keysUrl;\n @SerializedName(\"collaborators_url\") public String collaboratorsUrl;\n @SerializedName(\"teams_url\") public String teamsUrl;\n @SerializedName(\"hooks_url\") public String hooksUrl;\n @SerializedName(\"issue_events_url\") public String issueEventsUrl;\n @SerializedName(\"events_url\") public String eventsUrl;\n @SerializedName(\"assignees_url\") public String assigneesUrl;\n @SerializedName(\"branches_url\") public String branchesUrl;\n @SerializedName(\"tags_url\") public String tagsUrl;\n @SerializedName(\"blobs_url\") public String blobsUrl;\n @SerializedName(\"git_tags_url\") public String gitTagsUrl;\n @SerializedName(\"git_refs_url\") public String gitRefsUrl;\n @SerializedName(\"trees_url\") public String treesUrl;\n @SerializedName(\"statuses_url\") public String statusesUrl;\n @SerializedName(\"languages_url\") public String languagesUrl;\n @SerializedName(\"stargazers_url\") public String stargazersUrl;\n @SerializedName(\"contributors_url\") public String contributorsUrl;\n @SerializedName(\"subscribers_url\") public String subscribersUrl;\n @SerializedName(\"subscription_url\") public String subscriptionUrl;\n @SerializedName(\"commits_url\") public String commitsUrl;\n @SerializedName(\"git_commits_url\") public String gitCommitsUrl;\n @SerializedName(\"comments_url\") public String commentsUrl;\n @SerializedName(\"issue_comment_url\") public String issueCommentUrl;\n @SerializedName(\"contents_url\") public String contentsUrl;\n @SerializedName(\"compare_url\") public String compareUrl;\n @SerializedName(\"merges_url\") public String mergesUrl;\n @SerializedName(\"archive_url\") public String archiveUrl;\n @SerializedName(\"downloads_url\") public String downloadsUrl;\n @SerializedName(\"issues_url\") public String issuesUrl;\n @SerializedName(\"pulls_url\") public String pullsUrl;\n @SerializedName(\"milestones_url\") public String milestonesUrl;\n @SerializedName(\"notifications_url\") public String notificationsUrl;\n @SerializedName(\"labels_url\") public String labelsUrl;\n @SerializedName(\"releases_url\") public String releasesUrl;\n @SerializedName(\"deployments_url\") public String deploymentsUrl;\n @SerializedName(\"created_at\") public String createdAt;\n @SerializedName(\"updated_at\") public String updatedAt;\n @SerializedName(\"pushed_at\") public String pushedAt;\n @SerializedName(\"git_url\") public String gitUrl;\n @SerializedName(\"ssh_url\") public String sshUrl;\n @SerializedName(\"clone_url\") public String cloneUrl;\n @SerializedName(\"svn_url\") public String svnUrl;\n @SerializedName(\"homepage\") public String homepage;\n @SerializedName(\"size\") public int size;\n @SerializedName(\"stargazers_count\") public int stargazersCount;\n @SerializedName(\"watchers_count\") public int watchersCount;\n @SerializedName(\"language\") public String language;\n @SerializedName(\"has_issues\") public boolean hasIssues;\n @SerializedName(\"has_downloads\") public boolean hasDownloads;\n @SerializedName(\"has_wiki\") public boolean hasWiki;\n @SerializedName(\"has_pages\") public boolean hasPages;\n @SerializedName(\"forks_count\") public int forksCount;\n @SerializedName(\"mirror_url\") public String mirrorUrl;\n @SerializedName(\"open_issues_count\") public int openIssuesCount;\n @SerializedName(\"forks\") public int forks;\n @SerializedName(\"open_issues\") public int openIssues;\n @SerializedName(\"watchers\") public int watchers;\n @SerializedName(\"default_branch\") public String defaultBranch;\n\n public Repository() {}\n\n protected Repository(Parcel in) {\n this.id = in.readInt();\n this.name = in.readString();\n this.fullName = in.readString();\n this.owner = in.readParcelable(Owner.class.getClassLoader());\n this._private = in.readByte() != 0;\n this.htmlUrl = in.readString();\n this.description = in.readString();\n this.fork = in.readByte() != 0;\n this.url = in.readString();\n this.forksUrl = in.readString();\n this.keysUrl = in.readString();\n this.collaboratorsUrl = in.readString();\n this.teamsUrl = in.readString();\n this.hooksUrl = in.readString();\n this.issueEventsUrl = in.readString();\n this.eventsUrl = in.readString();\n this.assigneesUrl = in.readString();\n this.branchesUrl = in.readString();\n this.tagsUrl = in.readString();\n this.blobsUrl = in.readString();\n this.gitTagsUrl = in.readString();\n this.gitRefsUrl = in.readString();\n this.treesUrl = in.readString();\n this.statusesUrl = in.readString();\n this.languagesUrl = in.readString();\n this.stargazersUrl = in.readString();\n this.contributorsUrl = in.readString();\n this.subscribersUrl = in.readString();\n this.subscriptionUrl = in.readString();\n this.commitsUrl = in.readString();\n this.gitCommitsUrl = in.readString();\n this.commentsUrl = in.readString();\n this.issueCommentUrl = in.readString();\n this.contentsUrl = in.readString();\n this.compareUrl = in.readString();\n this.mergesUrl = in.readString();\n this.archiveUrl = in.readString();\n this.downloadsUrl = in.readString();\n this.issuesUrl = in.readString();\n this.pullsUrl = in.readString();\n this.milestonesUrl = in.readString();\n this.notificationsUrl = in.readString();\n this.labelsUrl = in.readString();\n this.releasesUrl = in.readString();\n this.deploymentsUrl = in.readString();\n this.createdAt = in.readString();\n this.updatedAt = in.readString();\n this.pushedAt = in.readString();\n this.gitUrl = in.readString();\n this.sshUrl = in.readString();\n this.cloneUrl = in.readString();\n this.svnUrl = in.readString();\n this.homepage = in.readString();\n this.size = in.readInt();\n this.stargazersCount = in.readInt();\n this.watchersCount = in.readInt();\n this.language = in.readString();\n this.hasIssues = in.readByte() != 0;\n this.hasDownloads = in.readByte() != 0;\n this.hasWiki = in.readByte() != 0;\n this.hasPages = in.readByte() != 0;\n this.forksCount = in.readInt();\n this.mirrorUrl = in.readString();\n this.openIssuesCount = in.readInt();\n this.forks = in.readInt();\n this.openIssues = in.readInt();\n this.watchers = in.readInt();\n this.defaultBranch = in.readString();\n }\n\n @Override public int describeContents() { return 0; }\n\n @Override public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(this.id);\n dest.writeString(this.name);\n dest.writeString(this.fullName);\n dest.writeParcelable(this.owner, flags);\n dest.writeByte(this._private ? (byte) 1 : (byte) 0);\n dest.writeString(this.htmlUrl);\n dest.writeString(this.description);\n dest.writeByte(this.fork ? (byte) 1 : (byte) 0);\n dest.writeString(this.url);\n dest.writeString(this.forksUrl);\n dest.writeString(this.keysUrl);\n dest.writeString(this.collaboratorsUrl);\n dest.writeString(this.teamsUrl);\n dest.writeString(this.hooksUrl);\n dest.writeString(this.issueEventsUrl);\n dest.writeString(this.eventsUrl);\n dest.writeString(this.assigneesUrl);\n dest.writeString(this.branchesUrl);\n dest.writeString(this.tagsUrl);\n dest.writeString(this.blobsUrl);\n dest.writeString(this.gitTagsUrl);\n dest.writeString(this.gitRefsUrl);\n dest.writeString(this.treesUrl);\n dest.writeString(this.statusesUrl);\n dest.writeString(this.languagesUrl);\n dest.writeString(this.stargazersUrl);\n dest.writeString(this.contributorsUrl);\n dest.writeString(this.subscribersUrl);\n dest.writeString(this.subscriptionUrl);\n dest.writeString(this.commitsUrl);\n dest.writeString(this.gitCommitsUrl);\n dest.writeString(this.commentsUrl);\n dest.writeString(this.issueCommentUrl);\n dest.writeString(this.contentsUrl);\n dest.writeString(this.compareUrl);\n dest.writeString(this.mergesUrl);\n dest.writeString(this.archiveUrl);\n dest.writeString(this.downloadsUrl);\n dest.writeString(this.issuesUrl);\n dest.writeString(this.pullsUrl);\n dest.writeString(this.milestonesUrl);\n dest.writeString(this.notificationsUrl);\n dest.writeString(this.labelsUrl);\n dest.writeString(this.releasesUrl);\n dest.writeString(this.deploymentsUrl);\n dest.writeString(this.createdAt);\n dest.writeString(this.updatedAt);\n dest.writeString(this.pushedAt);\n dest.writeString(this.gitUrl);\n dest.writeString(this.sshUrl);\n dest.writeString(this.cloneUrl);\n dest.writeString(this.svnUrl);\n dest.writeString(this.homepage);\n dest.writeInt(this.size);\n dest.writeInt(this.stargazersCount);\n dest.writeInt(this.watchersCount);\n dest.writeString(this.language);\n dest.writeByte(this.hasIssues ? (byte) 1 : (byte) 0);\n dest.writeByte(this.hasDownloads ? (byte) 1 : (byte) 0);\n dest.writeByte(this.hasWiki ? (byte) 1 : (byte) 0);\n dest.writeByte(this.hasPages ? (byte) 1 : (byte) 0);\n dest.writeInt(this.forksCount);\n dest.writeString(this.mirrorUrl);\n dest.writeInt(this.openIssuesCount);\n dest.writeInt(this.forks);\n dest.writeInt(this.openIssues);\n dest.writeInt(this.watchers);\n dest.writeString(this.defaultBranch);\n }\n}", "public class RepositoriesPresentationModel implements Serializable, Parcelable {\n public static final Parcelable.Creator<RepositoriesPresentationModel> CREATOR =\n new Parcelable.Creator<RepositoriesPresentationModel>() {\n @Override public RepositoriesPresentationModel createFromParcel(\n Parcel source) {return new RepositoriesPresentationModel(source);}\n\n @Override public RepositoriesPresentationModel[] newArray(\n int size) {return new RepositoriesPresentationModel[size];}\n };\n private List<Repository> repositories;\n private String username;\n\n public RepositoriesPresentationModel(String username) {\n this.username = username;\n }\n\n protected RepositoriesPresentationModel(Parcel in) {\n this.repositories = in.createTypedArrayList(Repository.CREATOR);\n this.username = in.readString();\n }\n\n public String getUsername() {\n return username;\n }\n\n public List<Repository> getRepositories() {\n return repositories;\n }\n\n public void setRepositories(List<Repository> repositories) {\n this.repositories = repositories;\n }\n\n public boolean shouldFetchRepositories() {\n return repositories == null;\n }\n\n @Override public int describeContents() { return 0; }\n\n @Override public void writeToParcel(Parcel dest, int flags) {\n dest.writeTypedList(this.repositories);\n dest.writeString(this.username);\n }\n}", "public class ReposRecyclerAdapter\n extends RecyclerView.Adapter<ReposRecyclerAdapter.RepoViewHolder> {\n private final List<Repository> repositories;\n\n public ReposRecyclerAdapter(List<Repository> repositories) {\n this.repositories = repositories;\n }\n\n @Override public RepoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n return new RepoViewHolder(LayoutInflater.from(parent.getContext())\n .inflate(R.layout.cell_repo_view, parent, false));\n }\n\n @Override @SuppressFBWarnings(\"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR\")\n public void onBindViewHolder(RepoViewHolder holder, int position) {\n Repository repository = repositories.get(position);\n holder.title.setText(repository.name);\n holder.starsCount.setText(String.format(\"%s ★\", repository.stargazersCount));\n }\n\n @Override public int getItemCount() {\n return repositories.size();\n }\n\n public static class RepoViewHolder extends RecyclerView.ViewHolder {\n @Bind(R.id.repoTitleText) TextView title;\n @Bind(R.id.repoStarsCountText) TextView starsCount;\n\n public RepoViewHolder(View itemView) {\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n}", "public abstract class BaseFragment<M, V extends DroidMVPView, P extends DroidMVPPresenter<V, M>>\n extends DroidMVPFragment<M, V, P> {\n @Inject protected P presenter;\n\n @NonNull @Override protected P createPresenter() {\n //this field will be populated by field injeciton from dagger\n // your presenter should not accept the presentationModel as its constructor's paramteter.\n // Instead, it will be provided by #attachView method.\n return presenter;\n }\n}", "public interface RepositoriesView extends DroidMVPView {\n void showTitle(String username);\n\n void showLoadingProgress();\n\n void showRepositoriesList(List<Repository> repositories);\n\n void showRepositoriesFetchError();\n}", "public class RepositoriesPresenter\n extends SimpleDroidMVPPresenter<RepositoriesView, RepositoriesPresentationModel> {\n private GithubApi githubApi;\n\n @Inject public RepositoriesPresenter(GithubApi githubApi) {\n this.githubApi = githubApi;\n }\n\n @Override public void attachView(RepositoriesView mvpView,\n RepositoriesPresentationModel presentationModel) {\n super.attachView(mvpView, presentationModel);\n if (presentationModel.shouldFetchRepositories()) {\n getUserRepositories(presentationModel);\n } else {\n mvpView.showRepositoriesList(presentationModel.getRepositories());\n }\n mvpView.showTitle(presentationModel.getUsername());\n }\n\n private void getUserRepositories(RepositoriesPresentationModel presentationModel) {\n if (getMvpView() != null) {\n getMvpView().showLoadingProgress();\n }\n githubApi.getUserRepositories(presentationModel.getUsername())\n .enqueue(new Callback<List<Repository>>() {\n public void onResponse(Call<List<Repository>> call,\n Response<List<Repository>> response) {\n if (response.isSuccessful()) {\n onRepositoriesFetched(response.body());\n } else {\n onRepositoriesFetchError();\n }\n }\n\n public void onFailure(Call<List<Repository>> call, Throwable t) {\n onRepositoriesFetchError();\n }\n });\n }\n\n private void onRepositoriesFetchError() {\n if (getMvpView() != null) {\n getMvpView().showRepositoriesFetchError();\n }\n }\n\n private void onRepositoriesFetched(List<Repository> repositories) {\n getPresentationModel().setRepositories(repositories);\n if (getMvpView() != null) {\n getMvpView().showRepositoriesList(repositories);\n }\n }\n}", "public final class Constants {\n public static final String PARAM_USERNAME = \"username\";\n\n private Constants() {\n }\n}" ]
import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ViewAnimator; import butterknife.Bind; import butterknife.ButterKnife; import io.appflate.droidvmp.androidsample.R; import io.appflate.droidvmp.androidsample.domain.ApiManager; import io.appflate.droidvmp.androidsample.model.Repository; import io.appflate.droidvmp.androidsample.model.presentation.RepositoriesPresentationModel; import io.appflate.droidvmp.androidsample.ui.adapters.ReposRecyclerAdapter; import io.appflate.droidvmp.androidsample.ui.base.BaseFragment; import io.appflate.droidvmp.androidsample.ui.mvpviews.RepositoriesView; import io.appflate.droidvmp.androidsample.ui.presenters.RepositoriesPresenter; import io.appflate.droidvmp.androidsample.utils.Constants; import java.util.List;
/* * Copyright (C) 2016 Appflate.io * * 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 io.appflate.droidvmp.androidsample.ui.fragments; /** * Created by andrzejchm on 22/06/16. */ public class RepositoriesFragment extends BaseFragment<RepositoriesPresentationModel, RepositoriesView, RepositoriesPresenter> implements RepositoriesView { public static final String TAG = RepositoriesFragment.class.getCanonicalName(); private static final int CHILD_PROGRESS_VIEW = 0; private static final int CHILD_CONTENT_VIEW = 1; @Bind(R.id.reposRecyclerView) RecyclerView reposRecyclerView; @Bind(R.id.reposAnimator) ViewAnimator reposAnimator; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @NonNull @Override protected RepositoriesPresenter createPresenter() { return new RepositoriesPresenter(ApiManager.getInstance().getApiService()); } @NonNull @Override protected RepositoriesPresentationModel createPresentationModel() { String username = getArguments().getString(Constants.PARAM_USERNAME); return new RepositoriesPresentationModel(username); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_repositories, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @Override public void showTitle(String username) { getActivity().setTitle(username); } @Override public void showLoadingProgress() { reposAnimator.setDisplayedChild(CHILD_PROGRESS_VIEW); } @Override public void showRepositoriesList(List<Repository> repositories) { reposAnimator.setDisplayedChild(CHILD_CONTENT_VIEW); reposRecyclerView.setLayoutManager( new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
reposRecyclerView.setAdapter(new ReposRecyclerAdapter(repositories));
3
dedyk/JaponskiPomocnik
app/src/main/java/pl/idedyk/android/japaneselearnhelper/test/WordTest.java
[ "public class JapaneseAndroidLearnHelperApplication extends MultiDexApplication {\n\n\tpublic static final ThemeType defaultThemeType = ThemeType.BLACK;\n\t\n\tprivate static JapaneseAndroidLearnHelperApplication singleton;\n\n\tpublic static JapaneseAndroidLearnHelperApplication getInstance() {\n\t\treturn singleton;\n\t}\n\t\n\tprivate JapaneseAndroidLearnHelperContext context;\n\t\n\tprivate DictionaryManagerCommon dictionaryManager;\n\t\n\tprivate ConfigManager configManager;\n\t\n\tprivate WordDictionaryMissingWordQueue wordDictionaryMissingWordQueue;\n\n\tprivate QueueEventThread queueEventThread;\n\t\n\tprivate Typeface babelStoneHanSubset = null;\n\t\n\t// private Tracker tracker = null;\n\n\t@Override\n\tpublic void onConfigurationChanged(Configuration newConfig) {\n\t\tsuper.onConfigurationChanged(newConfig);\n\t}\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tsingleton = this;\n\t}\n\n\t@Override\n\tpublic void onLowMemory() {\n\t\tsuper.onLowMemory();\n\t}\n\n\t@Override\n\tpublic void onTerminate() {\n\t\tsuper.onTerminate();\n\n\t\tstopQueueThread();\n\n\t\tif (dictionaryManager != null) {\n\t\t\tdictionaryManager.close();\n\t\t}\n\t}\n\t\n\tpublic JapaneseAndroidLearnHelperContext getContext() {\n\t\t\n\t\tif (context == null) {\n\t\t\tcontext = new JapaneseAndroidLearnHelperContext();\n\t\t}\n\t\t\n\t\treturn context;\n\t}\n\n\tpublic DictionaryManagerCommon getDictionaryManager(final Activity activity) {\n\t\t\n\t\tResources resources = activity.getResources();\n\t\tAssetManager assets = activity.getAssets();\n\t\t\t\t\n\t\tif (dictionaryManager == null) {\n\t\t\t\n\t int versionCode = 0;\n\t \n\t try {\n\t \tPackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n\t \t\n\t versionCode = packageInfo.versionCode;\n\n\t } catch (NameNotFoundException e) { \t\n\t }\n\t \n\t ILoadWithProgress loadWithProgress = new ILoadWithProgress() {\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tpublic void setMaxValue(int maxValue) {\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tpublic void setError(String errorMessage) {\t\t\t\t\t\n\t\t\t\t\tthrow new RuntimeException(errorMessage);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tpublic void setDescription(String desc) {\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tpublic void setCurrentPos(int currentPos) {\n\t\t\t\t}\n\t\t\t};\n\t\t\t\t\t\t\n\t\t\tdictionaryManager = DictionaryManagerCommon.getDictionaryManager();\n\t\t\t\n\t\t\tdictionaryManager.init(activity, loadWithProgress, resources, assets, getPackageName(), versionCode);\n\t\t}\n\t\t\n\t\treturn dictionaryManager;\n\t}\n\n\tpublic void setDictionaryManager(DictionaryManagerCommon dictionaryManager) {\n\t\tthis.dictionaryManager = dictionaryManager;\n\t}\n\n\tpublic DataManager getDataManager() {\n\n\t\tif (dictionaryManager == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn dictionaryManager.getDataManager();\n\t}\n\n\tpublic ConfigManager getConfigManager(Activity activity) {\n\t\t\n\t\tif (configManager == null) {\n\t\t\tconfigManager = new ConfigManager(activity);\n\t\t}\n\t\t\n\t\treturn configManager;\n\t}\n\n\tpublic void setConfigManager(ConfigManager configManager) {\n\t\tthis.configManager = configManager;\n\t}\n\t\n\tpublic WordDictionaryMissingWordQueue getWordDictionaryMissingWordQueue(Activity activity) {\n\t\t\n\t\tif (wordDictionaryMissingWordQueue == null) {\n\t\t\twordDictionaryMissingWordQueue = new WordDictionaryMissingWordQueue(activity);\n\t\t}\n\t\t\n\t\treturn wordDictionaryMissingWordQueue;\n\t}\n\n\tpublic void setWordDictionaryMissingWordQueue(WordDictionaryMissingWordQueue wordDictionaryMissingWordQueue) {\n\t\tthis.wordDictionaryMissingWordQueue = wordDictionaryMissingWordQueue;\n\t}\n\n\tpublic Typeface getBabelStoneHanSubset(AssetManager assetManager) {\n\t\t\n\t\tif (babelStoneHanSubset != null) {\n\t\t\treturn babelStoneHanSubset;\n\t\t}\n\t\t\n\t\tbabelStoneHanSubset = Typeface.createFromAsset(getAssets(), \"BabelStoneHan-subset.ttf\");\n\t\t\n\t\treturn babelStoneHanSubset;\n\t}\n\n\tpublic void setContentViewAndTheme(Activity activity, int contentViewId) {\n\t\tactivity.setTheme(getThemeType(activity).styleId);\n\n\t\tDataBindingUtil.setContentView(activity, contentViewId);\n\t}\n\n\tpublic ThemeType getThemeType() {\n\t\treturn getThemeType(null);\n\t}\n\n\tprivate ThemeType getThemeType(Activity activity) {\n\n\t\tif (configManager != null) {\n\t\t\treturn configManager.getCommonConfig().getThemeType(defaultThemeType);\n\t\t}\n\n\t\tif (activity == null) {\n\t\t\treturn defaultThemeType;\n\t\t}\n\n\t\tgetConfigManager(activity);\n\n\t\tif (configManager != null) {\n\t\t\treturn configManager.getCommonConfig().getThemeType(defaultThemeType);\n\t\t}\n\n\t\treturn defaultThemeType;\n\t}\n\n\tpublic int getLinkColor() {\n\n\t\tTypedArray typedArray = getTheme().obtainStyledAttributes(\n\t\t\t\tgetThemeType().getStyleId(),\n\t\t\t\tnew int[] { android.R.attr.textColorLink });\n\n\t\tint intColor = typedArray.getColor(0, 0);\n\n\t\ttypedArray.recycle();\n\n\t\treturn intColor;\n\t}\n\n\t/*\n\tpublic Tracker getTracker() {\n\t\t\n\t\tif (tracker != null) {\n\t\t\treturn tracker;\n\t\t}\n\t\t\n\t\tGoogleAnalytics analytics = GoogleAnalytics.getInstance(this);\n\n\t\ttracker = analytics.newTracker(R.xml.app_tracker);\n\n\t\ttracker.enableAdvertisingIdCollection(true);\n\t\t\n\t\treturn tracker;\t\t\n\t}\n\t*/\n\n\tpublic void logScreen(Activity activity, String screenName) {\n\n\t /*\n\t\tTracker tracker = getTracker();\n\t\t\n\t\ttracker.setScreenName(screenName);\n\t\t\n\t\ttracker.send(new HitBuilders.AppViewBuilder().build());\n\t\t*/\n\n\t\taddQueueEvent(activity, new StatLogScreenEvent(getConfigManager(activity).getCommonConfig().getOrGenerateUniqueUserId(), screenName));\n\t}\n\t\n\tpublic void logEvent(Activity activity, String screenName, String actionName, String label) {\n\n\t /*\n\t\tTracker tracker = getTracker();\n\t\t\n\t\ttracker.send(new HitBuilders.EventBuilder()\n\t\t\t\t.setCategory(screenName)\n\t\t\t\t.setAction(actionName).\n\t\t\t\tsetLabel(label).\n\t\t\t\tbuild());\n\t\t*/\n\n\t\taddQueueEvent(activity, new StatLogEventEvent(getConfigManager(activity).getCommonConfig().getOrGenerateUniqueUserId(), screenName, actionName, label));\n\t}\n\n\tpublic synchronized void startQueueThread(Activity activity) {\n\n\t\tif (queueEventThread == null || queueEventThread.isAlive() == false) {\n\n queueEventThread = new QueueEventThread(activity.getPackageManager(), activity.getPackageName());\n\n queueEventThread.start();\n\t\t}\n\t}\n\n\tpublic synchronized void stopQueueThread() {\n\n\t\tif (queueEventThread != null && queueEventThread.isAlive() == true) {\n\n queueEventThread.requestStop();\n\n\t\t\ttry {\n queueEventThread.join(11000);\n\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\t// noop\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic synchronized void addQueueEvent(Activity activity, IQueueEvent queueEvent) {\n\n\t\tstartQueueThread(activity);\n\n\t\tif (queueEventThread != null) {\n\n\t\t\tThemeType themeType = getThemeType(activity);\n\n\t\t\tqueueEventThread.addQueueEvent(activity, themeType, queueEvent);\n\t\t}\n\t}\n\n\tpublic enum ThemeType {\n\n\t\tBLACK(\tR.style.JapaneseDictionaryBlackStyle,\n\t\t\t\tandroid.R.color.white,\n\t\t\t\tR.color.title_background_for_black,\n\t\t\t\tandroid.R.color.white,\n\t\t\t\tColor.DKGRAY,\n\t\t\t\tR.drawable.delete_for_black,\n\t\t\t\tR.drawable.user_group_list_for_black,\n\t\t\t\tR.drawable.listening_for_black),\n\n\t\tWHITE(\tR.style.JapaneseDictionaryWhiteStyle,\n\t\t\t\tandroid.R.color.black,\n\t\t\t\tR.color.title_background_for_white,\n\t\t\t\tandroid.R.color.black,\n\t\t\t\tColor.WHITE,\n\t\t\t\tR.drawable.delete_for_white,\n\t\t\t\tR.drawable.user_group_list_for_white,\n\t\t\t\tR.drawable.listening_for_white);\n\n\t\tprivate int styleId;\n\n\t\tprivate int textColorId;\n\n\t\tprivate int titleItemBackgroundColorId;\n\n\t\tprivate int kanjiStrokeColorId;\n\n\t\tprivate int kanjiSearchRadicalInactiveColorId;\n\n\t\tprivate int deleteIconId;\n\n\t\tprivate int userGroupListIconId;\n\n\t\tprivate int listenIconId;\n\n\t\tprivate ThemeType(int styleId, int textColorId, int titleItemBackgroundColorId, int kanjiStrokeColorId, int kanjiSearchRadicalInactiveColorId, int deleteIconId, int userGroupListIconId, int listenIconId) {\n\t\t\tthis.styleId = styleId;\n\t\t\tthis.textColorId = textColorId;\n\t\t\tthis.titleItemBackgroundColorId = titleItemBackgroundColorId;\n\t\t\tthis.kanjiStrokeColorId = kanjiStrokeColorId;\n\t\t\tthis.kanjiSearchRadicalInactiveColorId = kanjiSearchRadicalInactiveColorId;\n\t\t\tthis.deleteIconId = deleteIconId;\n\t\t\tthis.userGroupListIconId = userGroupListIconId;\n\t\t\tthis.listenIconId = listenIconId;\n\t\t}\n\n\t\tpublic int getStyleId() {\n\t\t\treturn styleId;\n\t\t}\n\n\t\tpublic int getTextColorId() {\n\t\t\treturn textColorId;\n\t\t}\n\n\t\tpublic int getTextColorAsColor() {\n\t\t\treturn getInstance().getResources().getColor(textColorId);\n\t\t}\n\n\t\tpublic int getTitleItemBackgroundColorAsColor() {\n\t\t\treturn getInstance().getResources().getColor(titleItemBackgroundColorId);\n\t\t}\n\n\t\tpublic Drawable getTitleItemBackgroundColorAsDrawable() {\n\t\t\tColorDrawable colorDrawable = new ColorDrawable(getTitleItemBackgroundColorAsColor());\n\n\t\t\treturn colorDrawable;\n\t\t}\n\n\t\tpublic int getKanjiStrokeColorAsColor() {\n\t\t\treturn getInstance().getResources().getColor(kanjiStrokeColorId);\n\t\t}\n\n\t\tpublic int getKanjiSearchRadicalInactiveColorId() {\n\t\t\treturn kanjiSearchRadicalInactiveColorId;\n\t\t}\n\n\t\tpublic int getDeleteIconId() {\n\t\t\treturn deleteIconId;\n\t\t}\n\n\t\tpublic int getUserGroupListIconId() {\n\t\t\treturn userGroupListIconId;\n\t\t}\n\n\t\tpublic Drawable getUserGroupListIconAsDrawable() {\n\t\t\treturn getInstance().getResources().getDrawable(userGroupListIconId);\n\t\t}\n\n\t\tpublic int getListenIconId() {\n\t\t\treturn listenIconId;\n\t\t}\n\t}\n}", "public class MenuShorterHelper {\n\n\tpublic static void onCreateOptionsMenu(Menu menu) {\n\t\tmenu.add(Menu.NONE, R.id.main_menu_kana_text_menu_item, Menu.NONE, R.string.main_menu_kana_text_short);\n\t\tmenu.add(Menu.NONE, R.id.main_menu_counters_text_menu_item, Menu.NONE, R.string.main_menu_counters_text_short);\n\t\tmenu.add(Menu.NONE, R.id.main_menu_keigo_table_text_menu_item, Menu.NONE, R.string.main_menu_keigo_table_text_short);\n\t\tmenu.add(Menu.NONE, R.id.main_menu_transitive_intransitive_pairs_table_text_menu_item, Menu.NONE, R.string.main_menu_transitive_intransitive_pairs_table_text_short);\n\t\tmenu.add(Menu.NONE, R.id.main_menu_dictionary_text_menu_item, Menu.NONE, R.string.main_menu_dictionary_text);\n\t\tmenu.add(Menu.NONE, R.id.main_menu_kanji_text_menu_item, Menu.NONE, R.string.main_menu_kanji_text_short);\n\t\t// menu.add(Menu.NONE, R.id.main_menu_kanji_recognizer_text_menu_item, Menu.NONE, R.string.main_menu_kanji_recognizer_text_short);\n\t\tmenu.add(Menu.NONE, R.id.main_menu_show_user_group_menu_item, Menu.NONE, R.string.main_menu_show_user_group_text);\n\t}\n\t\n\tpublic static boolean onOptionsItemSelected(MenuItem item, Context applicationContext, Activity activity) {\n\t\t\n\t\tint itemId = item.getItemId();\n\t\t\n\t\tif (itemId == R.id.main_menu_kana_text_menu_item) { // kana table\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, Kana.class);\n\n\t\t\tactivity.startActivity(intent);\n\t\t\t\n\t\t\treturn true;\n\t\t} else if (itemId == R.id.main_menu_counters_text_menu_item) { // counter table\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, CountersActivity.class);\n\n\t\t\tactivity.startActivity(intent);\n\t\t\t\n\t\t\treturn true;\n\t\t} else if (itemId == R.id.main_menu_keigo_table_text_menu_item) { // keigo table\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, KeigoTable.class);\n\n\t\t\tactivity.startActivity(intent);\n\t\t\t\n\t\t\treturn true;\n\t\t} else if (itemId == R.id.main_menu_transitive_intransitive_pairs_table_text_menu_item) { // transitive intransitive pairs table\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, TransitiveIntransitivePairsTable.class);\n\n\t\t\tactivity.startActivity(intent);\n\t\t\t\n\t\t} else if (itemId == R.id.main_menu_dictionary_text_menu_item) { // dictionary\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, WordDictionaryTab.class);\n\n\t\t\tactivity.startActivity(intent);\n\t\t\t\n\t\t\treturn true;\n\t\t} else if (itemId == R.id.main_menu_kanji_text_menu_item) { // kanji search\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, KanjiSearch.class);\n\n\t\t\tactivity.startActivity(intent);\n\t\t\t\n\t\t\treturn true;\n\t\t/* } else if (itemId == R.id.main_menu_kanji_recognizer_text_menu_item) { // kanji recognize\n\t\t\t\n\t\t\tIntent intent = new Intent(applicationContext, KanjiRecognizeActivity.class);\n\n\t\t\tactivity.startActivity(intent);\t\n\t\t\t\n\t\t\treturn true;\n\t\t*/\n\t\t} else if (itemId == R.id.main_menu_show_user_group_menu_item) { // pokaz grupy uzytkownika\n\n\t\t\tIntent intent = new Intent(applicationContext, UserGroupActivity.class);\n\n\t\t\tactivity.startActivity(intent);\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n}", "public class WordTestConfig {\n\t\t\n\tprivate final String wordTestConfigPrefix = \"wordTestConfig_\";\n\t\t\n\tprivate final String repeatNumberPostfix = \"repeatNumber\";\n\t\t\t\t\n\tprivate final String wordGroupsPostfix = \"wordGroups\";\n\n\tprivate final String wordUserGroupsPostfix = \"wordUserGroups\";\n\t\t\n\tprivate final String randomPostfix = \"random\";\n\t\t\n\tprivate final String untilSuccessPostfix = \"untilSuccess\";\n\t\t\n\tprivate final String untilSuccessNewWordLimitPostfix = \"untilSuccessNewWordLimit\";\n\t\t\n\tprivate final String showKanjiPostfix = \"showKanji\";\n\t\t\n\tprivate final String showKanaPostfix = \"showKana\";\n\t\t\n\tprivate final String showTranslatePostfix = \"showTranslate\";\n\t\t\n\tprivate final String showAdditionalInfoPostfix = \"showAdditionalInfo\";\n\t\t\n\tprivate final String wordTestModePostfix = \"wordTestMode\";\n\t\t\n\tpublic Integer getRepeatNumber() {\n\t\treturn preferences.getInt(wordTestConfigPrefix + repeatNumberPostfix, 1);\n\t}\n\t\t\n\tpublic void setRepeatNumber(int repeatNumber) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putInt(wordTestConfigPrefix + repeatNumberPostfix, repeatNumber);\n\t\t\t\n\t\teditor.commit();\t\t\t\n\t}\t\n\t\t\n\tpublic Set<String> getChosenWordGroups() {\n\t\t\t\n\t\tSet<String> result = new HashSet<String>();\n\t\t\t\n\t\tString chosenWordGroupString = preferences.getString(wordTestConfigPrefix + wordGroupsPostfix, null);\n\t\t\t\n\t\tif (chosenWordGroupString == null || chosenWordGroupString.trim().equals(\"\") == true) {\n\t\t\treturn result;\n\t\t}\n\t\t\t\n\t\tString[] chosenWordGroupSplited = chosenWordGroupString.split(\",\");\n\t\t\t\n\t\tfor (String currentChosenWordGroup : chosenWordGroupSplited) {\n\t\t\tresult.add(currentChosenWordGroup);\n\t\t}\n\t\t\t\n\t\treturn result;\n\t}\n\n\tpublic Set<Integer> getChosenWordUserGroups() {\n\n\t\tSet<Integer> result = new HashSet<Integer>();\n\n\t\tString chosenWordUserGroupString = preferences.getString(wordTestConfigPrefix + wordUserGroupsPostfix, null);\n\n\t\tif (chosenWordUserGroupString == null || chosenWordUserGroupString.trim().equals(\"\") == true) {\n\t\t\treturn result;\n\t\t}\n\n\t\tString[] chosenWordUserGroupSplited = chosenWordUserGroupString.split(\",\");\n\n\t\tfor (String currentChosenWordUserGroupId : chosenWordUserGroupSplited) {\n\t\t\tresult.add(new Integer(currentChosenWordUserGroupId));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic void setChosenWordGroups(List<String> chosenWordGroupsNumberList) {\n\t\t\t\n\t\tif (chosenWordGroupsNumberList == null) {\n\t\t\treturn;\n\t\t}\n\t\t\t\n\t\tStringBuffer chosenWordGroupsNumberSb = new StringBuffer();\n\t\t\t\n\t\tfor (int chosenWordGroupsNumberListIdx = 0; chosenWordGroupsNumberListIdx < chosenWordGroupsNumberList.size(); ++chosenWordGroupsNumberListIdx) {\n\t\t\t\t\n\t\t\tchosenWordGroupsNumberSb.append(chosenWordGroupsNumberList.get(chosenWordGroupsNumberListIdx));\n\t\t\t\t\n\t\t\tif (chosenWordGroupsNumberListIdx != chosenWordGroupsNumberList.size() - 1) {\n\t\t\t\tchosenWordGroupsNumberSb.append(\",\");\t\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putString(wordTestConfigPrefix + wordGroupsPostfix, chosenWordGroupsNumberSb.toString());\n\t\t\t\n\t\teditor.commit();\n\t}\n\n\tpublic void setChosenWordUserGroups(List<Integer> chosenWordUserGroupsNumberList) {\n\n\t\tif (chosenWordUserGroupsNumberList == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tStringBuffer chosenWordUserGroupsNumberSb = new StringBuffer();\n\n\t\tfor (int chosenWordUserGroupsNumberListIdx = 0; chosenWordUserGroupsNumberListIdx < chosenWordUserGroupsNumberList.size(); ++chosenWordUserGroupsNumberListIdx) {\n\n\t\t\tchosenWordUserGroupsNumberSb.append(chosenWordUserGroupsNumberList.get(chosenWordUserGroupsNumberListIdx));\n\n\t\t\tif (chosenWordUserGroupsNumberListIdx != chosenWordUserGroupsNumberList.size() - 1) {\n\t\t\t\tchosenWordUserGroupsNumberSb.append(\",\");\n\t\t\t}\n\t\t}\n\n\t\tEditor editor = preferences.edit();\n\n\t\teditor.putString(wordTestConfigPrefix + wordUserGroupsPostfix, chosenWordUserGroupsNumberSb.toString());\n\n\t\teditor.commit();\n\t}\n\n\tpublic Boolean getRandom() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + randomPostfix, true);\n\t}\n\n\tpublic void setRandom(boolean random) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + randomPostfix, random);\n\t\t\t\n\t\teditor.commit();\n\t}\n\n\tpublic Boolean getUntilSuccess() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + untilSuccessPostfix, true);\n\t}\n\n\tpublic void setUntilSuccess(boolean untilSuccess) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + untilSuccessPostfix, untilSuccess);\n\t\t\t\n\t\teditor.commit();\n\t}\n\n\tpublic Boolean getUntilSuccessNewWordLimit() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + untilSuccessNewWordLimitPostfix, false);\n\t}\n\n\tpublic void setUntilSuccessNewWordLimit(boolean untilSuccessNewWordLimit) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + untilSuccessNewWordLimitPostfix, untilSuccessNewWordLimit);\n\t\t\t\n\t\teditor.commit();\n\t}\n\t\t\n\tpublic Boolean getShowKanji() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + showKanjiPostfix, true);\n\t}\n\n\tpublic void setShowKanji(boolean showKanji) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + showKanjiPostfix, showKanji);\n\t\t\t\n\t\teditor.commit();\n\t}\n\n\tpublic Boolean getShowKana() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + showKanaPostfix, true);\n\t}\n\n\tpublic void setShowKana(boolean showKanji) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + showKanaPostfix, showKanji);\n\t\t\t\n\t\teditor.commit();\n\t}\n\t\t\n\tpublic Boolean getShowTranslate() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + showTranslatePostfix, true);\n\t}\n\n\tpublic void setShowTranslate(boolean showTranslate) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + showTranslatePostfix, showTranslate);\n\t\t\t\n\t\teditor.commit();\n\t}\n\n\tpublic Boolean getShowAdditionalInfo() {\n\t\treturn preferences.getBoolean(wordTestConfigPrefix + showAdditionalInfoPostfix, true);\n\t}\n\n\tpublic void setAdditionalInfoTranslate(boolean showAdditionalInfo) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putBoolean(wordTestConfigPrefix + showAdditionalInfoPostfix, showAdditionalInfo);\n\t\t\t\n\t\teditor.commit();\n\t}\n\t\t\n\tpublic WordTestMode getWordTestMode() {\n\t\t\t\n\t\tString wordTestMode = preferences.getString(wordTestConfigPrefix + wordTestModePostfix, WordTestMode.INPUT.toString());\n\t\t\t\t\t\t\n\t\treturn WordTestMode.valueOf(wordTestMode);\n\t}\n\t\t\n\tpublic void setWordTestMode(WordTestMode wordTestMode) {\n\t\t\t\n\t\tEditor editor = preferences.edit();\n\t\t\t\n\t\teditor.putString(wordTestConfigPrefix + wordTestModePostfix, wordTestMode.toString());\n\t\t\t\n\t\teditor.commit();\n\t}\n}", "public class JapaneseAndroidLearnHelperContext {\n\t\n\tprivate JapaneseAndroidLearnHelperWordTestContext wordTestContext;\n\t\n\tprivate JapaneseAndroidLearnHelperKanaTestContext kanaTestContext;\n\n\tprivate JapaneseAndroidLearnHelperKanjiTestContext kanjiTestContext;\n\t\n\tprivate JapaneseAndroidLearnHelperDictionaryHearContext dictionaryHearContext;\n\n\tpublic JapaneseAndroidLearnHelperContext() {\n\t\tthis.wordTestContext = new JapaneseAndroidLearnHelperWordTestContext();\n\t\tthis.kanaTestContext = new JapaneseAndroidLearnHelperKanaTestContext();\n\t\tthis.kanjiTestContext = new JapaneseAndroidLearnHelperKanjiTestContext();\n\t\tthis.dictionaryHearContext = new JapaneseAndroidLearnHelperDictionaryHearContext();\n\t}\n\n\tpublic JapaneseAndroidLearnHelperWordTestContext getWordTestContext() {\n\t\treturn wordTestContext;\n\t}\n\t\n\tpublic JapaneseAndroidLearnHelperKanaTestContext getKanaTestContext() {\n\t\treturn kanaTestContext;\n\t}\n\n\tpublic JapaneseAndroidLearnHelperKanjiTestContext getKanjiTestContext() {\n\t\treturn kanjiTestContext;\n\t}\n\n\tpublic JapaneseAndroidLearnHelperDictionaryHearContext getDictionaryHearContext() {\n\t\treturn dictionaryHearContext;\n\t}\n}", "public class JapaneseAndroidLearnHelperWordTestContext {\n\t\n\tprivate EntryOrderList<DictionaryEntry> wordsTest;\n\t\n\tprivate int wordTestAnswers = 0;\n\tprivate int wordTestCorrectAnswers = 0;\n\tprivate int wordTestIncorrentAnswers = 0;\n\t\n\tprivate boolean wordTestOverviewShowAnswer = false;\n\t\t\n\tpublic void setWordsTest(EntryOrderList<DictionaryEntry> wordsTest) {\n\t\tthis.wordsTest = wordsTest;\n\t\t\n\t\tthis.wordTestAnswers = 0;\n\t\tthis.wordTestCorrectAnswers = 0;\n\t\tthis.wordTestIncorrentAnswers = 0;\n\t\t\n\t\tthis.wordTestOverviewShowAnswer = false;\n\t}\n\t\n\tpublic EntryOrderList<DictionaryEntry> getWordsTest() {\n\t\treturn wordsTest;\n\t}\n\n\tpublic int getWordTestAnswers() {\n\t\treturn wordTestAnswers;\n\t}\n\n\tpublic int getWordTestCorrectAnswers() {\n\t\treturn wordTestCorrectAnswers;\n\t}\n\n\tpublic int getWordTestIncorrentAnswers() {\n\t\treturn wordTestIncorrentAnswers;\n\t}\n\n\tpublic void addWordTestAnswers(int addValue) {\n\t\tthis.wordTestAnswers += addValue;\n\t}\n\n\tpublic void addWordTestCorrectAnswers(int addValue) {\n\t\tthis.wordTestCorrectAnswers += addValue;\n\t}\n\n\tpublic void addWordTestIncorrentAnswers(int addValue) {\n\t\tthis.wordTestIncorrentAnswers += addValue;\n\t}\n\t\n\tpublic boolean getAndSwitchWordTestOverviewShowAnswer() {\n\t\t\n\t\tboolean result = wordTestOverviewShowAnswer;\n\t\t\n\t\twordTestOverviewShowAnswer = !wordTestOverviewShowAnswer;\n\t\t\n\t\treturn result;\n\t}\n}", "@SuppressWarnings(\"deprecation\")\npublic class WordDictionaryDetails extends Activity {\n\n\tprivate List<IScreenItem> generatedDetails;\n\n\tprivate TtsConnector ttsConnector;\n\n\tprivate final Stack<Integer> backScreenPositionStack = new Stack<Integer>();\n\n\tprivate List<IScreenItem> searchScreenItemList = null;\n\n\tprivate Integer searchScreenItemCurrentPos = null;\n\n\tprivate DictionaryEntry dictionaryEntry = null;\n\tprivate DictionaryEntryType forceDictionaryEntryType = null;\n\n\t//\n\n\tprivate final static int ADD_ITEM_ID_TO_USER_GROUP_ACTIVITY_REQUEST_CODE = 1;\n\n\t@Override\n\tprotected void onDestroy() {\n\n\t\tif (ttsConnector != null) {\n\t\t\tttsConnector.stop();\n\t\t}\n\n\t\tsuper.onDestroy();\n\t}\n\n\t@Override\n\tprotected void onPause() {\n\t\tsuper.onPause();\n\t}\n\n\t@Override\n\tprotected void onRestart() {\n\t\tsuper.onRestart();\n\t}\n\n\t@Override\n\tprotected void onResume() {\n\t\tsuper.onResume();\n\t}\n\n\t@Override\n\tprotected void onStart() {\n\t\tsuper.onStart();\n\t}\n\n\t@Override\n\tprotected void onStop() {\n\t\tsuper.onStop();\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tsuper.onCreateOptionsMenu(menu);\n\n\t\tmenu.add(Menu.NONE, R.id.word_dictionary_details_menu_search, Menu.NONE, R.string.word_dictionary_details_menu_search);\n\t\tmenu.add(Menu.NONE, R.id.word_dictionary_details_menu_search_next, Menu.NONE,\n\t\t\t\tR.string.word_dictionary_details_menu_search_next);\n\n\t\tMenuShorterHelper.onCreateOptionsMenu(menu);\n\n\t\tif (dictionaryEntry.isName() == false) {\n\t\t\tmenu.add(Menu.NONE, R.id.word_dictionary_details_menu_add_item_id_to_user_group, Menu.NONE, R.string.word_dictionary_details_menu_add_item_id_to_user_group);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tsuper.onOptionsItemSelected(item);\n\n\t\tif (item.getItemId() == R.id.word_dictionary_details_menu_search) {\n\n\t\t\tAlertDialog.Builder alert = new AlertDialog.Builder(this);\n\n\t\t\talert.setTitle(getString(R.string.word_dictionary_details_search_title));\n\n\t\t\tfinal EditText input = new EditText(this);\n\n\t\t\tinput.setSingleLine(true);\n\n\t\t\talert.setView(input);\n\n\t\t\talert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\n\t\t\t\t\tString userInputSearchText = input.getText().toString().toLowerCase(Locale.getDefault());\n\n\t\t\t\t\tsearchScreenItemList = new ArrayList<IScreenItem>();\n\t\t\t\t\tsearchScreenItemCurrentPos = 0;\n\n\t\t\t\t\tTitleItem lastTitleItem = null;\n\n\t\t\t\t\tfor (IScreenItem currentScreenItem : generatedDetails) {\n\n\t\t\t\t\t\tif (currentScreenItem instanceof TitleItem) {\n\t\t\t\t\t\t\tlastTitleItem = (TitleItem) currentScreenItem;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString currentScreenItemToString = currentScreenItem.toString();\n\n\t\t\t\t\t\tif (currentScreenItemToString.toLowerCase(Locale.getDefault()).indexOf(userInputSearchText) != -1) {\n\n\t\t\t\t\t\t\tif (lastTitleItem != null) {\n\n\t\t\t\t\t\t\t\tif (searchScreenItemList.contains(lastTitleItem) == false) {\n\t\t\t\t\t\t\t\t\tsearchScreenItemList.add(lastTitleItem);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tif (searchScreenItemList.contains(currentScreenItem) == false) {\n\t\t\t\t\t\t\t\t\tsearchScreenItemList.add(currentScreenItem);\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\tif (searchScreenItemList.size() == 0) {\n\t\t\t\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\t\t\t\tgetString(R.string.word_dictionary_details_search_no_result), Toast.LENGTH_SHORT)\n\t\t\t\t\t\t\t\t.show();\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal ScrollView scrollMainLayout = (ScrollView) findViewById(R.id.word_dictionary_details_main_layout_scroll);\n\n\t\t\t\t\tbackScreenPositionStack.push(scrollMainLayout.getScrollY());\n\n\t\t\t\t\tint counterPos = searchScreenItemList.get(searchScreenItemCurrentPos).getY();\n\t\t\t\t\tscrollMainLayout.scrollTo(0, counterPos - 3);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\talert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t// noop\n\t\t\t\t}\n\t\t\t});\n\n\t\t\talert.show();\n\n\t\t\treturn true;\n\n\t\t} else if (item.getItemId() == R.id.word_dictionary_details_menu_search_next) {\n\n\t\t\tif (searchScreenItemList == null || searchScreenItemList.size() == 0) {\n\t\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\t\tgetString(R.string.word_dictionary_details_search_no_result), Toast.LENGTH_SHORT).show();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tsearchScreenItemCurrentPos = searchScreenItemCurrentPos + 1;\n\n\t\t\tif (searchScreenItemCurrentPos >= searchScreenItemList.size()) {\n\t\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\t\tgetString(R.string.word_dictionary_details_search_no_more_result), Toast.LENGTH_SHORT).show();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfinal ScrollView scrollMainLayout = (ScrollView) findViewById(R.id.word_dictionary_details_main_layout_scroll);\n\n\t\t\tbackScreenPositionStack.push(scrollMainLayout.getScrollY());\n\n\t\t\tint counterPos = searchScreenItemList.get(searchScreenItemCurrentPos).getY();\n\t\t\tscrollMainLayout.scrollTo(0, counterPos - 3);\n\n\t\t\treturn true;\n\n\t\t} else if (item.getItemId() == R.id.word_dictionary_details_menu_add_item_id_to_user_group) {\n\n\t\t\tIntent intent = new Intent(getApplicationContext(), UserGroupActivity.class);\n\n\t\t\tintent.putExtra(\"itemToAdd\", dictionaryEntry);\n\n\t\t\tstartActivityForResult(intent, ADD_ITEM_ID_TO_USER_GROUP_ACTIVITY_REQUEST_CODE);\n\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn MenuShorterHelper.onOptionsItemSelected(item, getApplicationContext(), this);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\n\t\tif (backScreenPositionStack.isEmpty() == true) {\n\t\t\tsuper.onBackPressed();\n\n\t\t\treturn;\n\t\t}\n\n\t\tInteger backPostion = backScreenPositionStack.pop();\n\n\t\tfinal ScrollView scrollMainLayout = (ScrollView) findViewById(R.id.word_dictionary_details_main_layout_scroll);\n\n\t\tscrollMainLayout.scrollTo(0, backPostion);\n\t}\n\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\n\t\tsuper.onCreate(savedInstanceState);\n\n\t\tJapaneseAndroidLearnHelperApplication.getInstance().setContentViewAndTheme(this, R.layout.word_dictionary_details);\n\t\t\n\t\tJapaneseAndroidLearnHelperApplication.getInstance().logScreen(this, getString(R.string.logs_word_dictionary_details));\n\n\t\tdictionaryEntry = (DictionaryEntry) getIntent().getSerializableExtra(\"item\");\n\t\tforceDictionaryEntryType = (DictionaryEntryType) getIntent().getSerializableExtra(\n\t\t\t\t\"forceDictionaryEntryType\");\n\n\t\tfinal ScrollView scrollMainLayout = (ScrollView) findViewById(R.id.word_dictionary_details_main_layout_scroll);\n\t\tfinal LinearLayout detailsMainLayout = (LinearLayout) findViewById(R.id.word_dictionary_details_main_layout);\n\n\t\tgeneratedDetails = generateDetails(dictionaryEntry, forceDictionaryEntryType, scrollMainLayout);\n\n\t\tfillDetailsMainLayout(generatedDetails, detailsMainLayout);\n\n\t\tButton reportProblemButton = (Button) findViewById(R.id.word_dictionary_details_report_problem_button);\n\n\t\treportProblemButton.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View view) {\n\n\t\t\t\tStringBuffer detailsSb = new StringBuffer();\n\n\t\t\t\t/*\n\t\t\t\tfor (IScreenItem currentGeneratedDetails : generatedDetails) {\n\t\t\t\t\tdetailsSb.append(currentGeneratedDetails.toString()).append(\"\\n\\n\");\n\t\t\t\t}\n\t\t\t\t */\n\n\t\t\t\tdetailsSb.append(\"\\nId: \" + dictionaryEntry.getId()).append(\"\\n\\n\");\n\t\t\t\tdetailsSb.append(\"Kanji: \" + (dictionaryEntry.getKanji() != null ? dictionaryEntry.getKanji() : \"\")).append(\"\\n\\n\");\n\t\t\t\tdetailsSb.append(\"Kana: \" + dictionaryEntry.getKana()).append(\"\\n\\n\");\n\t\t\t\tdetailsSb.append(\"Romaji: \" + dictionaryEntry.getRomaji()).append(\"\\n\\n\");\n\t\t\t\tdetailsSb.append(\"Tłumaczenie: \\n\");\n\n\t\t\t\tList<String> translates = dictionaryEntry.getTranslates();\n\n\t\t\t\tif (translates != null) {\n\n\t\t\t\t\tfor (String currentTranslate : translates) {\n\t\t\t\t\t\tdetailsSb.append(\" \").append(currentTranslate).append(\"\\n\");\n\t\t\t\t\t}\n\n\t\t\t\t\tdetailsSb.append(\"\\n\");\n\t\t\t\t}\n\n\t\t\t\tdetailsSb.append(\"Informacje dodatkowe: \" + (dictionaryEntry.getInfo() != null ? dictionaryEntry.getInfo() : \"\")).append(\"\\n\\n\");\n\n\t\t\t\tString chooseEmailClientTitle = getString(R.string.choose_email_client);\n\n\t\t\t\tString mailSubject = getString(R.string.word_dictionary_details_report_problem_email_subject);\n\n\t\t\t\tString mailBody = getString(R.string.word_dictionary_details_report_problem_email_body,\n\t\t\t\t\t\tdetailsSb.toString());\n\n\t\t\t\tString versionName = \"\";\n\t\t\t\tint versionCode = 0;\n\n\t\t\t\ttry {\n\t\t\t\t\tPackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n\n\t\t\t\t\tversionName = packageInfo.versionName;\n\t\t\t\t\tversionCode = packageInfo.versionCode;\n\n\t\t\t\t} catch (NameNotFoundException e) {\n\t\t\t\t}\n\n\t\t\t\tIntent reportProblemIntent = ReportProblem.createReportProblemIntent(mailSubject, mailBody.toString(),\n\t\t\t\t\t\tversionName, versionCode);\n\n\t\t\t\tstartActivity(Intent.createChooser(reportProblemIntent, chooseEmailClientTitle));\n\t\t\t}\n\t\t});\n\n\t\tif (ttsConnector != null) {\n\t\t\tttsConnector.stop();\n\t\t}\n\n\t\tttsConnector = new TtsConnector(this, TtsLanguage.JAPANESE);\n\t}\n\n\t@Override\n\tprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\n\t\tif (requestCode == ADD_ITEM_ID_TO_USER_GROUP_ACTIVITY_REQUEST_CODE) {\n\n\t\t\tfinal ScrollView scrollMainLayout = (ScrollView) findViewById(R.id.word_dictionary_details_main_layout_scroll);\n\t\t\tfinal LinearLayout detailsMainLayout = (LinearLayout) findViewById(R.id.word_dictionary_details_main_layout);\n\n\t\t\tgeneratedDetails = generateDetails(dictionaryEntry, forceDictionaryEntryType, scrollMainLayout);\n\n\t\t\tfillDetailsMainLayout(generatedDetails, detailsMainLayout);\n\t\t}\n\t}\n\n\tprivate List<IScreenItem> generateDetails(final DictionaryEntry dictionaryEntry,\n\t\t\t\t\t\t\t\t\t\t\t DictionaryEntryType forceDictionaryEntryType, final ScrollView scrollMainLayout) {\n\n\t\tList<IScreenItem> report = new ArrayList<IScreenItem>();\n\n\t\tDictionaryManagerCommon dictionaryManager = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this);\n\n\t\tString prefixKana = dictionaryEntry.getPrefixKana();\n\t\tString prefixRomaji = dictionaryEntry.getPrefixRomaji();\n\n\t\tif (prefixKana != null && prefixKana.length() == 0) {\n\t\t\tprefixKana = null;\n\t\t}\n\n\t\t// pobranie slow w formacie dictionary 2/JMdict\n\t\tJMdict.Entry dictionaryEntry2 = null;\n\t\tDictionary2HelperCommon.KanjiKanaPair dictionaryEntry2KanjiKanaPair;\n\n\t\t// sprawdzenie, czy wystepuje slowo w formacie JMdict\n\t\tList<Attribute> jmdictEntryIdAttributeList = dictionaryEntry.getAttributeList().getAttributeList(AttributeType.JMDICT_ENTRY_ID);\n\n\t\tif (jmdictEntryIdAttributeList != null && jmdictEntryIdAttributeList.size() > 0) { // cos jest\n\n\t\t\t// pobieramy entry id\n\t\t\tInteger entryId = Integer.parseInt(jmdictEntryIdAttributeList.get(0).getAttributeValue().get(0));\n\n\t\t\ttry {\n\t\t\t\t// pobieramy z bazy danych\n\t\t\t\tdictionaryEntry2 = dictionaryManager.getDictionaryEntry2ById(entryId);\n\n\t\t\t} catch (DictionaryException e) { // wystapil blad, idziemy dalej\n\t\t\t\tToast.makeText(WordDictionaryDetails.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\t\t\t}\n\t\t}\n\n\t\t// pobieramy sens dla wybranej pary kanji i kana\n\t\tif (dictionaryEntry2 != null) {\n\n\t\t\tList<Dictionary2HelperCommon.KanjiKanaPair> kanjiKanaPairList = Dictionary2HelperCommon.getKanjiKanaPairListStatic(dictionaryEntry2);\n\n\t\t\t// szukamy konkretnego znaczenia dla naszego slowa\n\t\t\tdictionaryEntry2KanjiKanaPair = Dictionary2HelperCommon.findKanjiKanaPair(kanjiKanaPairList, dictionaryEntry);\n\n\t\t} else {\n\t\t\tdictionaryEntry2KanjiKanaPair = null;\n\t\t}\n\n\t\t// info dla slow typu name\n\t\tif (dictionaryEntry.isName() == true) {\n\n\t\t\tStringValue dictionaryEntryInfoName = new StringValue(getString(R.string.word_dictionary_details_name_info), 12.0f, 0);\n\n\t\t\treport.add(dictionaryEntryInfoName);\n\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t}\n\n\t\t// Kanji\t\t\n\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_kanji_label), 0));\n\n\t\tfinal StringBuffer kanjiSb = new StringBuffer();\n\n\t\tboolean addKanjiWrite = false;\n\n\t\tif (dictionaryEntry.isKanjiExists() == true) {\n\t\t\tif (prefixKana != null) {\n\t\t\t\tkanjiSb.append(\"(\").append(prefixKana).append(\") \");\n\t\t\t}\n\n\t\t\tkanjiSb.append(dictionaryEntry.getKanji());\n\n\t\t\taddKanjiWrite = true;\n\t\t} else {\n\t\t\tkanjiSb.append(\"-\");\n\n\t\t\taddKanjiWrite = false;\n\t\t}\n\n\t\t// kanji draw on click listener\n\t\tOnClickListener kanjiDrawOnClickListener = new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\n\t\t\t\tList<KanjivgEntry> strokePathsForWord = null;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tstrokePathsForWord = JapaneseAndroidLearnHelperApplication.getInstance()\n\t\t\t\t\t\t\t.getDictionaryManager(WordDictionaryDetails.this).getStrokePathsForWord(kanjiSb.toString());\n\n\t\t\t\t} catch (DictionaryException e) {\n\n\t\t\t\t\tToast.makeText(WordDictionaryDetails.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tStrokePathInfo strokePathInfo = new StrokePathInfo();\n\n\t\t\t\tstrokePathInfo.setStrokePaths(strokePathsForWord);\n\n\t\t\t\tIntent intent = new Intent(getApplicationContext(), SodActivity.class);\n\n\t\t\t\tintent.putExtra(\"strokePathsInfo\", strokePathInfo);\n\t\t\t\tintent.putExtra(\"annotateStrokes\", false);\n\n\t\t\t\tstartActivity(intent);\n\t\t\t}\n\t\t};\n\n\t\tList<String> kanaList = dictionaryEntry.getKanaList();\n\n\t\tboolean isAddFavouriteWordStar = false;\n\n\t\t// check furigana\n\t\tList<FuriganaEntry> furiganaEntries = null;\n\n\t\ttry {\n\t\t\tfuriganaEntries = dictionaryManager.getFurigana(dictionaryEntry);\n\n\t\t} catch (DictionaryException e) {\n\t\t\tToast.makeText(this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\t\t}\n\n\t\tif (furiganaEntries != null && furiganaEntries.size() > 0 && addKanjiWrite == true) {\n\n\t\t\treport.add(new StringValue(getString(R.string.word_dictionary_word_anim), 12.0f, 0));\n\n\t\t\tfor (FuriganaEntry currentFuriganaEntry : furiganaEntries) {\n\n\t\t\t\tTableLayout furiganaTableLayout = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent,\n\t\t\t\t\t\ttrue, null);\n\n\t\t\t\tfinal int maxPartsInLine = 7;\n\n\t\t\t\tList<String> furiganaKanaParts = currentFuriganaEntry.getKanaPart();\n\t\t\t\tList<String> furiganaKanjiParts = currentFuriganaEntry.getKanjiPart();\n\n\t\t\t\tint maxParts = furiganaKanaParts.size() / maxPartsInLine\n\t\t\t\t\t\t+ (furiganaKanaParts.size() % maxPartsInLine > 0 ? 1 : 0);\n\n\t\t\t\tfor (int currentPart = 0; currentPart < maxParts; ++currentPart) {\n\n\t\t\t\t\tTableRow readingRow = new TableRow();\n\n\t\t\t\t\tStringValue spacer = new StringValue(\"\", 15.0f, 0);\n\t\t\t\t\tspacer.setGravity(Gravity.CENTER);\n\t\t\t\t\tspacer.setNullMargins(true);\n\n\t\t\t\t\treadingRow.addScreenItem(spacer);\n\n\t\t\t\t\tfor (int furiganaKanaPartsIdx = currentPart * maxPartsInLine; furiganaKanaPartsIdx < furiganaKanaParts\n\t\t\t\t\t\t\t.size() && furiganaKanaPartsIdx < (currentPart + 1) * maxPartsInLine; ++furiganaKanaPartsIdx) {\n\n\t\t\t\t\t\tStringValue currentKanaPartStringValue = new StringValue(\n\t\t\t\t\t\t\t\tfuriganaKanaParts.get(furiganaKanaPartsIdx), 15.0f, 0);\n\n\t\t\t\t\t\tcurrentKanaPartStringValue.setGravity(Gravity.CENTER);\n\t\t\t\t\t\tcurrentKanaPartStringValue.setNullMargins(true);\n\n\t\t\t\t\t\tcurrentKanaPartStringValue.setOnClickListener(kanjiDrawOnClickListener);\n\n\t\t\t\t\t\treadingRow.addScreenItem(currentKanaPartStringValue);\n\t\t\t\t\t}\n\n\t\t\t\t\tfuriganaTableLayout.addTableRow(readingRow);\n\n\t\t\t\t\tTableRow kanjiRow = new TableRow();\n\n\t\t\t\t\tStringValue spacer2 = new StringValue(\" \", 25.0f, 0);\n\t\t\t\t\tspacer2.setGravity(Gravity.CENTER);\n\t\t\t\t\tspacer2.setNullMargins(true);\n\n\t\t\t\t\tkanjiRow.addScreenItem(spacer2);\n\n\t\t\t\t\tfor (int furiganaKanjiPartsIdx = currentPart * maxPartsInLine; furiganaKanjiPartsIdx < furiganaKanjiParts\n\t\t\t\t\t\t\t.size() && furiganaKanjiPartsIdx < (currentPart + 1) * maxPartsInLine; ++furiganaKanjiPartsIdx) {\n\t\t\t\t\t\tStringValue currentKanjiPartStringValue = new StringValue(\n\t\t\t\t\t\t\t\tfuriganaKanjiParts.get(furiganaKanjiPartsIdx), 35.0f, 0);\n\n\t\t\t\t\t\tcurrentKanjiPartStringValue.setGravity(Gravity.CENTER);\n\t\t\t\t\t\tcurrentKanjiPartStringValue.setNullMargins(true);\n\n\t\t\t\t\t\tcurrentKanjiPartStringValue.setOnClickListener(kanjiDrawOnClickListener);\n\n\t\t\t\t\t\tkanjiRow.addScreenItem(currentKanjiPartStringValue);\n\t\t\t\t\t}\n\n\t\t\t\t\tfuriganaTableLayout.addTableRow(kanjiRow);\n\t\t\t\t}\n\n\t\t\t\treport.add(furiganaTableLayout);\n\n\t\t\t\tTableLayout actionButtons = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, null);\n\t\t\t\tTableRow actionTableRow = new TableRow();\n\n\t\t\t\t// speak image\n\t\t\t\tImage speakImage = new Image(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getListenIconId()), 0);\n\t\t\t\tspeakImage.setOnClickListener(new TTSJapaneseSpeak(null, currentFuriganaEntry.getKanaPartJoined()));\n\t\t\t\tactionTableRow.addScreenItem(speakImage);\n\n\t\t\t\t// copy kanji\n\t\t\t\tImage clipboardKanji = new Image(getResources().getDrawable(R.drawable.clipboard_kanji), 0);\n\t\t\t\tclipboardKanji.setOnClickListener(new CopyToClipboard(dictionaryEntry.getKanji()));\n\t\t\t\tactionTableRow.addScreenItem(clipboardKanji);\n\n\t\t\t\t// add to favourite word list\n\t\t\t\tif (isAddFavouriteWordStar == false && dictionaryEntry.isName() == false) {\n\n\t\t\t\t\tisAddFavouriteWordStar = true;\n\t\t\t\t\tactionTableRow.addScreenItem(createFavouriteWordStar(dictionaryManager, dictionaryEntry));\n\t\t\t\t}\n\n\t\t\t\t//\n\n\t\t\t\tactionButtons.addTableRow(actionTableRow);\n\t\t\t\treport.add(actionButtons);\n\t\t\t}\n\t\t} else {\n\t\t\tif (addKanjiWrite == true) {\n\t\t\t\tStringValue kanjiStringValue = new StringValue(kanjiSb.toString(), 35.0f, 0);\n\n\t\t\t\treport.add(new StringValue(getString(R.string.word_dictionary_word_anim), 12.0f, 0));\n\n\t\t\t\tkanjiStringValue.setOnClickListener(kanjiDrawOnClickListener);\n\n\t\t\t\treport.add(kanjiStringValue);\n\n\t\t\t\tTableLayout actionButtons = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, null);\n\t\t\t\tTableRow actionTableRow = new TableRow();\n\n\t\t\t\tImage speakImage = new Image(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getListenIconId()), 0);\n\n\t\t\t\tif (kanaList != null && kanaList.size() > 0) {\n\t\t\t\t\tspeakImage.setOnClickListener(new TTSJapaneseSpeak(null, kanaList.get(0)));\n\t\t\t\t} else {\n\t\t\t\t\tspeakImage.setOnClickListener(new TTSJapaneseSpeak(null, dictionaryEntry.getKanji()));\n\t\t\t\t}\n\n\t\t\t\tactionTableRow.addScreenItem(speakImage);\n\n\t\t\t\t// clipboard kanji\n\t\t\t\tImage clipboardKanji = new Image(getResources().getDrawable(R.drawable.clipboard_kanji), 0);\n\t\t\t\tclipboardKanji.setOnClickListener(new CopyToClipboard(dictionaryEntry.getKanji()));\n\t\t\t\tactionTableRow.addScreenItem(clipboardKanji);\n\n\t\t\t\t// add to favourite word list\n\t\t\t\tif (isAddFavouriteWordStar == false && dictionaryEntry.isName() == false) {\n\n\t\t\t\t\tisAddFavouriteWordStar = true;\n\t\t\t\t\tactionTableRow.addScreenItem(createFavouriteWordStar(dictionaryManager, dictionaryEntry));\n\t\t\t\t}\n\n\t\t\t\t//\n\n\t\t\t\tactionButtons.addTableRow(actionTableRow);\n\t\t\t\treport.add(actionButtons);\n\t\t\t}\n\t\t}\n\n\t\t// informacje dodatkowe do kanji\n\t\tif (addKanjiWrite == true && dictionaryEntry2KanjiKanaPair != null && dictionaryEntry2KanjiKanaPair.getKanjiInfo() != null) {\n\n\t\t\tList<KanjiAdditionalInfoEnum> kanjiAdditionalInfoList = dictionaryEntry2KanjiKanaPair.getKanjiInfo().getKanjiAdditionalInfoList();\n\n\t\t\tList<String> kanjiAdditionalInfoListString = Dictionary2HelperCommon.translateToPolishKanjiAdditionalInfoEnum(kanjiAdditionalInfoList);\n\n\t\t\tif (kanjiAdditionalInfoList != null && kanjiAdditionalInfoList.size() > 0) {\n\t\t\t\treport.add(new StringValue(pl.idedyk.japanese.dictionary.api.dictionary.Utils.convertListToString(kanjiAdditionalInfoListString, \"; \"), 13.0f, 0));\n\t\t\t}\n\t\t}\n\n\t\t// Reading\n\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_reading_label), 0));\n\t\treport.add(new StringValue(getString(R.string.word_dictionary_word_anim), 12.0f, 0));\n\n\t\tList<String> romajiList = dictionaryEntry.getRomajiList();\n\n\t\tfor (int idx = 0; idx < kanaList.size(); ++idx) {\n\n\t\t\tfinal StringBuffer sb = new StringBuffer();\n\n\t\t\tif (prefixKana != null) {\n\t\t\t\tsb.append(\"(\").append(prefixKana).append(\") \");\n\t\t\t}\n\n\t\t\tsb.append(kanaList.get(idx)).append(\" - \");\n\n\t\t\tif (prefixRomaji != null) {\n\t\t\t\tsb.append(\"(\").append(prefixRomaji).append(\") \");\n\t\t\t}\n\n\t\t\tsb.append(romajiList.get(idx));\n\n\t\t\tStringValue readingStringValue = new StringValue(sb.toString(), 20.0f, 0);\n\n\t\t\treadingStringValue.setOnClickListener(new OnClickListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\n\t\t\t\t\tList<KanjivgEntry> strokePathsForWord = null;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstrokePathsForWord = JapaneseAndroidLearnHelperApplication.getInstance()\n\t\t\t\t\t\t\t\t.getDictionaryManager(WordDictionaryDetails.this).getStrokePathsForWord(sb.toString());\n\n\t\t\t\t\t} catch (DictionaryException e) {\n\n\t\t\t\t\t\tToast.makeText(WordDictionaryDetails.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tStrokePathInfo strokePathInfo = new StrokePathInfo();\n\n\t\t\t\t\tstrokePathInfo.setStrokePaths(strokePathsForWord);\n\n\t\t\t\t\tIntent intent = new Intent(getApplicationContext(), SodActivity.class);\n\n\t\t\t\t\tintent.putExtra(\"strokePathsInfo\", strokePathInfo);\n\t\t\t\t\tintent.putExtra(\"annotateStrokes\", false);\n\n\t\t\t\t\tstartActivity(intent);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treport.add(readingStringValue);\n\n\t\t\tTableLayout actionButtons = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, null);\n\t\t\tTableRow actionTableRow = new TableRow();\n\n\t\t\t// speak image\t\t\n\t\t\tImage speakImage = new Image(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getListenIconId()), 0);\n\t\t\tspeakImage.setOnClickListener(new TTSJapaneseSpeak(null, kanaList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(speakImage);\n\n\t\t\t// clipboard kana\n\t\t\tImage clipboardKana = new Image(getResources().getDrawable(R.drawable.clipboard_kana), 0);\n\t\t\tclipboardKana.setOnClickListener(new CopyToClipboard(kanaList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(clipboardKana);\n\n\t\t\t// clipboard romaji\n\t\t\tImage clipboardRomaji = new Image(getResources().getDrawable(R.drawable.clipboard_romaji), 0);\n\t\t\tclipboardRomaji.setOnClickListener(new CopyToClipboard(romajiList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(clipboardRomaji);\n\n\t\t\t// add to favourite word list\n\t\t\tif (isAddFavouriteWordStar == false && dictionaryEntry.isName() == false) {\n\n\t\t\t\tisAddFavouriteWordStar = true;\n\t\t\t\tactionTableRow.addScreenItem(createFavouriteWordStar(dictionaryManager, dictionaryEntry));\n\n\t\t\t}\n\n\t\t\tactionButtons.addTableRow(actionTableRow);\n\n\t\t\treport.add(actionButtons);\n\t\t}\n\n\t\t// informacje dodatkowe do czytania\n\t\tif (dictionaryEntry2KanjiKanaPair != null && dictionaryEntry2KanjiKanaPair.getReadingInfo() != null) {\n\n\t\t\tList<ReadingAdditionalInfoEnum> readingAdditionalInfoList = dictionaryEntry2KanjiKanaPair.getReadingInfo().getReadingAdditionalInfoList();\n\n\t\t\tList<String> readingAdditionalInfoListString = Dictionary2HelperCommon.translateToPolishReadingAdditionalInfoEnum(readingAdditionalInfoList);\n\n\t\t\tif (readingAdditionalInfoList != null && readingAdditionalInfoList.size() > 0) {\n\t\t\t\treport.add(new StringValue(pl.idedyk.japanese.dictionary.api.dictionary.Utils.convertListToString(readingAdditionalInfoListString, \"; \"), 13.0f, 0));\n\t\t\t}\n\t\t}\n\n\t\t// Translate\n\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_translate_label), 0));\n\n\t\tif (dictionaryEntry2KanjiKanaPair == null) { // generowanie po staremu\n\n\t\t\tList<String> translates = dictionaryEntry.getTranslates();\n\n\t\t\tfor (int idx = 0; idx < translates.size(); ++idx) {\n\t\t\t\treport.add(new StringValue(translates.get(idx), 20.0f, 0));\n\t\t\t}\n\n\t\t} else { // generowanie z danych zawartych w dictionaryEntry2\n\n\t\t\t// mamy znaczenia\n\t\t\tfor (int senseIdx = 0; senseIdx < dictionaryEntry2KanjiKanaPair.getSenseList().size(); ++senseIdx) {\n\n\t\t\t\tSense sense = dictionaryEntry2KanjiKanaPair.getSenseList().get(senseIdx);\n\n\t\t\t\tList<Gloss> glossList = sense.getGlossList();\n\t\t\t\tList<SenseAdditionalInfo> senseAdditionalInfoList = sense.getAdditionalInfoList();\n\t\t\t\tList<LanguageSource> senseLanguageSourceList = sense.getLanguageSourceList();\n\t\t\t\tList<FieldEnum> senseFieldList = sense.getFieldList();\n\t\t\t\tList<MiscEnum> senseMiscList = sense.getMiscList();\n\t\t\t\tList<DialectEnum> senseDialectList = sense.getDialectList();\n\t\t\t\tList<PartOfSpeechEnum> partOfSpeechList = sense.getPartOfSpeechList();\n\n\t\t\t\t// numer znaczenia\n\t\t\t\treport.add(new StringValue(\"\" + (senseIdx + 1), 20.0f, 0));\n\n\t\t\t\t// pobieramy polskie tlumaczenia\n\t\t\t\tList<Gloss> glossPolList = new ArrayList<>();\n\n\t\t\t\tfor (Gloss currentGloss : glossList) {\n\n\t\t\t\t\tif (currentGloss.getLang().equals(\"pol\") == true) {\n\t\t\t\t\t\tglossPolList.add(currentGloss);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// i informacje dodatkowe\n\t\t\t\tSenseAdditionalInfo senseAdditionalPol = null;\n\n\t\t\t\tfor (SenseAdditionalInfo currentSenseAdditionalInfo : senseAdditionalInfoList) {\n\n\t\t\t\t\tif (currentSenseAdditionalInfo.getLang().equals(\"pol\") == true) {\n\n\t\t\t\t\t\tsenseAdditionalPol = currentSenseAdditionalInfo;\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// czesci mowy\n\t\t\t\tif (partOfSpeechList.size() > 0) {\n\n\t\t\t\t\tList<String> translateToPolishPartOfSpeechEnum = Dictionary2HelperCommon.translateToPolishPartOfSpeechEnum(partOfSpeechList);\n\n\t\t\t\t\t//\n\n\t\t\t\t\treport.add(new StringValue(pl.idedyk.japanese.dictionary.api.dictionary.Utils.convertListToString(translateToPolishPartOfSpeechEnum, \"; \"), 13.0f, 0));\n\t\t\t\t}\n\n\t\t\t\t// znaczenie\n\t\t\t\tfor (Gloss currentGlossPol : glossPolList) {\n\n\t\t\t\t\tString currentGlossPolReportValue = currentGlossPol.getValue();\n\n\t\t\t\t\t// sprawdzenie, czy wystepuje dodatkowy typ znaczenia\n\t\t\t\t\tif (currentGlossPol.getGType() != null) {\n\t\t\t\t\t\tcurrentGlossPolReportValue += \" (\" + Dictionary2HelperCommon.translateToPolishGlossType(currentGlossPol.getGType()) + \")\";\n\t\t\t\t\t}\n\n\t\t\t\t\treport.add(new StringValue(currentGlossPolReportValue, 20.0f, 0));\n\t\t\t\t}\n\n\t\t\t\t// informacje dodatkowe\n\t\t\t\tList<String> additionalInfoToAddList = new ArrayList<>();\n\n\t\t\t\t// dziedzina\n\t\t\t\tif (senseFieldList.size() > 0) {\n\t\t\t\t\tadditionalInfoToAddList.addAll(Dictionary2HelperCommon.translateToPolishFieldEnumList(senseFieldList));\n\t\t\t\t}\n\n\t\t\t\t// rozne informacje\n\t\t\t\tif (senseMiscList.size() > 0) {\n\t\t\t\t\tadditionalInfoToAddList.addAll(Dictionary2HelperCommon.translateToPolishMiscEnumList(senseMiscList));\n\t\t\t\t}\n\n\t\t\t\t// dialekt\n\t\t\t\tif (senseDialectList.size() > 0) {\n\t\t\t\t\tadditionalInfoToAddList.addAll(Dictionary2HelperCommon.translateToPolishDialectEnumList(senseDialectList));\n\t\t\t\t}\n\n\t\t\t\tif (senseAdditionalPol != null) { // czy informacje dodatkowe istnieja\n\n\t\t\t\t\tString senseAdditionalPolOptionalValue = senseAdditionalPol.getValue();\n\n\t\t\t\t\tadditionalInfoToAddList.add(senseAdditionalPolOptionalValue);\n\t\t\t\t}\n\n\t\t\t\t// czy sa informacje o zagranicznym pochodzeniu slow\n\t\t\t\tif (senseLanguageSourceList != null && senseLanguageSourceList.size() > 0) {\n\n\t\t\t\t\tfor (LanguageSource languageSource : senseLanguageSourceList) {\n\n\t\t\t\t\t\tString languageCodeInPolish = Dictionary2HelperCommon.translateToPolishLanguageCode(languageSource.getLang());\n\t\t\t\t\t\tString languageValue = languageSource.getValue();\n\t\t\t\t\t\tString languageLsWasei = Dictionary2HelperCommon.translateToPolishLanguageSourceLsWaseiEnum(languageSource.getLsWasei());\n\n\t\t\t\t\t\tif (languageValue != null && languageValue.trim().equals(\"\") == false) {\n\t\t\t\t\t\t\tadditionalInfoToAddList.add(languageCodeInPolish + \": \" + languageValue);\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tadditionalInfoToAddList.add(Dictionary2HelperCommon.translateToPolishLanguageCodeWithoutValue(languageSource.getLang()));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (languageLsWasei != null) {\n\t\t\t\t\t\t\tadditionalInfoToAddList.add(languageLsWasei);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (additionalInfoToAddList.size() > 0) {\n\t\t\t\t\treport.add(new StringValue(pl.idedyk.japanese.dictionary.api.dictionary.Utils.convertListToString(additionalInfoToAddList, \"; \"), 13.0f, 0));\n\t\t\t\t}\n\n\t\t\t\t// przerwa\n\t\t\t\treport.add(new StringValue(\"\", 10.0f, 0));\n\t\t\t}\n\t\t}\n\n\t\t// Additional info\n\t\tif (dictionaryEntry2KanjiKanaPair == null) { // generowanie tylko dla slownika w starym formacie, w nowym formacie informacje te znajda sie w sekcji znaczen\n\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_additional_info_label), 0));\n\n\t\t\tif (isSmTsukiNiKawatteOshiokiYo(kanjiSb.toString()) == true) {\n\t\t\t\treport.add(createSpecialAAText(R.string.sm_tsuki_ni_kawatte_oshioki_yo));\n\t\t\t} else if (isButaMoOdateryaKiNiNoboru(kanjiSb.toString()) == true) {\n\t\t\t\treport.add(createSpecialAAText(R.string.buta_mo_odaterya_ki_ni_noboru));\n\t\t\t} else {\n\t\t\t\tString info = dictionaryEntry.getInfo();\n\n\t\t\t\tif (info != null && info.length() > 0) {\n\t\t\t\t\treport.add(new StringValue(info, 20.0f, 0));\n\t\t\t\t} else {\n\t\t\t\t\treport.add(new StringValue(\"-\", 20.0f, 0));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Word type\n\t\tint addableDictionaryEntryTypeInfoCounter = 0;\n\n\t\tList<DictionaryEntryType> dictionaryEntryTypeList = dictionaryEntry.getDictionaryEntryTypeList();\n\n\t\tif (dictionaryEntryTypeList != null) {\n\t\t\tfor (DictionaryEntryType currentDictionaryEntryType : dictionaryEntryTypeList) {\n\n\t\t\t\tboolean addableDictionaryEntryTypeInfo = DictionaryEntryType\n\t\t\t\t\t\t.isAddableDictionaryEntryTypeInfo(currentDictionaryEntryType);\n\n\t\t\t\tif (addableDictionaryEntryTypeInfo == true) {\n\t\t\t\t\taddableDictionaryEntryTypeInfoCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (addableDictionaryEntryTypeInfoCounter > 0) {\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_part_of_speech), 0));\n\n\t\t\tif (addableDictionaryEntryTypeInfoCounter > 1) {\n\t\t\t\treport.add(new StringValue(getString(R.string.word_dictionary_details_part_of_speech_press), 12.0f, 0));\n\t\t\t}\n\n\t\t\tfor (final DictionaryEntryType currentDictionaryEntryType : dictionaryEntryTypeList) {\n\n\t\t\t\tStringValue currentDictionaryEntryTypeStringValue = new StringValue(\n\t\t\t\t\t\tcurrentDictionaryEntryType.getName(), 20.0f, 0);\n\n\t\t\t\tif (addableDictionaryEntryTypeInfoCounter > 1) {\n\t\t\t\t\tcurrentDictionaryEntryTypeStringValue.setOnClickListener(new OnClickListener() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\t\t\tIntent intent = new Intent(getApplicationContext(), WordDictionaryDetails.class);\n\n\t\t\t\t\t\t\tintent.putExtra(\"item\", dictionaryEntry);\n\t\t\t\t\t\t\tintent.putExtra(\"forceDictionaryEntryType\", currentDictionaryEntryType);\n\n\t\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treport.add(currentDictionaryEntryTypeStringValue);\n\t\t\t}\n\t\t}\n\n\t\tList<Attribute> attributeList = dictionaryEntry.getAttributeList().getAttributeList();\n\n\t\tif (attributeList != null && attributeList.size() > 0) {\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_attributes), 0));\n\n\t\t\tfor (Attribute currentAttribute : attributeList) {\n\n\t\t\t\tAttributeType attributeType = currentAttribute.getAttributeType();\n\n\t\t\t\tif (attributeType.isShow() == true) {\n\t\t\t\t\treport.add(new StringValue(attributeType.getName(), 15.0f, 0));\n\t\t\t\t}\n\n\t\t\t\tif (\tattributeType == AttributeType.VERB_TRANSITIVITY_PAIR ||\n\t\t\t\t\t\tattributeType == AttributeType.VERB_INTRANSITIVITY_PAIR ||\n\t\t\t\t\t\tattributeType == AttributeType.ALTERNATIVE ||\n\t\t\t\t\t\tattributeType == AttributeType.RELATED ||\n\t\t\t\t\t\tattributeType == AttributeType.ANTONYM) {\n\n\t\t\t\t\tInteger referenceWordId = Integer.parseInt(currentAttribute.getAttributeValue().get(0));\n\n\t\t\t\t\tDictionaryEntry referenceDictionaryEntryNonFinal = null;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\treferenceDictionaryEntryNonFinal = JapaneseAndroidLearnHelperApplication\n\t\t\t\t\t\t\t\t.getInstance().getDictionaryManager(WordDictionaryDetails.this)\n\t\t\t\t\t\t\t\t.getDictionaryEntryById(referenceWordId);\n\n\t\t\t\t\t} catch (DictionaryException e) {\n\n\t\t\t\t\t\tToast.makeText(WordDictionaryDetails.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\n\t\t\t\t\t\treferenceDictionaryEntryNonFinal = null;\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal DictionaryEntry referenceDictionaryEntry = referenceDictionaryEntryNonFinal;\n\n\t\t\t\t\tif (referenceDictionaryEntry != null) {\n\n\t\t\t\t\t\tStringValue attributeTypeStringValue = new StringValue(attributeType.getName(), 15.0f, 0);\n\n\t\t\t\t\t\tOnClickListener goToReferenceDictionaryEntryDetails = new OnClickListener() {\n\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tpublic void onClick(View v) {\n\n\t\t\t\t\t\t\t\tIntent intent = new Intent(getApplicationContext(), WordDictionaryDetails.class);\n\n\t\t\t\t\t\t\t\tintent.putExtra(\"item\", referenceDictionaryEntry);\n\n\t\t\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tattributeTypeStringValue.setOnClickListener(goToReferenceDictionaryEntryDetails);\n\n\t\t\t\t\t\treport.add(attributeTypeStringValue);\n\n\t\t\t\t\t\tString kana = referenceDictionaryEntry.getKana();\n\t\t\t\t\t\tString romaji = referenceDictionaryEntry.getRomaji();\n\t\t\t\t\t\t\n\t\t\t\t\t\tStringBuffer referenceDictionaryEntrySb = new StringBuffer();\n\n\t\t\t\t\t\tif (referenceDictionaryEntry.isKanjiExists() == true) {\n\t\t\t\t\t\t\treferenceDictionaryEntrySb.append(referenceDictionaryEntry.getKanji()).append(\", \");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treferenceDictionaryEntrySb.append(kana).append(\", \");\n\t\t\t\t\t\treferenceDictionaryEntrySb.append(romaji);\n\n\t\t\t\t\t\tStringValue referenceDictionaryEntryKanaRomajiStringValue = new StringValue(\n\t\t\t\t\t\t\t\treferenceDictionaryEntrySb.toString(), 15.0f, 1);\n\n\t\t\t\t\t\treferenceDictionaryEntryKanaRomajiStringValue\n\t\t\t\t\t\t\t\t.setOnClickListener(goToReferenceDictionaryEntryDetails);\n\n\t\t\t\t\t\treport.add(referenceDictionaryEntryKanaRomajiStringValue);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// dictionary groups\n\t\tList<GroupEnum> groups = dictionaryEntry.getGroups();\n\n\t\tif (groups != null && groups.size() > 0) {\n\t\t\t\n\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_dictionary_groups), 0));\n\n\t\t\tfor (int groupsIdx = 0; groupsIdx < groups.size(); ++groupsIdx) {\n\t\t\t\treport.add(new StringValue(String.valueOf(groups.get(groupsIdx).getValue()), 20.0f, 0));\n\t\t\t}\n\t\t}\n\n\t\t// user groups\n\t\tif (dictionaryEntry.isName() == false) { // tylko dla normalnych slowek\n\n\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_user_groups), 0));\n\n\t\t\tfinal DataManager dataManager = dictionaryManager.getDataManager();\n\n\t\t\tList<UserGroupEntity> userGroupEntityListForItemId = dataManager.getUserGroupEntityListForItemId(UserGroupEntity.Type.USER_GROUP, UserGroupItemEntity.Type.DICTIONARY_ENTRY, dictionaryEntry.getId());\n\n\t\t\tfor (UserGroupEntity currentUserGroupEntity : userGroupEntityListForItemId) {\n\n\t\t\t\tTableRow userGroupTableRow = new TableRow();\n\n\t\t\t\tOnClickListener deleteItemIdFromUserGroupOnClickListener = createDeleteItemIdFromUserGroupOnClickListener(dataManager, dictionaryEntry, currentUserGroupEntity, userGroupTableRow);\n\n\t\t\t\tStringValue userGroupNameStringValue = new StringValue(currentUserGroupEntity.getName(), 15.0f, 0);\n\t\t\t\tImage userGroupNameDeleteImage = new Image(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getDeleteIconId()), 0);\n\n\t\t\t\tuserGroupNameStringValue.setOnClickListener(deleteItemIdFromUserGroupOnClickListener);\n\t\t\t\tuserGroupNameDeleteImage.setOnClickListener(deleteItemIdFromUserGroupOnClickListener);\n\n\t\t\t\tuserGroupTableRow.addScreenItem(userGroupNameStringValue);\n\t\t\t\tuserGroupTableRow.addScreenItem(userGroupNameDeleteImage);\n\n\t\t\t\treport.add(userGroupTableRow);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t// dictionary position\n\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_dictionary_position), 0));\n\n\t\treport.add(new StringValue(String.valueOf(dictionaryEntry.getId()), 20.0f, 0));\n\t\t*/\n\n\t\t// known kanji\n\t\tList<KanjiEntry> knownKanji = null;\n\n\t\tif (dictionaryEntry.isKanjiExists() == true) {\n\n\t\t\ttry {\n\t\t\t\tknownKanji = JapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this)\n\t\t\t\t\t\t.findKnownKanji(dictionaryEntry.getKanji());\n\n\t\t\t} catch (DictionaryException e) {\n\t\t\t\tToast.makeText(WordDictionaryDetails.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\t\t\t}\n\t\t}\n\n\t\tif (knownKanji != null && knownKanji.size() > 0) {\n\n\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_known_kanji), 0));\n\t\t\treport.add(new StringValue(getString(R.string.word_dictionary_known_kanji_info), 12.0f, 0));\n\n\t\t\tfor (int knownKanjiIdx = 0; knownKanjiIdx < knownKanji.size(); ++knownKanjiIdx) {\n\n\t\t\t\tfinal KanjiEntry kanjiEntry = knownKanji.get(knownKanjiIdx);\n\n\t\t\t\tOnClickListener kanjiOnClickListener = new OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(View v) {\n\n\t\t\t\t\t\t// show kanji details\n\n\t\t\t\t\t\tIntent intent = new Intent(getApplicationContext(), KanjiDetails.class);\n\n\t\t\t\t\t\tintent.putExtra(\"item\", kanjiEntry);\n\n\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tStringValue knownKanjiStringValue = new StringValue(kanjiEntry.getKanji(), 16.0f, 1);\n\t\t\t\tStringValue polishTranslateStringValue = new StringValue(kanjiEntry.getPolishTranslates().toString(),\n\t\t\t\t\t\t16.0f, 1);\n\n\t\t\t\tknownKanjiStringValue.setOnClickListener(kanjiOnClickListener);\n\t\t\t\tpolishTranslateStringValue.setOnClickListener(kanjiOnClickListener);\n\n\t\t\t\treport.add(knownKanjiStringValue);\n\t\t\t\treport.add(polishTranslateStringValue);\n\n\t\t\t\tif (knownKanjiIdx != knownKanji.size() - 1) {\n\t\t\t\t\treport.add(new StringValue(\"\", 10.0f, 1));\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\t// index\n\t\tint indexStartPos = report.size();\n\n\t\tMap<GrammaFormConjugateResultType, GrammaFormConjugateResult> grammaCache = new HashMap<GrammaFormConjugateResultType, GrammaFormConjugateResult>();\n\n\t\t// Conjugater\n\t\tList<GrammaFormConjugateGroupTypeElements> grammaFormConjugateGroupTypeElementsList = GrammaConjugaterManager\n\t\t\t\t.getGrammaConjufateResult(JapaneseAndroidLearnHelperApplication.getInstance()\n\t\t\t\t\t\t.getDictionaryManager(this).getKeigoHelper(), dictionaryEntry, grammaCache,\n\t\t\t\t\t\tforceDictionaryEntryType, false);\n\n\t\tif (grammaFormConjugateGroupTypeElementsList != null) {\n\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_conjugater_label), 0));\n\n\t\t\tfor (GrammaFormConjugateGroupTypeElements currentGrammaFormConjugateGroupTypeElements : grammaFormConjugateGroupTypeElementsList) {\n\n\t\t\t\tif (currentGrammaFormConjugateGroupTypeElements.getGrammaFormConjugateGroupType().isShow() == false) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\treport.add(new TitleItem(currentGrammaFormConjugateGroupTypeElements.getGrammaFormConjugateGroupType()\n\t\t\t\t\t\t.getName(), 1));\n\n\t\t\t\tList<GrammaFormConjugateResult> grammaFormConjugateResults = currentGrammaFormConjugateGroupTypeElements\n\t\t\t\t\t\t.getGrammaFormConjugateResults();\n\n\t\t\t\tfor (GrammaFormConjugateResult currentGrammaFormConjugateResult : grammaFormConjugateResults) {\n\n\t\t\t\t\tif (currentGrammaFormConjugateResult.getResultType().isShow() == true) {\n\t\t\t\t\t\treport.add(new TitleItem(currentGrammaFormConjugateResult.getResultType().getName(), 2));\n\t\t\t\t\t}\n\n\t\t\t\t\taddGrammaFormConjugateResult(report, currentGrammaFormConjugateResult);\n\t\t\t\t}\n\n\t\t\t\treport.add(new StringValue(\"\", 15.0f, 1));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Sentence example\t\t\n\t\tList<String> exampleSentenceGroupIdsList = dictionaryEntry.getExampleSentenceGroupIdsList();\n\t\t\n\t\tList<GroupWithTatoebaSentenceList> tatoebaSentenceGroupList = null;\n\t\t\n\t\tif (exampleSentenceGroupIdsList != null && exampleSentenceGroupIdsList.size() != 0) {\n\t\t\t\n\t\t\ttatoebaSentenceGroupList = new ArrayList<GroupWithTatoebaSentenceList>();\n\t\t\t\n\t \tfor (String currentExampleSentenceGroupId : exampleSentenceGroupIdsList) {\n\n\t\t\t\tGroupWithTatoebaSentenceList tatoebaSentenceGroup = null;\n\t \t\ttry {\n\t\t\t\t\ttatoebaSentenceGroup = JapaneseAndroidLearnHelperApplication.getInstance()\n\t\t\t\t\t\t\t.getDictionaryManager(this).getTatoebaSentenceGroup(currentExampleSentenceGroupId);\n\n\t\t\t\t} catch (DictionaryException e) {\n\t\t\t\t\tToast.makeText(WordDictionaryDetails.this, getString(R.string.dictionary_exception_common_error_message, e.getMessage()), Toast.LENGTH_LONG).show();\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t \t\tif (tatoebaSentenceGroup != null) { \t\t\t\n\t \t\t\ttatoebaSentenceGroupList.add(tatoebaSentenceGroup);\n\t \t\t}\n\t\t\t}\n\t \t\n\t \tif (tatoebaSentenceGroupList.size() > 0) {\n\t \t\t\n\t\t\t\tif (grammaFormConjugateGroupTypeElementsList == null) {\n\t\t\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t\t\t}\n\t \t\t\n\t \t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_sentence_example_label), 0));\n\t \t\t\n\t \t\tfor (int tatoebaSentenceGroupListIdx = 0; tatoebaSentenceGroupListIdx < tatoebaSentenceGroupList.size(); ++tatoebaSentenceGroupListIdx) {\n\t \t\t\t\n\t \t\t\tGroupWithTatoebaSentenceList currentTatoebeSentenceGroup = tatoebaSentenceGroupList.get(tatoebaSentenceGroupListIdx);\n\t \t\t\t\n\t \t\t\tList<TatoebaSentence> tatoebaSentenceList = currentTatoebeSentenceGroup.getTatoebaSentenceList();\n\t \t\t\t\t\t\t\n\t \t\t\tList<TatoebaSentence> polishTatoebaSentenceList = new ArrayList<TatoebaSentence>();\n\t \t\t\tList<TatoebaSentence> japaneseTatoebaSentenceList = new ArrayList<TatoebaSentence>();\n\t \t\t\t\n\t \t\t\tfor (TatoebaSentence currentTatoebaSentence : tatoebaSentenceList) {\n\t \t\t\t\t\n\t \t\t\t\tif (currentTatoebaSentence.getLang().equals(\"pol\") == true) {\n\t \t\t\t\t\tpolishTatoebaSentenceList.add(currentTatoebaSentence);\n\t \t\t\t\t\t\n\t \t\t\t\t} else if (currentTatoebaSentence.getLang().equals(\"jpn\") == true) {\n\t \t\t\t\t\tjapaneseTatoebaSentenceList.add(currentTatoebaSentence);\n\t \t\t\t\t}\t\t\t\t\n\t \t\t\t}\n\t \t\t\t\n\t \t\t\tif (polishTatoebaSentenceList.size() > 0 && japaneseTatoebaSentenceList.size() > 0) {\n\n\t \t\t\t\tfor (TatoebaSentence currentPolishTatoebaSentence : polishTatoebaSentenceList) {\t \t\t\t\t\t\n\t \t\t\t\t\treport.add(new StringValue(currentPolishTatoebaSentence.getSentence(), 12.0f, 1));\t \t\t\t\t\t\n\t \t\t\t\t}\n\t \t\t\t\t\n\t \t\t\t\tfor (TatoebaSentence currentJapaneseTatoebaSentence : japaneseTatoebaSentenceList) {\t \t\t\t\t\t\n\t \t\t\t\t\treport.add(new StringValue(currentJapaneseTatoebaSentence.getSentence(), 12.0f, 1));\n\t \t\t\t\t}\n\t \t\t\t\t\n\t \t\t\t\tif (tatoebaSentenceGroupListIdx != tatoebaSentenceGroupList.size() - 1) {\t \t\t\t\t\t\n\t \t\t\t\t\treport.add(new StringValue(\"\", 6.0f, 1));\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t}\n\t \t\t\n\t \t\treport.add(new StringValue(\"\", 15.0f, 1));\n\t \t}\t\t\t\n\t\t}\t\t\n\n\t\t// Example\n\t\tList<ExampleGroupTypeElements> exampleGroupTypeElementsList = ExampleManager.getExamples(\n\t\t\t\tJapaneseAndroidLearnHelperApplication.getInstance().getDictionaryManager(this).getKeigoHelper(),\n\t\t\t\tdictionaryEntry, grammaCache, forceDictionaryEntryType, false);\n\n\t\tif (exampleGroupTypeElementsList != null) {\n\n\t\t\tif (grammaFormConjugateGroupTypeElementsList == null && (tatoebaSentenceGroupList == null || tatoebaSentenceGroupList.size() == 0)) {\n\t\t\t\treport.add(new StringValue(\"\", 15.0f, 2));\n\t\t\t}\n\n\t\t\treport.add(new TitleItem(getString(R.string.word_dictionary_details_example_label), 0));\n\n\t\t\tfor (ExampleGroupTypeElements currentExampleGroupTypeElements : exampleGroupTypeElementsList) {\n\n\t\t\t\treport.add(new TitleItem(currentExampleGroupTypeElements.getExampleGroupType().getName(), 1));\n\n\t\t\t\tString exampleGroupInfo = currentExampleGroupTypeElements.getExampleGroupType().getInfo();\n\n\t\t\t\tif (exampleGroupInfo != null) {\n\t\t\t\t\treport.add(new StringValue(exampleGroupInfo, 12.0f, 1));\n\t\t\t\t}\n\n\t\t\t\tList<ExampleResult> exampleResults = currentExampleGroupTypeElements.getExampleResults();\n\n\t\t\t\tfor (ExampleResult currentExampleResult : exampleResults) {\n\t\t\t\t\taddExampleResult(report, currentExampleResult);\n\t\t\t\t}\n\n\t\t\t\treport.add(new StringValue(\"\", 15.0f, 1));\n\t\t\t}\n\t\t}\n\n\t\t// add index\n\t\tif (indexStartPos < report.size()) {\n\n\t\t\tint indexStopPos = report.size();\n\n\t\t\tList<IScreenItem> indexList = new ArrayList<IScreenItem>();\n\n\t\t\tindexList.add(new StringValue(\"\", 15.0f, 2));\n\t\t\tindexList.add(new TitleItem(getString(R.string.word_dictionary_details_report_counters_index), 0));\n\t\t\tindexList.add(new StringValue(getString(R.string.word_dictionary_details_index_go), 12.0f, 1));\n\n\t\t\tfor (int reportIdx = indexStartPos; reportIdx < indexStopPos; ++reportIdx) {\n\n\t\t\t\tIScreenItem currentReportScreenItem = report.get(reportIdx);\n\n\t\t\t\tif (currentReportScreenItem instanceof TitleItem == false) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfinal TitleItem currentReportScreenItemAsTitle = (TitleItem) currentReportScreenItem;\n\n\t\t\t\tfinal StringValue titleStringValue = new StringValue(currentReportScreenItemAsTitle.getTitle(), 15.0f,\n\t\t\t\t\t\tcurrentReportScreenItemAsTitle.getLevel() + 2);\n\n\t\t\t\ttitleStringValue.setOnClickListener(new OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(View v) {\n\n\t\t\t\t\t\tbackScreenPositionStack.push(scrollMainLayout.getScrollY());\n\n\t\t\t\t\t\tint counterPos = currentReportScreenItemAsTitle.getY();\n\t\t\t\t\t\tscrollMainLayout.scrollTo(0, counterPos - 3);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tindexList.add(titleStringValue);\n\t\t\t}\n\n\t\t\tfor (int indexListIdx = 0, reportStartPos = indexStartPos; indexListIdx < indexList.size(); ++indexListIdx) {\n\t\t\t\treport.add(reportStartPos, indexList.get(indexListIdx));\n\n\t\t\t\treportStartPos++;\n\t\t\t}\n\t\t}\n\n\t\treturn report;\n\t}\n\n\tprivate void fillDetailsMainLayout(List<IScreenItem> generatedDetails, LinearLayout detailsMainLayout) {\n\n\t\tdetailsMainLayout.removeAllViews();\n\n\t\tfor (IScreenItem currentDetailsReportItem : generatedDetails) {\n\t\t\tcurrentDetailsReportItem.generate(this, getResources(), detailsMainLayout);\n\t\t}\n\t}\n\n\tprivate void addGrammaFormConjugateResult(List<IScreenItem> report,\n\t\t\tGrammaFormConjugateResult grammaFormConjugateResult) {\n\n\t\tTableLayout actionButtons = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, null);\n\t\tTableRow actionTableRow = new TableRow();\n\n\t\tString grammaFormKanji = grammaFormConjugateResult.getKanji();\n\n\t\tString prefixKana = grammaFormConjugateResult.getPrefixKana();\n\t\tString prefixRomaji = grammaFormConjugateResult.getPrefixRomaji();\n\n\t\tStringBuffer grammaFormKanjiSb = new StringBuffer();\n\n\t\tif (grammaFormKanji != null) {\n\t\t\tif (prefixKana != null && prefixKana.equals(\"\") == false) {\n\t\t\t\tgrammaFormKanjiSb.append(\"(\").append(prefixKana).append(\") \");\n\t\t\t}\n\n\t\t\tgrammaFormKanjiSb.append(grammaFormKanji);\n\n\t\t\treport.add(new StringValue(grammaFormKanjiSb.toString(), 15.0f, 2));\n\t\t}\n\n\t\tList<String> grammaFormKanaList = grammaFormConjugateResult.getKanaList();\n\t\tList<String> grammaFormRomajiList = grammaFormConjugateResult.getRomajiList();\n\n\t\tfor (int idx = 0; idx < grammaFormKanaList.size(); ++idx) {\n\n\t\t\tStringBuffer sb = new StringBuffer();\n\n\t\t\tif (prefixKana != null && prefixKana.equals(\"\") == false) {\n\t\t\t\tsb.append(\"(\").append(prefixKana).append(\") \");\n\t\t\t}\n\n\t\t\tsb.append(grammaFormKanaList.get(idx));\n\n\t\t\treport.add(new StringValue(sb.toString(), 15.0f, 2));\n\n\t\t\tStringBuffer grammaFormRomajiSb = new StringBuffer();\n\n\t\t\tif (prefixRomaji != null && prefixRomaji.equals(\"\") == false) {\n\t\t\t\tgrammaFormRomajiSb.append(\"(\").append(prefixRomaji).append(\") \");\n\t\t\t}\n\n\t\t\tgrammaFormRomajiSb.append(grammaFormRomajiList.get(idx));\n\n\t\t\treport.add(new StringValue(grammaFormRomajiSb.toString(), 15.0f, 2));\n\n\t\t\t// speak image\n\t\t\tImage speakImage = new Image(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getListenIconId()), 2);\n\t\t\tspeakImage.setOnClickListener(new TTSJapaneseSpeak(null, grammaFormKanaList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(speakImage);\n\n\t\t\t// clipboard kanji\n\t\t\tif (grammaFormKanji != null) {\n\t\t\t\tImage clipboardKanji = new Image(getResources().getDrawable(R.drawable.clipboard_kanji), 0);\n\t\t\t\tclipboardKanji.setOnClickListener(new CopyToClipboard(grammaFormKanji));\n\t\t\t\tactionTableRow.addScreenItem(clipboardKanji);\n\t\t\t}\n\n\t\t\t// clipboard kana\n\t\t\tImage clipboardKana = new Image(getResources().getDrawable(R.drawable.clipboard_kana), 0);\n\t\t\tclipboardKana.setOnClickListener(new CopyToClipboard(grammaFormKanaList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(clipboardKana);\n\n\t\t\t// clipboard romaji\n\t\t\tImage clipboardRomaji = new Image(getResources().getDrawable(R.drawable.clipboard_romaji), 0);\n\t\t\tclipboardRomaji.setOnClickListener(new CopyToClipboard(grammaFormRomajiList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(clipboardRomaji);\n\n\t\t\tactionButtons.addTableRow(actionTableRow);\n\n\t\t\treport.add(actionButtons);\n\t\t}\n\n\t\tGrammaFormConjugateResult alternative = grammaFormConjugateResult.getAlternative();\n\n\t\tif (alternative != null) {\n\t\t\treport.add(new StringValue(\"\", 5.0f, 1));\n\n\t\t\taddGrammaFormConjugateResult(report, alternative);\n\t\t}\n\t}\n\n\tprivate void addExampleResult(List<IScreenItem> report, ExampleResult exampleResult) {\n\n\t\tTableLayout actionButtons = new TableLayout(TableLayout.LayoutParam.WrapContent_WrapContent, true, null);\n\t\tTableRow actionTableRow = new TableRow();\n\n\t\tString exampleKanji = exampleResult.getKanji();\n\t\tString prefixKana = exampleResult.getPrefixKana();\n\t\tString prefixRomaji = exampleResult.getPrefixRomaji();\n\n\t\tStringBuffer exampleKanjiSb = new StringBuffer();\n\n\t\tif (exampleKanji != null) {\n\t\t\tif (prefixKana != null && prefixKana.equals(\"\") == false) {\n\t\t\t\texampleKanjiSb.append(\"(\").append(prefixKana).append(\") \");\n\t\t\t}\n\n\t\t\texampleKanjiSb.append(exampleKanji);\n\n\t\t\treport.add(new StringValue(exampleKanjiSb.toString(), 15.0f, 2));\n\t\t}\n\n\t\tList<String> exampleKanaList = exampleResult.getKanaList();\n\t\tList<String> exampleRomajiList = exampleResult.getRomajiList();\n\n\t\tfor (int idx = 0; idx < exampleKanaList.size(); ++idx) {\n\n\t\t\tStringBuffer sb = new StringBuffer();\n\n\t\t\tif (prefixKana != null && prefixKana.equals(\"\") == false) {\n\t\t\t\tsb.append(\"(\").append(prefixKana).append(\") \");\n\t\t\t}\n\n\t\t\tsb.append(exampleKanaList.get(idx));\n\n\t\t\treport.add(new StringValue(sb.toString(), 15.0f, 2));\n\n\t\t\tStringBuffer exampleRomajiSb = new StringBuffer();\n\n\t\t\tif (prefixRomaji != null && prefixRomaji.equals(\"\") == false) {\n\t\t\t\texampleRomajiSb.append(\"(\").append(prefixRomaji).append(\") \");\n\t\t\t}\n\n\t\t\texampleRomajiSb.append(exampleRomajiList.get(idx));\n\n\t\t\treport.add(new StringValue(exampleRomajiSb.toString(), 15.0f, 2));\n\n\t\t\tString exampleResultInfo = exampleResult.getInfo();\n\n\t\t\tif (exampleResultInfo != null) {\n\t\t\t\treport.add(new StringValue(exampleResultInfo, 12.0f, 2));\n\t\t\t}\n\n\t\t\t// speak image\n\t\t\tImage speakImage = new Image(getResources().getDrawable(JapaneseAndroidLearnHelperApplication.getInstance().getThemeType().getListenIconId()), 2);\n\t\t\tspeakImage.setOnClickListener(new TTSJapaneseSpeak(null, exampleKanaList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(speakImage);\n\n\t\t\t// clipboard kanji\n\t\t\tif (exampleKanji != null) {\n\t\t\t\tImage clipboardKanji = new Image(getResources().getDrawable(R.drawable.clipboard_kanji), 0);\n\t\t\t\tclipboardKanji.setOnClickListener(new CopyToClipboard(exampleKanji));\n\t\t\t\tactionTableRow.addScreenItem(clipboardKanji);\n\t\t\t}\n\n\t\t\t// clipboard kana\n\t\t\tImage clipboardKana = new Image(getResources().getDrawable(R.drawable.clipboard_kana), 0);\n\t\t\tclipboardKana.setOnClickListener(new CopyToClipboard(exampleKanaList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(clipboardKana);\n\n\t\t\t// clipboard romaji\n\t\t\tImage clipboardRomaji = new Image(getResources().getDrawable(R.drawable.clipboard_romaji), 0);\n\t\t\tclipboardRomaji.setOnClickListener(new CopyToClipboard(exampleRomajiList.get(idx)));\n\t\t\tactionTableRow.addScreenItem(clipboardRomaji);\n\n\t\t\tactionButtons.addTableRow(actionTableRow);\n\n\t\t\treport.add(actionButtons);\n\t\t}\n\n\t\tExampleResult alternative = exampleResult.getAlternative();\n\n\t\tif (alternative != null) {\n\t\t\treport.add(new StringValue(\"\", 5.0f, 1));\n\n\t\t\taddExampleResult(report, alternative);\n\t\t}\n\t}\n\n\t// special\n\tprivate boolean isSmTsukiNiKawatteOshiokiYo(String value) {\n\n\t\tif (value == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (value.equals(\"月に代わって、お仕置きよ!\") == true) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate boolean isButaMoOdateryaKiNiNoboru(String value) {\n\n\t\tif (value == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (value.equals(\"豚もおだてりゃ木に登る\") == true || value.equals(\"ブタもおだてりゃ木に登る\") == true || value.equals(\"豚も煽てりゃ木に登る\") == true) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate StringValue createSpecialAAText(int stringId) {\n\n\t\tStringValue smStringValue = new StringValue(getString(stringId), 3.8f, 0);\n\n\t\tsmStringValue.setTypeface(Typeface.MONOSPACE);\n\t\tsmStringValue.setTextColor(Color.BLACK);\n\t\tsmStringValue.setBackgroundColor(Color.WHITE);\n\t\tsmStringValue.setGravity(Gravity.CENTER);\n\n\t\treturn smStringValue;\n\t}\n\n\tprivate class TTSJapaneseSpeak implements OnClickListener {\n\n\t\tprivate final String prefix;\n\n\t\tprivate final String kanjiKana;\n\n\t\tpublic TTSJapaneseSpeak(String prefix, String kanjiKana) {\n\t\t\tthis.prefix = prefix;\n\t\t\tthis.kanjiKana = kanjiKana;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\n\t\t\tStringBuffer text = new StringBuffer();\n\n\t\t\tif (prefix != null) {\n\t\t\t\ttext.append(prefix);\n\t\t\t}\n\n\t\t\tif (kanjiKana != null) {\n\t\t\t\ttext.append(kanjiKana);\n\t\t\t}\n\n\t\t\tif (ttsConnector != null && ttsConnector.getOnInitResult() != null\n\t\t\t\t\t&& ttsConnector.getOnInitResult().booleanValue() == true) {\n\t\t\t\tttsConnector.speak(text.toString());\n\t\t\t} else {\n\t\t\t\tAlertDialog alertDialog = new AlertDialog.Builder(WordDictionaryDetails.this).create();\n\n\t\t\t\talertDialog.setMessage(getString(R.string.tts_japanese_error));\n\t\t\t\talertDialog.setCancelable(false);\n\n\t\t\t\talertDialog.setButton(getString(R.string.tts_error_ok), new DialogInterface.OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t// noop\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\talertDialog.setButton2(getString(R.string.tts_google_play_go), new DialogInterface.OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\n\t\t\t\t\t\tUri marketUri = Uri.parse(getString(R.string.tts_google_android_tts_url));\n\n\t\t\t\t\t\tIntent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);\n\n\t\t\t\t\t\tstartActivity(marketIntent);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\talertDialog.show();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Image createFavouriteWordStar(DictionaryManagerCommon dictionaryManager, final DictionaryEntry dictionaryEntry) {\n\n\t\tfinal DataManager dataManager = dictionaryManager.getDataManager();\n\n\t\tUserGroupEntity startUserGroup = null;\n\n\t\ttry {\n\t\t\tstartUserGroup = dataManager.getStarUserGroup();\n\n\t\t} catch (DataManagerException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\n\t\tfinal UserGroupEntity startUserGroup2 = startUserGroup;\n\n\t\tboolean isItemIdExistsInStarGroup = dataManager.isItemIdExistsInUserGroup(startUserGroup, UserGroupItemEntity.Type.DICTIONARY_ENTRY, dictionaryEntry.getId());\n\n\t\tfinal int starBigOff = android.R.drawable.star_big_off;\n\t\tfinal int starBigOn = android.R.drawable.star_big_on;\n\n\t\tfinal Image starImage = new Image(getResources().getDrawable(isItemIdExistsInStarGroup == false ? starBigOff : starBigOn), 0);\n\n\t\tstarImage.setOnClickListener(new OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\n\t\t\t\tboolean isItemIdExistsInStarGroup = dataManager.isItemIdExistsInUserGroup(startUserGroup2, UserGroupItemEntity.Type.DICTIONARY_ENTRY, dictionaryEntry.getId());\n\n\t\t\t\tif (isItemIdExistsInStarGroup == false) {\n\t\t\t\t\tdataManager.addItemIdToUserGroup(startUserGroup2, UserGroupItemEntity.Type.DICTIONARY_ENTRY, dictionaryEntry.getId());\n\n\t\t\t\t\tstarImage.changeImage(getResources().getDrawable(starBigOn));\n\n\t\t\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\t\t\tgetString(R.string.word_dictionary_details_add_to_star_group), Toast.LENGTH_SHORT).show();\n\n\n\t\t\t\t} else {\n\t\t\t\t\tdataManager.deleteItemIdFromUserGroup(startUserGroup2, UserGroupItemEntity.Type.DICTIONARY_ENTRY, dictionaryEntry.getId());\n\n\t\t\t\t\tstarImage.changeImage(getResources().getDrawable(starBigOff));\n\n\t\t\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\t\t\tgetString(R.string.word_dictionary_details_remove_from_star_group), Toast.LENGTH_SHORT).show();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\treturn starImage;\n\t}\n\n\tprivate OnClickListener createDeleteItemIdFromUserGroupOnClickListener(final DataManager dataManager, final DictionaryEntry dictionaryEntry, final UserGroupEntity userGroupEntity, final TableRow userGroupTableRow) {\n\n\t\treturn new OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\n\t\t\t\tfinal AlertDialog alertDialog = new AlertDialog.Builder(WordDictionaryDetails.this).create();\n\n\t\t\t\talertDialog.setTitle(getString(R.string.word_dictionary_details_delete_item_id_from_user_group_title));\n\t\t\t\talertDialog.setMessage(getString(R.string.word_dictionary_details_delete_item_id_from_user_group_message, userGroupEntity.getName()));\n\n\t\t\t\talertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.user_group_ok_button), new DialogInterface.OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\n\t\t\t\t\t\t// usuwamy z bazy danych\n\t\t\t\t\t\tdataManager.deleteItemIdFromUserGroup(userGroupEntity, UserGroupItemEntity.Type.DICTIONARY_ENTRY, dictionaryEntry.getId());\n\n\t\t\t\t\t\t// ukrywamy grupe\n\t\t\t\t\t\tuserGroupTableRow.setVisibility(View.GONE);\n\n\t\t\t\t\t\t// komunikat\n\t\t\t\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\t\t\t\tgetString(R.string.word_dictionary_details_delete_item_id_from_user_group_toast, userGroupEntity.getName()), Toast.LENGTH_SHORT).show();\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\talertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.user_group_cancel_button), new DialogInterface.OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\talertDialog.dismiss();\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (isFinishing() == false) {\n\t\t\t\t\talertDialog.show();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\n\n\tprivate class CopyToClipboard implements OnClickListener {\n\n\t\tprivate final String text;\n\n\t\tpublic CopyToClipboard(String text) {\n\t\t\tthis.text = text;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\n\t\t\tClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n\n\t\t\tclipboardManager.setText(text);\n\n\t\t\tToast.makeText(WordDictionaryDetails.this,\n\t\t\t\t\tgetString(R.string.word_dictionary_details_clipboard_copy, text), Toast.LENGTH_SHORT).show();\n\t\t}\n\t}\n}", "public class ReportProblem {\n\t\n\tpublic static Intent createReportProblemIntent(String mailSubject, String mailBody, String versionName, int versionCode) {\n\t\t\n\t\tIntent email = new Intent(Intent.ACTION_SEND);\n\t\t\n\t\tmailBody += \"---\\nVersion code: \" + versionCode + \"\\nVersion name: \" + versionName + \"\\n\";\n\t\t\n\t\temail.putExtra(Intent.EXTRA_EMAIL, new String[] { \"fryderyk.mazurek@gmail.com\" } );\n\t\t\n\t\temail.putExtra(Intent.EXTRA_SUBJECT, mailSubject);\n\t\temail.putExtra(Intent.EXTRA_TEXT, mailBody);\n\t\t\n\t\temail.setType(\"message/rfc822\");\n\t\t\n\t\treturn email;\n\t}\n}", "public class EntryOrderList<T> {\n\t\n\tprivate List<T> list;\n\t\n\tprivate int groupSize;\n\t\n\tprivate int currentPos;\n\t\n\tpublic EntryOrderList(List<T> list, int groupSize) {\n\t\t\n\t\tthis.list = list;\n\t\t\n\t\tthis.groupSize = groupSize;\n\t\t\n\t\tthis.currentPos = 0;\n\t}\n\t\n\tpublic T getNext() {\n\t\t\n\t\tif (currentPos < list.size()) {\n\t\t\treturn list.get(currentPos);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic int getCurrentPos() {\n\t\treturn currentPos;\n\t}\n\t\n\tpublic int size() {\n\t\treturn list.size();\n\t}\n\t\n\tpublic T getEntry(int idx) {\n\t\treturn list.get(idx);\n\t}\n\n\tpublic void currentPositionOk() {\t\t\n\t\tcurrentPos++;\n\t}\n\t\n\tpublic void currentPositionBad() {\n\t\t\n\t\tif (currentPos >= list.size()) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tT currentPosT = list.get(currentPos);\n\t\t\n\t\tint nextPosition = currentPos + groupSize;\n\t\t\n\t\tif (nextPosition > list.size()) {\n\t\t\tnextPosition = list.size();\n\t\t}\n\t\t\n\t\tlist.add(nextPosition, currentPosT);\n\t\t\n\t\tcurrentPos++;\n\t}\n\t\n\tpublic String toString() {\n\t\t\n\t\tStringBuffer sb = new StringBuffer();\n\t\t\n\t\tfor (int idx = 0; idx < list.size(); ++idx) {\n\t\t\t\n\t\t\tif (idx == currentPos) {\n\t\t\t\tsb.append(\"* \");\n\t\t\t}\n\t\t\t\n\t\t\tif (idx == currentPos + groupSize) {\n\t\t\t\tsb.append(\"| \");\n\t\t\t}\n\t\t\t\n\t\t\tsb.append(list.get(idx));\n\t\t\t\n\t\t\tif (idx != list.size() - 1) {\n\t\t\t\tsb.append(\" \");\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn sb.toString();\t\t\n\t}\n}", "public class ListUtil {\n\n\tpublic static String getListAsString(List<?> list, String delimeter) {\n\t\tStringBuffer sb = new StringBuffer();\n\t\t\n\t\tfor (int idx = 0; idx < list.size(); ++idx) {\n\t\t\tsb.append(list.get(idx));\n\t\t\t\n\t\t\tif (idx != list.size() - 1) {\n\t\t\t\tsb.append(delimeter);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn sb.toString();\n\t}\n}" ]
import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import pl.idedyk.android.japaneselearnhelper.JapaneseAndroidLearnHelperApplication; import pl.idedyk.android.japaneselearnhelper.MenuShorterHelper; import pl.idedyk.android.japaneselearnhelper.R; import pl.idedyk.android.japaneselearnhelper.config.ConfigManager.WordTestConfig; import pl.idedyk.android.japaneselearnhelper.context.JapaneseAndroidLearnHelperContext; import pl.idedyk.android.japaneselearnhelper.context.JapaneseAndroidLearnHelperWordTestContext; import pl.idedyk.android.japaneselearnhelper.dictionaryscreen.WordDictionaryDetails; import pl.idedyk.android.japaneselearnhelper.problem.ReportProblem; import pl.idedyk.android.japaneselearnhelper.utils.EntryOrderList; import pl.idedyk.android.japaneselearnhelper.utils.ListUtil; import pl.idedyk.japanese.dictionary.api.dictionary.Utils; import pl.idedyk.japanese.dictionary.api.dto.Attribute; import pl.idedyk.japanese.dictionary.api.dto.AttributeType; import pl.idedyk.japanese.dictionary.api.dto.DictionaryEntry; import pl.idedyk.japanese.dictionary.api.exception.DictionaryException; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.text.InputType; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;
package pl.idedyk.android.japaneselearnhelper.test; public class WordTest extends Activity { private TextViewAndEditText[] textViewAndEditTextForWordAsArray; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, R.id.report_problem_menu_item, Menu.NONE, R.string.report_problem); MenuShorterHelper.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); // report problem if (item.getItemId() == R.id.report_problem_menu_item) { final JapaneseAndroidLearnHelperContext context = JapaneseAndroidLearnHelperApplication.getInstance() .getContext(); final JapaneseAndroidLearnHelperWordTestContext wordTestContext = context.getWordTestContext(); final WordTestConfig wordTestConfig = JapaneseAndroidLearnHelperApplication.getInstance() .getConfigManager(WordTest.this).getWordTestConfig(); // config WordTestMode wordTestMode = wordTestConfig.getWordTestMode(); Set<String> chosenWordGroups = wordTestConfig.getChosenWordGroups(); Boolean random = wordTestConfig.getRandom(); Boolean untilSuccess = wordTestConfig.getUntilSuccess(); Integer repeatNumber = wordTestConfig.getRepeatNumber(); Boolean showKanji = wordTestConfig.getShowKanji(); Boolean showKana = wordTestConfig.getShowKana(); Boolean showTranslate = wordTestConfig.getShowTranslate(); Boolean showAdditionalInfo = wordTestConfig.getShowAdditionalInfo(); // context
EntryOrderList<DictionaryEntry> wordsTest = wordTestContext.getWordsTest();
7
lrtdc/light_drtc
src/main/java/org/light/rtc/admin/AdminNodeRabbitMqRun.java
[ "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\r\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-16\")\r\npublic class TDssService {\r\n\r\n public interface Iface {\r\n\r\n public int addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TException;\r\n\r\n public int rtcStats(List<String> userLogs) throws org.apache.thrift.TException;\r\n\r\n public int batchStats(int start, int size) throws org.apache.thrift.TException;\r\n\r\n public int getAdminNodeId() throws org.apache.thrift.TException;\r\n\r\n public int getHealthStatus() throws org.apache.thrift.TException;\r\n\r\n public int getJobStatus() throws org.apache.thrift.TException;\r\n\r\n }\r\n\r\n public interface AsyncIface {\r\n\r\n public void addMqinfoToAdminQu(List<String> uLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void rtcStats(List<String> userLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void batchStats(int start, int size, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void getAdminNodeId(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void getHealthStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void getJobStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n }\r\n\r\n public static class Client extends org.apache.thrift.TServiceClient implements Iface {\r\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\r\n public Factory() {}\r\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\r\n return new Client(prot);\r\n }\r\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\r\n return new Client(iprot, oprot);\r\n }\r\n }\r\n\r\n public Client(org.apache.thrift.protocol.TProtocol prot)\r\n {\r\n super(prot, prot);\r\n }\r\n\r\n public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\r\n super(iprot, oprot);\r\n }\r\n\r\n public int addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TException\r\n {\r\n send_addMqinfoToAdminQu(uLogs);\r\n return recv_addMqinfoToAdminQu();\r\n }\r\n\r\n public void send_addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TException\r\n {\r\n addMqinfoToAdminQu_args args = new addMqinfoToAdminQu_args();\r\n args.setULogs(uLogs);\r\n sendBase(\"addMqinfoToAdminQu\", args);\r\n }\r\n\r\n public int recv_addMqinfoToAdminQu() throws org.apache.thrift.TException\r\n {\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n receiveBase(result, \"addMqinfoToAdminQu\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"addMqinfoToAdminQu failed: unknown result\");\r\n }\r\n\r\n public int rtcStats(List<String> userLogs) throws org.apache.thrift.TException\r\n {\r\n send_rtcStats(userLogs);\r\n return recv_rtcStats();\r\n }\r\n\r\n public void send_rtcStats(List<String> userLogs) throws org.apache.thrift.TException\r\n {\r\n rtcStats_args args = new rtcStats_args();\r\n args.setUserLogs(userLogs);\r\n sendBase(\"rtcStats\", args);\r\n }\r\n\r\n public int recv_rtcStats() throws org.apache.thrift.TException\r\n {\r\n rtcStats_result result = new rtcStats_result();\r\n receiveBase(result, \"rtcStats\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"rtcStats failed: unknown result\");\r\n }\r\n\r\n public int batchStats(int start, int size) throws org.apache.thrift.TException\r\n {\r\n send_batchStats(start, size);\r\n return recv_batchStats();\r\n }\r\n\r\n public void send_batchStats(int start, int size) throws org.apache.thrift.TException\r\n {\r\n batchStats_args args = new batchStats_args();\r\n args.setStart(start);\r\n args.setSize(size);\r\n sendBase(\"batchStats\", args);\r\n }\r\n\r\n public int recv_batchStats() throws org.apache.thrift.TException\r\n {\r\n batchStats_result result = new batchStats_result();\r\n receiveBase(result, \"batchStats\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"batchStats failed: unknown result\");\r\n }\r\n\r\n public int getAdminNodeId() throws org.apache.thrift.TException\r\n {\r\n send_getAdminNodeId();\r\n return recv_getAdminNodeId();\r\n }\r\n\r\n public void send_getAdminNodeId() throws org.apache.thrift.TException\r\n {\r\n getAdminNodeId_args args = new getAdminNodeId_args();\r\n sendBase(\"getAdminNodeId\", args);\r\n }\r\n\r\n public int recv_getAdminNodeId() throws org.apache.thrift.TException\r\n {\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n receiveBase(result, \"getAdminNodeId\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"getAdminNodeId failed: unknown result\");\r\n }\r\n\r\n public int getHealthStatus() throws org.apache.thrift.TException\r\n {\r\n send_getHealthStatus();\r\n return recv_getHealthStatus();\r\n }\r\n\r\n public void send_getHealthStatus() throws org.apache.thrift.TException\r\n {\r\n getHealthStatus_args args = new getHealthStatus_args();\r\n sendBase(\"getHealthStatus\", args);\r\n }\r\n\r\n public int recv_getHealthStatus() throws org.apache.thrift.TException\r\n {\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n receiveBase(result, \"getHealthStatus\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"getHealthStatus failed: unknown result\");\r\n }\r\n\r\n public int getJobStatus() throws org.apache.thrift.TException\r\n {\r\n send_getJobStatus();\r\n return recv_getJobStatus();\r\n }\r\n\r\n public void send_getJobStatus() throws org.apache.thrift.TException\r\n {\r\n getJobStatus_args args = new getJobStatus_args();\r\n sendBase(\"getJobStatus\", args);\r\n }\r\n\r\n public int recv_getJobStatus() throws org.apache.thrift.TException\r\n {\r\n getJobStatus_result result = new getJobStatus_result();\r\n receiveBase(result, \"getJobStatus\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"getJobStatus failed: unknown result\");\r\n }\r\n\r\n }\r\n public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {\r\n public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {\r\n private org.apache.thrift.async.TAsyncClientManager clientManager;\r\n private org.apache.thrift.protocol.TProtocolFactory protocolFactory;\r\n public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {\r\n this.clientManager = clientManager;\r\n this.protocolFactory = protocolFactory;\r\n }\r\n public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {\r\n return new AsyncClient(protocolFactory, clientManager, transport);\r\n }\r\n }\r\n\r\n public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {\r\n super(protocolFactory, clientManager, transport);\r\n }\r\n\r\n public void addMqinfoToAdminQu(List<String> uLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n addMqinfoToAdminQu_call method_call = new addMqinfoToAdminQu_call(uLogs, resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class addMqinfoToAdminQu_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n private List<String> uLogs;\r\n public addMqinfoToAdminQu_call(List<String> uLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n this.uLogs = uLogs;\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"addMqinfoToAdminQu\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n addMqinfoToAdminQu_args args = new addMqinfoToAdminQu_args();\r\n args.setULogs(uLogs);\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_addMqinfoToAdminQu();\r\n }\r\n }\r\n\r\n public void rtcStats(List<String> userLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n rtcStats_call method_call = new rtcStats_call(userLogs, resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class rtcStats_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n private List<String> userLogs;\r\n public rtcStats_call(List<String> userLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n this.userLogs = userLogs;\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"rtcStats\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n rtcStats_args args = new rtcStats_args();\r\n args.setUserLogs(userLogs);\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_rtcStats();\r\n }\r\n }\r\n\r\n public void batchStats(int start, int size, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n batchStats_call method_call = new batchStats_call(start, size, resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class batchStats_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n private int start;\r\n private int size;\r\n public batchStats_call(int start, int size, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n this.start = start;\r\n this.size = size;\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"batchStats\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n batchStats_args args = new batchStats_args();\r\n args.setStart(start);\r\n args.setSize(size);\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_batchStats();\r\n }\r\n }\r\n\r\n public void getAdminNodeId(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n getAdminNodeId_call method_call = new getAdminNodeId_call(resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class getAdminNodeId_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n public getAdminNodeId_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"getAdminNodeId\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n getAdminNodeId_args args = new getAdminNodeId_args();\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_getAdminNodeId();\r\n }\r\n }\r\n\r\n public void getHealthStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n getHealthStatus_call method_call = new getHealthStatus_call(resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class getHealthStatus_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n public getHealthStatus_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"getHealthStatus\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n getHealthStatus_args args = new getHealthStatus_args();\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_getHealthStatus();\r\n }\r\n }\r\n\r\n public void getJobStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n getJobStatus_call method_call = new getJobStatus_call(resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class getJobStatus_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n public getJobStatus_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"getJobStatus\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n getJobStatus_args args = new getJobStatus_args();\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_getJobStatus();\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {\r\n private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());\r\n public Processor(I iface) {\r\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));\r\n }\r\n\r\n protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\r\n super(iface, getProcessMap(processMap));\r\n }\r\n\r\n private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\r\n processMap.put(\"addMqinfoToAdminQu\", new addMqinfoToAdminQu());\r\n processMap.put(\"rtcStats\", new rtcStats());\r\n processMap.put(\"batchStats\", new batchStats());\r\n processMap.put(\"getAdminNodeId\", new getAdminNodeId());\r\n processMap.put(\"getHealthStatus\", new getHealthStatus());\r\n processMap.put(\"getJobStatus\", new getJobStatus());\r\n return processMap;\r\n }\r\n\r\n public static class addMqinfoToAdminQu<I extends Iface> extends org.apache.thrift.ProcessFunction<I, addMqinfoToAdminQu_args> {\r\n public addMqinfoToAdminQu() {\r\n super(\"addMqinfoToAdminQu\");\r\n }\r\n\r\n public addMqinfoToAdminQu_args getEmptyArgsInstance() {\r\n return new addMqinfoToAdminQu_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public addMqinfoToAdminQu_result getResult(I iface, addMqinfoToAdminQu_args args) throws org.apache.thrift.TException {\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n result.success = iface.addMqinfoToAdminQu(args.uLogs);\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class rtcStats<I extends Iface> extends org.apache.thrift.ProcessFunction<I, rtcStats_args> {\r\n public rtcStats() {\r\n super(\"rtcStats\");\r\n }\r\n\r\n public rtcStats_args getEmptyArgsInstance() {\r\n return new rtcStats_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public rtcStats_result getResult(I iface, rtcStats_args args) throws org.apache.thrift.TException {\r\n rtcStats_result result = new rtcStats_result();\r\n result.success = iface.rtcStats(args.userLogs);\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class batchStats<I extends Iface> extends org.apache.thrift.ProcessFunction<I, batchStats_args> {\r\n public batchStats() {\r\n super(\"batchStats\");\r\n }\r\n\r\n public batchStats_args getEmptyArgsInstance() {\r\n return new batchStats_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public batchStats_result getResult(I iface, batchStats_args args) throws org.apache.thrift.TException {\r\n batchStats_result result = new batchStats_result();\r\n result.success = iface.batchStats(args.start, args.size);\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class getAdminNodeId<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getAdminNodeId_args> {\r\n public getAdminNodeId() {\r\n super(\"getAdminNodeId\");\r\n }\r\n\r\n public getAdminNodeId_args getEmptyArgsInstance() {\r\n return new getAdminNodeId_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public getAdminNodeId_result getResult(I iface, getAdminNodeId_args args) throws org.apache.thrift.TException {\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n result.success = iface.getAdminNodeId();\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class getHealthStatus<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getHealthStatus_args> {\r\n public getHealthStatus() {\r\n super(\"getHealthStatus\");\r\n }\r\n\r\n public getHealthStatus_args getEmptyArgsInstance() {\r\n return new getHealthStatus_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public getHealthStatus_result getResult(I iface, getHealthStatus_args args) throws org.apache.thrift.TException {\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n result.success = iface.getHealthStatus();\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class getJobStatus<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getJobStatus_args> {\r\n public getJobStatus() {\r\n super(\"getJobStatus\");\r\n }\r\n\r\n public getJobStatus_args getEmptyArgsInstance() {\r\n return new getJobStatus_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public getJobStatus_result getResult(I iface, getJobStatus_args args) throws org.apache.thrift.TException {\r\n getJobStatus_result result = new getJobStatus_result();\r\n result.success = iface.getJobStatus();\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {\r\n private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());\r\n public AsyncProcessor(I iface) {\r\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));\r\n }\r\n\r\n protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\r\n super(iface, getProcessMap(processMap));\r\n }\r\n\r\n private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\r\n processMap.put(\"addMqinfoToAdminQu\", new addMqinfoToAdminQu());\r\n processMap.put(\"rtcStats\", new rtcStats());\r\n processMap.put(\"batchStats\", new batchStats());\r\n processMap.put(\"getAdminNodeId\", new getAdminNodeId());\r\n processMap.put(\"getHealthStatus\", new getHealthStatus());\r\n processMap.put(\"getJobStatus\", new getJobStatus());\r\n return processMap;\r\n }\r\n\r\n public static class addMqinfoToAdminQu<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, addMqinfoToAdminQu_args, Integer> {\r\n public addMqinfoToAdminQu() {\r\n super(\"addMqinfoToAdminQu\");\r\n }\r\n\r\n public addMqinfoToAdminQu_args getEmptyArgsInstance() {\r\n return new addMqinfoToAdminQu_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, addMqinfoToAdminQu_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.addMqinfoToAdminQu(args.uLogs,resultHandler);\r\n }\r\n }\r\n\r\n public static class rtcStats<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, rtcStats_args, Integer> {\r\n public rtcStats() {\r\n super(\"rtcStats\");\r\n }\r\n\r\n public rtcStats_args getEmptyArgsInstance() {\r\n return new rtcStats_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n rtcStats_result result = new rtcStats_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n rtcStats_result result = new rtcStats_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, rtcStats_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.rtcStats(args.userLogs,resultHandler);\r\n }\r\n }\r\n\r\n public static class batchStats<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, batchStats_args, Integer> {\r\n public batchStats() {\r\n super(\"batchStats\");\r\n }\r\n\r\n public batchStats_args getEmptyArgsInstance() {\r\n return new batchStats_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n batchStats_result result = new batchStats_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n batchStats_result result = new batchStats_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, batchStats_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.batchStats(args.start, args.size,resultHandler);\r\n }\r\n }\r\n\r\n public static class getAdminNodeId<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getAdminNodeId_args, Integer> {\r\n public getAdminNodeId() {\r\n super(\"getAdminNodeId\");\r\n }\r\n\r\n public getAdminNodeId_args getEmptyArgsInstance() {\r\n return new getAdminNodeId_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, getAdminNodeId_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.getAdminNodeId(resultHandler);\r\n }\r\n }\r\n\r\n public static class getHealthStatus<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getHealthStatus_args, Integer> {\r\n public getHealthStatus() {\r\n super(\"getHealthStatus\");\r\n }\r\n\r\n public getHealthStatus_args getEmptyArgsInstance() {\r\n return new getHealthStatus_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, getHealthStatus_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.getHealthStatus(resultHandler);\r\n }\r\n }\r\n\r\n public static class getJobStatus<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getJobStatus_args, Integer> {\r\n public getJobStatus() {\r\n super(\"getJobStatus\");\r\n }\r\n\r\n public getJobStatus_args getEmptyArgsInstance() {\r\n return new getJobStatus_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n getJobStatus_result result = new getJobStatus_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n getJobStatus_result result = new getJobStatus_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, getJobStatus_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.getJobStatus(resultHandler);\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class addMqinfoToAdminQu_args implements org.apache.thrift.TBase<addMqinfoToAdminQu_args, addMqinfoToAdminQu_args._Fields>, java.io.Serializable, Cloneable, Comparable<addMqinfoToAdminQu_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"addMqinfoToAdminQu_args\");\r\n\r\n private static final org.apache.thrift.protocol.TField U_LOGS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"uLogs\", org.apache.thrift.protocol.TType.LIST, (short)1);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new addMqinfoToAdminQu_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new addMqinfoToAdminQu_argsTupleSchemeFactory());\r\n }\r\n\r\n public List<String> uLogs; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n U_LOGS((short)1, \"uLogs\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 1: // U_LOGS\r\n return U_LOGS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.U_LOGS, new org.apache.thrift.meta_data.FieldMetaData(\"uLogs\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(addMqinfoToAdminQu_args.class, metaDataMap);\r\n }\r\n\r\n public addMqinfoToAdminQu_args() {\r\n }\r\n\r\n public addMqinfoToAdminQu_args(\r\n List<String> uLogs)\r\n {\r\n this();\r\n this.uLogs = uLogs;\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public addMqinfoToAdminQu_args(addMqinfoToAdminQu_args other) {\r\n if (other.isSetULogs()) {\r\n List<String> __this__uLogs = new ArrayList<String>(other.uLogs);\r\n this.uLogs = __this__uLogs;\r\n }\r\n }\r\n\r\n public addMqinfoToAdminQu_args deepCopy() {\r\n return new addMqinfoToAdminQu_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n this.uLogs = null;\r\n }\r\n\r\n public int getULogsSize() {\r\n return (this.uLogs == null) ? 0 : this.uLogs.size();\r\n }\r\n\r\n public java.util.Iterator<String> getULogsIterator() {\r\n return (this.uLogs == null) ? null : this.uLogs.iterator();\r\n }\r\n\r\n public void addToULogs(String elem) {\r\n if (this.uLogs == null) {\r\n this.uLogs = new ArrayList<String>();\r\n }\r\n this.uLogs.add(elem);\r\n }\r\n\r\n public List<String> getULogs() {\r\n return this.uLogs;\r\n }\r\n\r\n public addMqinfoToAdminQu_args setULogs(List<String> uLogs) {\r\n this.uLogs = uLogs;\r\n return this;\r\n }\r\n\r\n public void unsetULogs() {\r\n this.uLogs = null;\r\n }\r\n\r\n /** Returns true if field uLogs is set (has been assigned a value) and false otherwise */\r\n public boolean isSetULogs() {\r\n return this.uLogs != null;\r\n }\r\n\r\n public void setULogsIsSet(boolean value) {\r\n if (!value) {\r\n this.uLogs = null;\r\n }\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case U_LOGS:\r\n if (value == null) {\r\n unsetULogs();\r\n } else {\r\n setULogs((List<String>)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case U_LOGS:\r\n return getULogs();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case U_LOGS:\r\n return isSetULogs();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof addMqinfoToAdminQu_args)\r\n return this.equals((addMqinfoToAdminQu_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(addMqinfoToAdminQu_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_uLogs = true && this.isSetULogs();\r\n boolean that_present_uLogs = true && that.isSetULogs();\r\n if (this_present_uLogs || that_present_uLogs) {\r\n if (!(this_present_uLogs && that_present_uLogs))\r\n return false;\r\n if (!this.uLogs.equals(that.uLogs))\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_uLogs = true && (isSetULogs());\r\n list.add(present_uLogs);\r\n if (present_uLogs)\r\n list.add(uLogs);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(addMqinfoToAdminQu_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetULogs()).compareTo(other.isSetULogs());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetULogs()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.uLogs, other.uLogs);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"addMqinfoToAdminQu_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\"uLogs:\");\r\n if (this.uLogs == null) {\r\n sb.append(\"null\");\r\n } else {\r\n sb.append(this.uLogs);\r\n }\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsStandardSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_argsStandardScheme getScheme() {\r\n return new addMqinfoToAdminQu_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsStandardScheme extends StandardScheme<addMqinfoToAdminQu_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 1: // U_LOGS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {\r\n {\r\n org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();\r\n struct.uLogs = new ArrayList<String>(_list0.size);\r\n String _elem1;\r\n for (int _i2 = 0; _i2 < _list0.size; ++_i2)\r\n {\r\n _elem1 = iprot.readString();\r\n struct.uLogs.add(_elem1);\r\n }\r\n iprot.readListEnd();\r\n }\r\n struct.setULogsIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.uLogs != null) {\r\n oprot.writeFieldBegin(U_LOGS_FIELD_DESC);\r\n {\r\n oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.uLogs.size()));\r\n for (String _iter3 : struct.uLogs)\r\n {\r\n oprot.writeString(_iter3);\r\n }\r\n oprot.writeListEnd();\r\n }\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsTupleSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_argsTupleScheme getScheme() {\r\n return new addMqinfoToAdminQu_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsTupleScheme extends TupleScheme<addMqinfoToAdminQu_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetULogs()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetULogs()) {\r\n {\r\n oprot.writeI32(struct.uLogs.size());\r\n for (String _iter4 : struct.uLogs)\r\n {\r\n oprot.writeString(_iter4);\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n {\r\n org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());\r\n struct.uLogs = new ArrayList<String>(_list5.size);\r\n String _elem6;\r\n for (int _i7 = 0; _i7 < _list5.size; ++_i7)\r\n {\r\n _elem6 = iprot.readString();\r\n struct.uLogs.add(_elem6);\r\n }\r\n }\r\n struct.setULogsIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class addMqinfoToAdminQu_result implements org.apache.thrift.TBase<addMqinfoToAdminQu_result, addMqinfoToAdminQu_result._Fields>, java.io.Serializable, Cloneable, Comparable<addMqinfoToAdminQu_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"addMqinfoToAdminQu_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new addMqinfoToAdminQu_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new addMqinfoToAdminQu_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(addMqinfoToAdminQu_result.class, metaDataMap);\r\n }\r\n\r\n public addMqinfoToAdminQu_result() {\r\n }\r\n\r\n public addMqinfoToAdminQu_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public addMqinfoToAdminQu_result(addMqinfoToAdminQu_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public addMqinfoToAdminQu_result deepCopy() {\r\n return new addMqinfoToAdminQu_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public addMqinfoToAdminQu_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof addMqinfoToAdminQu_result)\r\n return this.equals((addMqinfoToAdminQu_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(addMqinfoToAdminQu_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(addMqinfoToAdminQu_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"addMqinfoToAdminQu_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultStandardSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_resultStandardScheme getScheme() {\r\n return new addMqinfoToAdminQu_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultStandardScheme extends StandardScheme<addMqinfoToAdminQu_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultTupleSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_resultTupleScheme getScheme() {\r\n return new addMqinfoToAdminQu_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultTupleScheme extends TupleScheme<addMqinfoToAdminQu_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class rtcStats_args implements org.apache.thrift.TBase<rtcStats_args, rtcStats_args._Fields>, java.io.Serializable, Cloneable, Comparable<rtcStats_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"rtcStats_args\");\r\n\r\n private static final org.apache.thrift.protocol.TField USER_LOGS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"userLogs\", org.apache.thrift.protocol.TType.LIST, (short)1);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new rtcStats_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new rtcStats_argsTupleSchemeFactory());\r\n }\r\n\r\n public List<String> userLogs; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n USER_LOGS((short)1, \"userLogs\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 1: // USER_LOGS\r\n return USER_LOGS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.USER_LOGS, new org.apache.thrift.meta_data.FieldMetaData(\"userLogs\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(rtcStats_args.class, metaDataMap);\r\n }\r\n\r\n public rtcStats_args() {\r\n }\r\n\r\n public rtcStats_args(\r\n List<String> userLogs)\r\n {\r\n this();\r\n this.userLogs = userLogs;\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public rtcStats_args(rtcStats_args other) {\r\n if (other.isSetUserLogs()) {\r\n List<String> __this__userLogs = new ArrayList<String>(other.userLogs);\r\n this.userLogs = __this__userLogs;\r\n }\r\n }\r\n\r\n public rtcStats_args deepCopy() {\r\n return new rtcStats_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n this.userLogs = null;\r\n }\r\n\r\n public int getUserLogsSize() {\r\n return (this.userLogs == null) ? 0 : this.userLogs.size();\r\n }\r\n\r\n public java.util.Iterator<String> getUserLogsIterator() {\r\n return (this.userLogs == null) ? null : this.userLogs.iterator();\r\n }\r\n\r\n public void addToUserLogs(String elem) {\r\n if (this.userLogs == null) {\r\n this.userLogs = new ArrayList<String>();\r\n }\r\n this.userLogs.add(elem);\r\n }\r\n\r\n public List<String> getUserLogs() {\r\n return this.userLogs;\r\n }\r\n\r\n public rtcStats_args setUserLogs(List<String> userLogs) {\r\n this.userLogs = userLogs;\r\n return this;\r\n }\r\n\r\n public void unsetUserLogs() {\r\n this.userLogs = null;\r\n }\r\n\r\n /** Returns true if field userLogs is set (has been assigned a value) and false otherwise */\r\n public boolean isSetUserLogs() {\r\n return this.userLogs != null;\r\n }\r\n\r\n public void setUserLogsIsSet(boolean value) {\r\n if (!value) {\r\n this.userLogs = null;\r\n }\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case USER_LOGS:\r\n if (value == null) {\r\n unsetUserLogs();\r\n } else {\r\n setUserLogs((List<String>)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case USER_LOGS:\r\n return getUserLogs();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case USER_LOGS:\r\n return isSetUserLogs();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof rtcStats_args)\r\n return this.equals((rtcStats_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(rtcStats_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_userLogs = true && this.isSetUserLogs();\r\n boolean that_present_userLogs = true && that.isSetUserLogs();\r\n if (this_present_userLogs || that_present_userLogs) {\r\n if (!(this_present_userLogs && that_present_userLogs))\r\n return false;\r\n if (!this.userLogs.equals(that.userLogs))\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_userLogs = true && (isSetUserLogs());\r\n list.add(present_userLogs);\r\n if (present_userLogs)\r\n list.add(userLogs);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(rtcStats_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetUserLogs()).compareTo(other.isSetUserLogs());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetUserLogs()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.userLogs, other.userLogs);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"rtcStats_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\"userLogs:\");\r\n if (this.userLogs == null) {\r\n sb.append(\"null\");\r\n } else {\r\n sb.append(this.userLogs);\r\n }\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class rtcStats_argsStandardSchemeFactory implements SchemeFactory {\r\n public rtcStats_argsStandardScheme getScheme() {\r\n return new rtcStats_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_argsStandardScheme extends StandardScheme<rtcStats_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 1: // USER_LOGS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {\r\n {\r\n org.apache.thrift.protocol.TList _list8 = iprot.readListBegin();\r\n struct.userLogs = new ArrayList<String>(_list8.size);\r\n String _elem9;\r\n for (int _i10 = 0; _i10 < _list8.size; ++_i10)\r\n {\r\n _elem9 = iprot.readString();\r\n struct.userLogs.add(_elem9);\r\n }\r\n iprot.readListEnd();\r\n }\r\n struct.setUserLogsIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.userLogs != null) {\r\n oprot.writeFieldBegin(USER_LOGS_FIELD_DESC);\r\n {\r\n oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.userLogs.size()));\r\n for (String _iter11 : struct.userLogs)\r\n {\r\n oprot.writeString(_iter11);\r\n }\r\n oprot.writeListEnd();\r\n }\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class rtcStats_argsTupleSchemeFactory implements SchemeFactory {\r\n public rtcStats_argsTupleScheme getScheme() {\r\n return new rtcStats_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_argsTupleScheme extends TupleScheme<rtcStats_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetUserLogs()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetUserLogs()) {\r\n {\r\n oprot.writeI32(struct.userLogs.size());\r\n for (String _iter12 : struct.userLogs)\r\n {\r\n oprot.writeString(_iter12);\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n {\r\n org.apache.thrift.protocol.TList _list13 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());\r\n struct.userLogs = new ArrayList<String>(_list13.size);\r\n String _elem14;\r\n for (int _i15 = 0; _i15 < _list13.size; ++_i15)\r\n {\r\n _elem14 = iprot.readString();\r\n struct.userLogs.add(_elem14);\r\n }\r\n }\r\n struct.setUserLogsIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class rtcStats_result implements org.apache.thrift.TBase<rtcStats_result, rtcStats_result._Fields>, java.io.Serializable, Cloneable, Comparable<rtcStats_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"rtcStats_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new rtcStats_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new rtcStats_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(rtcStats_result.class, metaDataMap);\r\n }\r\n\r\n public rtcStats_result() {\r\n }\r\n\r\n public rtcStats_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public rtcStats_result(rtcStats_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public rtcStats_result deepCopy() {\r\n return new rtcStats_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public rtcStats_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof rtcStats_result)\r\n return this.equals((rtcStats_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(rtcStats_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(rtcStats_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"rtcStats_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class rtcStats_resultStandardSchemeFactory implements SchemeFactory {\r\n public rtcStats_resultStandardScheme getScheme() {\r\n return new rtcStats_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_resultStandardScheme extends StandardScheme<rtcStats_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class rtcStats_resultTupleSchemeFactory implements SchemeFactory {\r\n public rtcStats_resultTupleScheme getScheme() {\r\n return new rtcStats_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_resultTupleScheme extends TupleScheme<rtcStats_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class batchStats_args implements org.apache.thrift.TBase<batchStats_args, batchStats_args._Fields>, java.io.Serializable, Cloneable, Comparable<batchStats_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"batchStats_args\");\r\n\r\n private static final org.apache.thrift.protocol.TField START_FIELD_DESC = new org.apache.thrift.protocol.TField(\"start\", org.apache.thrift.protocol.TType.I32, (short)1);\r\n private static final org.apache.thrift.protocol.TField SIZE_FIELD_DESC = new org.apache.thrift.protocol.TField(\"size\", org.apache.thrift.protocol.TType.I32, (short)2);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new batchStats_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new batchStats_argsTupleSchemeFactory());\r\n }\r\n\r\n public int start; // required\r\n public int size; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n START((short)1, \"start\"),\r\n SIZE((short)2, \"size\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 1: // START\r\n return START;\r\n case 2: // SIZE\r\n return SIZE;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __START_ISSET_ID = 0;\r\n private static final int __SIZE_ISSET_ID = 1;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.START, new org.apache.thrift.meta_data.FieldMetaData(\"start\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n tmpMap.put(_Fields.SIZE, new org.apache.thrift.meta_data.FieldMetaData(\"size\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(batchStats_args.class, metaDataMap);\r\n }\r\n\r\n public batchStats_args() {\r\n }\r\n\r\n public batchStats_args(\r\n int start,\r\n int size)\r\n {\r\n this();\r\n this.start = start;\r\n setStartIsSet(true);\r\n this.size = size;\r\n setSizeIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public batchStats_args(batchStats_args other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.start = other.start;\r\n this.size = other.size;\r\n }\r\n\r\n public batchStats_args deepCopy() {\r\n return new batchStats_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setStartIsSet(false);\r\n this.start = 0;\r\n setSizeIsSet(false);\r\n this.size = 0;\r\n }\r\n\r\n public int getStart() {\r\n return this.start;\r\n }\r\n\r\n public batchStats_args setStart(int start) {\r\n this.start = start;\r\n setStartIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetStart() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __START_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field start is set (has been assigned a value) and false otherwise */\r\n public boolean isSetStart() {\r\n return EncodingUtils.testBit(__isset_bitfield, __START_ISSET_ID);\r\n }\r\n\r\n public void setStartIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __START_ISSET_ID, value);\r\n }\r\n\r\n public int getSize() {\r\n return this.size;\r\n }\r\n\r\n public batchStats_args setSize(int size) {\r\n this.size = size;\r\n setSizeIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSize() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SIZE_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field size is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSize() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SIZE_ISSET_ID);\r\n }\r\n\r\n public void setSizeIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SIZE_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case START:\r\n if (value == null) {\r\n unsetStart();\r\n } else {\r\n setStart((Integer)value);\r\n }\r\n break;\r\n\r\n case SIZE:\r\n if (value == null) {\r\n unsetSize();\r\n } else {\r\n setSize((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case START:\r\n return getStart();\r\n\r\n case SIZE:\r\n return getSize();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case START:\r\n return isSetStart();\r\n case SIZE:\r\n return isSetSize();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof batchStats_args)\r\n return this.equals((batchStats_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(batchStats_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_start = true;\r\n boolean that_present_start = true;\r\n if (this_present_start || that_present_start) {\r\n if (!(this_present_start && that_present_start))\r\n return false;\r\n if (this.start != that.start)\r\n return false;\r\n }\r\n\r\n boolean this_present_size = true;\r\n boolean that_present_size = true;\r\n if (this_present_size || that_present_size) {\r\n if (!(this_present_size && that_present_size))\r\n return false;\r\n if (this.size != that.size)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_start = true;\r\n list.add(present_start);\r\n if (present_start)\r\n list.add(start);\r\n\r\n boolean present_size = true;\r\n list.add(present_size);\r\n if (present_size)\r\n list.add(size);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(batchStats_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetStart()).compareTo(other.isSetStart());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetStart()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.start, other.start);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n lastComparison = Boolean.valueOf(isSetSize()).compareTo(other.isSetSize());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSize()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.size, other.size);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"batchStats_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\"start:\");\r\n sb.append(this.start);\r\n first = false;\r\n if (!first) sb.append(\", \");\r\n sb.append(\"size:\");\r\n sb.append(this.size);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class batchStats_argsStandardSchemeFactory implements SchemeFactory {\r\n public batchStats_argsStandardScheme getScheme() {\r\n return new batchStats_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_argsStandardScheme extends StandardScheme<batchStats_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, batchStats_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 1: // START\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.start = iprot.readI32();\r\n struct.setStartIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n case 2: // SIZE\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.size = iprot.readI32();\r\n struct.setSizeIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, batchStats_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldBegin(START_FIELD_DESC);\r\n oprot.writeI32(struct.start);\r\n oprot.writeFieldEnd();\r\n oprot.writeFieldBegin(SIZE_FIELD_DESC);\r\n oprot.writeI32(struct.size);\r\n oprot.writeFieldEnd();\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class batchStats_argsTupleSchemeFactory implements SchemeFactory {\r\n public batchStats_argsTupleScheme getScheme() {\r\n return new batchStats_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_argsTupleScheme extends TupleScheme<batchStats_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, batchStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetStart()) {\r\n optionals.set(0);\r\n }\r\n if (struct.isSetSize()) {\r\n optionals.set(1);\r\n }\r\n oprot.writeBitSet(optionals, 2);\r\n if (struct.isSetStart()) {\r\n oprot.writeI32(struct.start);\r\n }\r\n if (struct.isSetSize()) {\r\n oprot.writeI32(struct.size);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, batchStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(2);\r\n if (incoming.get(0)) {\r\n struct.start = iprot.readI32();\r\n struct.setStartIsSet(true);\r\n }\r\n if (incoming.get(1)) {\r\n struct.size = iprot.readI32();\r\n struct.setSizeIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class batchStats_result implements org.apache.thrift.TBase<batchStats_result, batchStats_result._Fields>, java.io.Serializable, Cloneable, Comparable<batchStats_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"batchStats_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new batchStats_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new batchStats_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(batchStats_result.class, metaDataMap);\r\n }\r\n\r\n public batchStats_result() {\r\n }\r\n\r\n public batchStats_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public batchStats_result(batchStats_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public batchStats_result deepCopy() {\r\n return new batchStats_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public batchStats_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof batchStats_result)\r\n return this.equals((batchStats_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(batchStats_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(batchStats_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"batchStats_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class batchStats_resultStandardSchemeFactory implements SchemeFactory {\r\n public batchStats_resultStandardScheme getScheme() {\r\n return new batchStats_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_resultStandardScheme extends StandardScheme<batchStats_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, batchStats_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, batchStats_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class batchStats_resultTupleSchemeFactory implements SchemeFactory {\r\n public batchStats_resultTupleScheme getScheme() {\r\n return new batchStats_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_resultTupleScheme extends TupleScheme<batchStats_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, batchStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, batchStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getAdminNodeId_args implements org.apache.thrift.TBase<getAdminNodeId_args, getAdminNodeId_args._Fields>, java.io.Serializable, Cloneable, Comparable<getAdminNodeId_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getAdminNodeId_args\");\r\n\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getAdminNodeId_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getAdminNodeId_argsTupleSchemeFactory());\r\n }\r\n\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n;\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getAdminNodeId_args.class, metaDataMap);\r\n }\r\n\r\n public getAdminNodeId_args() {\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getAdminNodeId_args(getAdminNodeId_args other) {\r\n }\r\n\r\n public getAdminNodeId_args deepCopy() {\r\n return new getAdminNodeId_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getAdminNodeId_args)\r\n return this.equals((getAdminNodeId_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getAdminNodeId_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getAdminNodeId_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getAdminNodeId_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_argsStandardSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_argsStandardScheme getScheme() {\r\n return new getAdminNodeId_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_argsStandardScheme extends StandardScheme<getAdminNodeId_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getAdminNodeId_argsTupleSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_argsTupleScheme getScheme() {\r\n return new getAdminNodeId_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_argsTupleScheme extends TupleScheme<getAdminNodeId_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getAdminNodeId_result implements org.apache.thrift.TBase<getAdminNodeId_result, getAdminNodeId_result._Fields>, java.io.Serializable, Cloneable, Comparable<getAdminNodeId_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getAdminNodeId_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getAdminNodeId_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getAdminNodeId_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getAdminNodeId_result.class, metaDataMap);\r\n }\r\n\r\n public getAdminNodeId_result() {\r\n }\r\n\r\n public getAdminNodeId_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getAdminNodeId_result(getAdminNodeId_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public getAdminNodeId_result deepCopy() {\r\n return new getAdminNodeId_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public getAdminNodeId_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getAdminNodeId_result)\r\n return this.equals((getAdminNodeId_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getAdminNodeId_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getAdminNodeId_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getAdminNodeId_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_resultStandardSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_resultStandardScheme getScheme() {\r\n return new getAdminNodeId_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_resultStandardScheme extends StandardScheme<getAdminNodeId_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getAdminNodeId_resultTupleSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_resultTupleScheme getScheme() {\r\n return new getAdminNodeId_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_resultTupleScheme extends TupleScheme<getAdminNodeId_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getHealthStatus_args implements org.apache.thrift.TBase<getHealthStatus_args, getHealthStatus_args._Fields>, java.io.Serializable, Cloneable, Comparable<getHealthStatus_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getHealthStatus_args\");\r\n\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getHealthStatus_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getHealthStatus_argsTupleSchemeFactory());\r\n }\r\n\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n;\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getHealthStatus_args.class, metaDataMap);\r\n }\r\n\r\n public getHealthStatus_args() {\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getHealthStatus_args(getHealthStatus_args other) {\r\n }\r\n\r\n public getHealthStatus_args deepCopy() {\r\n return new getHealthStatus_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getHealthStatus_args)\r\n return this.equals((getHealthStatus_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getHealthStatus_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getHealthStatus_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getHealthStatus_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getHealthStatus_argsStandardSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_argsStandardScheme getScheme() {\r\n return new getHealthStatus_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_argsStandardScheme extends StandardScheme<getHealthStatus_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getHealthStatus_argsTupleSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_argsTupleScheme getScheme() {\r\n return new getHealthStatus_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_argsTupleScheme extends TupleScheme<getHealthStatus_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getHealthStatus_result implements org.apache.thrift.TBase<getHealthStatus_result, getHealthStatus_result._Fields>, java.io.Serializable, Cloneable, Comparable<getHealthStatus_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getHealthStatus_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getHealthStatus_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getHealthStatus_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getHealthStatus_result.class, metaDataMap);\r\n }\r\n\r\n public getHealthStatus_result() {\r\n }\r\n\r\n public getHealthStatus_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getHealthStatus_result(getHealthStatus_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public getHealthStatus_result deepCopy() {\r\n return new getHealthStatus_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public getHealthStatus_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getHealthStatus_result)\r\n return this.equals((getHealthStatus_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getHealthStatus_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getHealthStatus_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getHealthStatus_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getHealthStatus_resultStandardSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_resultStandardScheme getScheme() {\r\n return new getHealthStatus_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_resultStandardScheme extends StandardScheme<getHealthStatus_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getHealthStatus_resultTupleSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_resultTupleScheme getScheme() {\r\n return new getHealthStatus_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_resultTupleScheme extends TupleScheme<getHealthStatus_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getJobStatus_args implements org.apache.thrift.TBase<getJobStatus_args, getJobStatus_args._Fields>, java.io.Serializable, Cloneable, Comparable<getJobStatus_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getJobStatus_args\");\r\n\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getJobStatus_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getJobStatus_argsTupleSchemeFactory());\r\n }\r\n\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n;\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getJobStatus_args.class, metaDataMap);\r\n }\r\n\r\n public getJobStatus_args() {\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getJobStatus_args(getJobStatus_args other) {\r\n }\r\n\r\n public getJobStatus_args deepCopy() {\r\n return new getJobStatus_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getJobStatus_args)\r\n return this.equals((getJobStatus_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getJobStatus_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getJobStatus_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getJobStatus_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getJobStatus_argsStandardSchemeFactory implements SchemeFactory {\r\n public getJobStatus_argsStandardScheme getScheme() {\r\n return new getJobStatus_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_argsStandardScheme extends StandardScheme<getJobStatus_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getJobStatus_argsTupleSchemeFactory implements SchemeFactory {\r\n public getJobStatus_argsTupleScheme getScheme() {\r\n return new getJobStatus_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_argsTupleScheme extends TupleScheme<getJobStatus_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getJobStatus_result implements org.apache.thrift.TBase<getJobStatus_result, getJobStatus_result._Fields>, java.io.Serializable, Cloneable, Comparable<getJobStatus_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getJobStatus_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getJobStatus_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getJobStatus_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getJobStatus_result.class, metaDataMap);\r\n }\r\n\r\n public getJobStatus_result() {\r\n }\r\n\r\n public getJobStatus_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getJobStatus_result(getJobStatus_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public getJobStatus_result deepCopy() {\r\n return new getJobStatus_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public getJobStatus_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getJobStatus_result)\r\n return this.equals((getJobStatus_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getJobStatus_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getJobStatus_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getJobStatus_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getJobStatus_resultStandardSchemeFactory implements SchemeFactory {\r\n public getJobStatus_resultStandardScheme getScheme() {\r\n return new getJobStatus_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_resultStandardScheme extends StandardScheme<getJobStatus_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getJobStatus_resultTupleSchemeFactory implements SchemeFactory {\r\n public getJobStatus_resultTupleScheme getScheme() {\r\n return new getJobStatus_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_resultTupleScheme extends TupleScheme<getJobStatus_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r", "public interface StreamLogParser {\n\t/**\n\t * 自定义实现:从指定队列dataQu中,获取指定数目curNum的单条日志信息, \n\t * 加工成每条信息类似: {uid:设备ID或通行证ID,data:{view:{docIds},collect:{docIds}}}形式的信息列表\n\t * @param dataQu\n\t * @param curNum\n\t * @return\n\t */\n\tList<String> parseLogs(ConcurrentLinkedQueue<String> dataQu, int curNum);\n}", "public class RabbitMqCollect extends MqConsumer{\n\tprivate Connection connection;\n\tprivate Channel channel;\n\tprivate QueueingConsumer consumer;\n\t\n\tpublic RabbitMqCollect(){\n\t\tsuper();\n\t\tthis.init();\n\t}\n\t\n\tpublic void init(){\n\t\tConnectionFactory factory = new ConnectionFactory();\n\t\tfactory.setPort(Constants.mqPort);\n\t\tfactory.setHost(Constants.mqHost);\n\t factory.setUsername(Constants.mqUser);\n\t factory.setPassword(Constants.mqPswd);\n\t factory.setVirtualHost(Constants.mqVhost);\n\t try {\n\t \tconnection = factory.newConnection();\n\t \tchannel = connection.createChannel();\n\t\t} catch (TimeoutException e) {\n\t\t\te.printStackTrace();\n\t\t}catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t consumer = new QueueingConsumer(channel);\n\t\ttry {\n\t\t\tchannel.basicConsume(Constants.mqClickFirstQu, true, consumer);\n\t\t\tchannel.basicConsume(Constants.mqClickSecondQu, true, consumer);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\t/**\n\t * 为保证数据实时收集并及时提交到任务计算节点,务必将收集的消息,调用super.mqTimer.parseMqText(routingKey, message);\n\t */\n\tpublic void run(){\n\t\tQueueingConsumer.Delivery delivery = null;\n\t\tString message = null, routingKey=null;\n\t\twhile(true){\n\t\t\ttry {\n\t\t\t\tdelivery = consumer.nextDelivery();\n\t\t\t} catch (ShutdownSignalException | ConsumerCancelledException\n\t\t\t\t\t| InterruptedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tmessage = new String(delivery.getBody(),\"UTF-8\");\n\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\troutingKey = delivery.getEnvelope().getRoutingKey(); // 可获取路由关键词\n\t\t\tsuper.mqTimer.parseMqText(routingKey, message);\n\t\t\tmessage = null;\n\t\t}\n\t}\n\t\n\t/**\n * 关闭channel和connection。并非必须,因为隐含是自动调用的。\n * @throws IOException\n */\n public void close() throws IOException{\n try {\n\t\t\tthis.channel.close();\n } catch (TimeoutException e) {\n\t\t\te.printStackTrace();\n }\n this.connection.close();\n }\n\n//\tpublic static void main(String[] args) {\n//\t\tRabbitMqCollect rmc = new RabbitMqCollect();\n//\t\trmc.run();\n//\t}\n\n}", "public class RtdcAdminService implements Iface {\n\n\t@Override\n\tpublic int addMqinfoToAdminQu(List<String> uLogs) throws TException {\n\t\tboolean rt = AdminNodeTimer.addSteamData(uLogs);\n\t\tif(rt)\n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int rtcStats(List<String> userLogs) throws TException {\n\t\t\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int batchStats(int start, int size) throws TException {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getAdminNodeId() throws TException {\n\t\t\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getHealthStatus() throws TException {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic int getJobStatus() throws TException {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n}", "public class AdminNodeTimer extends TimerTask{\r\n\tprotected FileUtil fu = new FileUtil();\r\n\tprotected static ConcurrentLinkedQueue<String> dataQu = new ConcurrentLinkedQueue<String>();\r\n\tprivate static TreeMap<Long,Integer> delayTaskIdDataNums = new TreeMap<Long,Integer>();\r\n\tprotected static ConcurrentLinkedQueue<List<String>> memDelayQu = new ConcurrentLinkedQueue<List<String>>();\r\n\tprivate static int minBathJobStatus = 0;\r\n\tprivate static StreamLogParser slp;\r\n\tprivate AdminNodeService ans = new AdminNodeService();\r\n\tprivate long timerNum = 0;\r\n\t\r\n\tpublic static void setStreamLogParser(StreamLogParser streamLogParser){\r\n\t\tslp = streamLogParser;\r\n\t}\r\n\t\r\n\tpublic static boolean addSteamData(List<String> uLogs){\r\n\t\treturn dataQu.addAll(uLogs);\r\n\t}\r\n\t\r\n\tpublic static int getJobStatus(){\r\n\t\treturn minBathJobStatus;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tint curLogNum = dataQu.size();\r\n\t\tSystem.out.println(ConfigProperty.getCurDateTime()+\" curLogNum : \"+curLogNum);\r\n\t\tif(curLogNum>0){\r\n\t\t\tList<String> userActionList = slp.parseLogs(dataQu, curLogNum);\r\n\t\t\tint memDelayTaskNum = memDelayQu.size();\r\n\t\t\tif(minBathJobStatus==0){\r\n\t\t\t\tif(memDelayTaskNum>0){\r\n\t\t\t\t\tans.setUserActions(memDelayQu.poll());\r\n\t\t\t\t\tnew Thread(new AdminConsole()).start();\r\n\t\t\t\t\tif(memDelayTaskNum<Constants.maxDelayTaskNum){\r\n\t\t\t\t\t\tif(delayTaskIdDataNums.size()>0){\r\n\t\t\t\t\t\t\twhile(memDelayQu.size()<Constants.maxDelayTaskNum && delayTaskIdDataNums.size()>0){\r\n\t\t\t\t\t\t\t\tString taskFile = Constants.delayTaskDir + delayTaskIdDataNums.pollFirstEntry().getKey() + Constants.delayTaskFileSurfix;\r\n\t\t\t\t\t\t\t\tList<String> rtJsonList = fu.readActions(taskFile);\r\n\t\t\t\t\t\t\t\tif(rtJsonList!=null){\r\n\t\t\t\t\t\t\t\t\tmemDelayQu.add(rtJsonList);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tfu.delActionFile(taskFile);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(memDelayQu.size()<Constants.maxDelayTaskNum){\r\n\t\t\t\t\t\t\tmemDelayQu.add(userActionList);\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\tlong rtNum = ans.getCurrentTime();\r\n\t\t\t\t\t\t\tdelayTaskIdDataNums.put(rtNum, curLogNum);\r\n\t\t\t\t\t\t\tfu.writeActions(userActionList, Constants.delayTaskDir+rtNum+Constants.delayTaskFileSurfix);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tlong rtNum = ans.getCurrentTime();\r\n\t\t\t\t\t\tdelayTaskIdDataNums.put(rtNum, curLogNum);\r\n\t\t\t\t\t\tfu.writeActions(userActionList, Constants.delayTaskDir+rtNum+Constants.delayTaskFileSurfix);\r\n\t\t\t\t\t}\r\n\t\t\t\t}else{\r\n\t\t\t\t\tans.setUserActions(userActionList);\r\n\t\t\t\t\tnew Thread(new AdminConsole()).start();\r\n\t\t\t\t}\r\n\t\t\t}else{\r\n\t\t\t\tif(memDelayTaskNum<Constants.maxDelayTaskNum){\r\n\t\t\t\t\tmemDelayQu.add(userActionList);\r\n\t\t\t\t}else{\r\n\t\t\t\t\tlong rtNum = ans.getCurrentTime();\r\n\t\t\t\t\tdelayTaskIdDataNums.put(rtNum, curLogNum);\r\n\t\t\t\t\tfu.writeActions(userActionList, Constants.delayTaskDir+rtNum+Constants.delayTaskFileSurfix);\r\n\t\t\t\t}\r\n\t\t\t\tSystem.out.println(ConfigProperty.getCurDateTime()+\" 上次计算任务还没有结束\");\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(++timerNum%100==0){\r\n\t\t\tSystem.out.println(\"分布式计算任务周期频率更新 \" +timerNum);\r\n\t\t\tSystem.gc();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void reRun(){\r\n\t\tif(memDelayQu.size()>0){\r\n\t\t\tSystem.out.println(\"AdminNodeTimer reRun method ......\"+memDelayQu.size());\r\n\t\t\tans.setUserActions(memDelayQu.poll());\r\n\t\t\tnew Thread(new AdminConsole()).start();\r\n\t\t\tif(delayTaskIdDataNums.size()>0){\r\n\t\t\t\tString taskFile = Constants.delayTaskDir + delayTaskIdDataNums.pollFirstEntry().getKey() + Constants.delayTaskFileSurfix;\r\n\t\t\t\tList<String> rtJsonList = fu.readActions(taskFile);\r\n\t\t\t\tif(rtJsonList!=null){\r\n\t\t\t\t\tmemDelayQu.add(rtJsonList);\r\n\t\t\t\t}\r\n\t\t\t\tfu.delActionFile(taskFile); \r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprotected class AdminConsole implements Runnable{\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\t\t\tminBathJobStatus = 1;\r\n\t\t\ttry{\r\n\t\t\t\tans.run();\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tSystem.err.println(\"分布式计算任务管理服务错误: \"+e.getMessage());\r\n\t\t\t}\r\n\t\t\tminBathJobStatus = 0;\r\n\t\t\treRun();\r\n\t\t}\r\n\t}\r\n\r\n}\r", "public class ConfigProperty {\r\n\t\r\n\tprivate static Properties dbProps;\r\n\t\r\n\tprivate static synchronized void init_prop(){\r\n\t\tdbProps = new Properties();\t\r\n\t\tString path = ConfigProperty.class.getClassLoader().getResource(\"\").getPath();\r\n\t\tpath = path.replaceAll(\"%20\", \" \");\r\n\t\tInputStream fileinputstream = null;\r\n\t\ttry {\r\n\t\t\tfileinputstream = new FileInputStream(path+\"rtc_conf.properties\");\r\n\t\t} catch (FileNotFoundException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tdbProps.load(fileinputstream);\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.err.println(\"不能读取数据库配置文件, 请确保rtc_conf.properties在CLASSPATH指定的路径中!\");\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static Properties getProps(){\r\n\t\tif(dbProps==null)\r\n\t\t\tinit_prop();\r\n\t\treturn dbProps;\r\n\t}\r\n\t\r\n\tpublic static String getCurDateTime() {\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyyMMddHHmmss\");//\"yyyyMMddHHmmss\"\r\n\t\treturn df.format(new Date());\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"cluterName\"));\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"clusterHosts\"));\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"serverPort\"));\r\n\t\t\r\n\t\tSystem.out.println(\"=============================================\");\r\n\t\t\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"minThreadNum\"));\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"maxThreadNum\"));\r\n\t\t\r\n\t}\r\n\t\r\n}\r", "public class Constants {\n\t// es cluster config\n\tpublic static String esClusterName = ConfigProperty.getProps().getProperty(\"cluterName\");\n\tpublic static String esClusterHosts = ConfigProperty.getProps().getProperty(\"clusterHosts\");\n\t\n\t//rabbitmq config\n\tpublic final static String mqHost = ConfigProperty.getProps().getProperty(\"mq.host\");\n\tpublic final static int mqPort = Integer.parseInt(ConfigProperty.getProps().getProperty(\"mq.port\"));\n\tpublic final static String mqUser = ConfigProperty.getProps().getProperty(\"mq.user\");\n\tpublic final static String mqPswd = ConfigProperty.getProps().getProperty(\"mq.pswd\");\n\tpublic final static String mqVhost = ConfigProperty.getProps().getProperty(\"mq.vhost\");\n\tpublic final static String mqExchange = ConfigProperty.getProps().getProperty(\"mq.exchange\");\n\tpublic final static String mqClickKey = ConfigProperty.getProps().getProperty(\"mq.clickRoutKey\");\n\tpublic final static String mqClickFirstQu = ConfigProperty.getProps().getProperty(\"mq.clickQueue1\");\n\tpublic final static String mqClickSecondQu = ConfigProperty.getProps().getProperty(\"mq.clickQueue2\");\n\t\n\t//kafka config\n\tpublic final static String kfZkServers = ConfigProperty.getProps().getProperty(\"kfZkServers\");\n\tpublic final static String kfGroupId = ConfigProperty.getProps().getProperty(\"kfGroupId\");\n\tpublic final static String kfAutoOffsetReset = ConfigProperty.getProps().getProperty(\"kfAutoOffsetReset\");\n\tpublic final static String kfTopic = ConfigProperty.getProps().getProperty(\"kfTopic\");\n\t\n\t//Timer config (unit : seconds)\n\tpublic final static int mqDoBatchTimer = Integer.parseInt(ConfigProperty.getProps().getProperty(\"mqDoBatchTimer\"));\n\t\n\t//AdminNode hosts and ports for DataCollectNode using\n\tpublic final static String adminNodeHosts = ConfigProperty.getProps().getProperty(\"adminNodeHosts\");\n\t\n\t//AdminNode server port\n\tpublic final static int adminNodePort = Integer.parseInt(ConfigProperty.getProps().getProperty(\"adminNodePort\"));\n\t\n\t//JobNode hosts and ports for AdminNode using\n\tpublic final static String jobNodeHosts = ConfigProperty.getProps().getProperty(\"jobNodeHosts\");\n\t\n\t//JobNode server port\n\tpublic final static int jobNodePort = Integer.parseInt(ConfigProperty.getProps().getProperty(\"jobNodePort\"));\n\t\n\t//rtc timer\n\tpublic final static int rtcPeriodSeconds = Integer.parseInt(ConfigProperty.getProps().getProperty(\"rtcPeriodSeconds\"));\n\t\n\tpublic final static int adminNodeId = Integer.parseInt(ConfigProperty.getProps().getProperty(\"adminNodeId\"));\n\t\n\tpublic final static int minJobBatchNum = Integer.parseInt(ConfigProperty.getProps().getProperty(\"minJobBatchNum\"));\n\tpublic final static int atomJobBatchNum = Integer.parseInt(ConfigProperty.getProps().getProperty(\"atomJobBatchNum\"));\n\t\n\t//redis cluster config\n\tpublic final static String redisHosts = ConfigProperty.getProps().getProperty(\"redisHosts\");\n\tpublic final static String redisPswd = ConfigProperty.getProps().getProperty(\"redisPswd\");\n\t\n\tpublic final static String delayTaskDir = ConfigProperty.getProps().getProperty(\"delayTaskDir\");\n\tpublic final static String delayTaskFileSurfix = ConfigProperty.getProps().getProperty(\"delayTaskFileSurfix\");\n\tpublic final static int maxDelayTaskNum = Integer.parseInt(ConfigProperty.getProps().getProperty(\"maxDelayTaskNum\"));\n\t\n}" ]
import java.util.Timer; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TTransportException; import org.light.rtc.api.TDssService; import org.light.rtc.base.StreamLogParser; import org.light.rtc.mq.RabbitMqCollect; import org.light.rtc.service.RtdcAdminService; import org.light.rtc.timer.AdminNodeTimer; import org.light.rtc.util.ConfigProperty; import org.light.rtc.util.Constants;
package org.light.rtc.admin; public class AdminNodeRabbitMqRun { /** * your self defending function for parsing your data stream logs * @param slp */ public void setSteamParser(StreamLogParser slp){ AdminNodeTimer.setStreamLogParser(slp); } private class DataCollect implements Runnable{ @Override public void run() { RabbitMqCollect rmc = new RabbitMqCollect(); rmc.run(); } } public void run(){ this.adminJobTImer(); new Thread(new DataCollect()).start(); RtdcAdminService rss = new RtdcAdminService(); TDssService.Processor<RtdcAdminService> tp = new TDssService.Processor<RtdcAdminService>(rss); TServerTransport serverTransport = null; try { serverTransport = new TServerSocket(Constants.adminNodePort); } catch (TTransportException e) { e.printStackTrace(); } TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(serverTransport); tArgs.maxWorkerThreads(1000); tArgs.minWorkerThreads(10); tArgs.processor(tp); TCompactProtocol.Factory portFactory = new TCompactProtocol.Factory(); tArgs.protocolFactory(portFactory); TServer tServer = new TThreadPoolServer(tArgs);
System.out.println(ConfigProperty.getCurDateTime()+"......轻量级实时计算框架任务管理节点(通过RabbitMq整合CN)服务启动......");
5
dmillerw/RemoteIO
src/main/java/me/dmillerw/remoteio/core/proxy/ClientProxy.java
[ "@Mod(modid = ModInfo.MOD_ID, name = ModInfo.MOD_NAME, version = ModInfo.MOD_VERSION, dependencies = \"required-after:Forge@[12.18.2.2099,)\")\npublic class RemoteIO {\n\n @Mod.Instance(\"remoteio\")\n public static RemoteIO instance;\n\n @SidedProxy(\n serverSide = ModInfo.CORE_PACKAGE + \".core.proxy.CommonProxy\",\n clientSide = ModInfo.CORE_PACKAGE + \".core.proxy.ClientProxy\")\n public static IProxy proxy;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n proxy.preInit(event);\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.init(event);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n }\n\n @Mod.EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n FrequencyRegistry.load(new File(DimensionManager.getCurrentSaveRootDirectory(), \"SavedFrequencies.cfg\"));\n }\n\n @Mod.EventHandler\n public void serverStopping(FMLServerStoppingEvent event) {\n FrequencyRegistry.save(new File(DimensionManager.getCurrentSaveRootDirectory(), \"SavedFrequencies.cfg\"));\n }\n}", "public class BlockRemoteInterface extends Block implements ITileEntityProvider {\n\n public static final RenderStateProperty RENDER_STATE = new RenderStateProperty(\"render_state\");\n\n public BlockRemoteInterface() {\n super(Material.IRON);\n\n setUnlocalizedName(ModInfo.MOD_ID + \":block.remote_interface\");\n setDefaultState(this.blockState.getBaseState());\n setCreativeTab(ModTab.TAB);\n }\n\n @Override\n protected BlockStateContainer createBlockState() {\n return new ExtendedBlockState(this, new IProperty[] {}, new IUnlistedProperty[] {RENDER_STATE});\n }\n\n @Override\n public IBlockState getStateFromMeta(int meta) {\n return getDefaultState();\n }\n\n @Override\n public int getMetaFromState(IBlockState state) {\n return 0;\n }\n\n @Override\n public TileEntity createNewTileEntity(World worldIn, int meta) {\n return new TileRemoteInterface();\n }\n\n @Override\n public boolean isOpaqueCube(IBlockState state)\n {\n return false;\n }\n\n @Override\n public boolean isFullCube(IBlockState state)\n {\n return false;\n }\n\n @Override\n public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) {\n return true;\n }\n\n @Override\n public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) {\n return true;\n }\n\n @Override\n public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {\n TileEntity tile = worldIn.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n TileRemoteInterface remote = (TileRemoteInterface) tile;\n if (playerIn.isSneaking()) {\n playerIn.openGui(RemoteIO.instance, 0, worldIn, pos.getX(), pos.getY(), pos.getZ());\n return true;\n } else {\n IBlockState connected = remote.getRemoteState();\n if (connected == null) {\n return false;\n }\n\n RemoteIO.proxy.onBlockActivated(worldIn, remote.getRemotePosition(), connected, playerIn, hand, null, side, hitX, hitY, hitZ);\n\n return true;\n }\n }\n return false;\n }\n\n @Override\n public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn) {\n TileEntity tile = worldIn.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n TileRemoteInterface remote = (TileRemoteInterface) tile;\n IBlockState connected = remote.getRemoteState();\n\n if (connected != null)\n connected.getBlock().onBlockClicked(worldIn, remote.getRemotePosition(), playerIn);\n }\n }\n\n @Override\n public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) {\n TileEntity tile = world.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n return ((TileRemoteInterface)tile).getExtendedBlockState(state);\n } else {\n return super.getExtendedState(state, world, pos);\n }\n }\n\n @Override\n public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {\n TileEntity tile = source.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n TileRemoteInterface remote = (TileRemoteInterface) tile;\n IBlockState connected = remote.getRemoteState();\n\n if (connected != null) {\n return connected.getBlock().getBoundingBox(connected, source, remote.getRemotePosition());\n }\n }\n return super.getBoundingBox(state, source, pos);\n }\n\n @Nullable\n @Override\n public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) {\n TileEntity tile = worldIn.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n TileRemoteInterface remote = (TileRemoteInterface) tile;\n IBlockState connected = remote.getRemoteState();\n\n if (connected != null) {\n return connected.getBlock().getCollisionBoundingBox(connected, worldIn, remote.getRemotePosition());\n }\n }\n return super.getCollisionBoundingBox(blockState, worldIn, pos);\n }\n\n @Override\n public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos) {\n TileEntity tile = world.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n TileRemoteInterface remote = (TileRemoteInterface) tile;\n IBlockState connected = remote.getRemoteState();\n if (connected == null || (connected.getBlock() == Blocks.AIR || connected.getBlock() == this))\n return 0;\n\n return connected.getBlock().getLightValue(connected, world, remote.getRemotePosition());\n } else {\n return 0;\n }\n }\n\n @SideOnly(Side.CLIENT)\n public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {\n //TODO: Disabled until I can find a way to shift particles spawned in world\n /*TileEntity tile = worldIn.getTileEntity(pos);\n if (tile != null && tile instanceof TileRemoteInterface) {\n IBlockState connected = ((TileRemoteInterface)tile).getRemoteState();\n if (connected != null)\n connected.getBlock().randomDisplayTick(connected, worldIn, pos, rand);\n }*/\n }\n}", "@GameRegistry.ObjectHolder(ModInfo.MOD_ID)\npublic class ModBlocks {\n\n public static final BlockRemoteInterface remote_interface = null;\n @GameRegistry.ObjectHolder(ModInfo.MOD_ID + \":remote_interface\")\n public static final ItemBlock remote_interface_item = null;\n\n public static final BlockAnalyzer analyzer = null;\n @GameRegistry.ObjectHolder(ModInfo.MOD_ID + \":analyzer\")\n public static final ItemBlock analyzer_item = null;\n\n @Mod.EventBusSubscriber\n public static class RegistrationHandler {\n\n @SubscribeEvent\n public static void addBlocks(RegistryEvent.Register<Block> event) {\n event.getRegistry().registerAll(\n new BlockRemoteInterface().setRegistryName(ModInfo.MOD_ID, \"remote_interface\"),\n new BlockAnalyzer().setRegistryName(ModInfo.MOD_ID, \"analyzer\")\n );\n }\n\n @SubscribeEvent\n public static void addItems(RegistryEvent.Register<Item> event) {\n event.getRegistry().registerAll(\n new ItemBlock(ModBlocks.remote_interface).setRegistryName(ModInfo.MOD_ID, \"remote_interface\"),\n new ItemBlock(ModBlocks.analyzer).setRegistryName(ModInfo.MOD_ID, \"analyzer\")\n );\n }\n }\n}", "public class BaseModelLoader implements ICustomModelLoader {\n\n private static Map<Predicate<String>, IModel> modelRegistry = Maps.newHashMap();\n static {\n modelRegistry.put((new Predicate<String>() {\n @Override\n public boolean test(String path) {\n return path.contains(\"block\") && path.contains(\"remote_interface\");\n }\n }), new MagicalModel());\n }\n\n @Override\n public boolean accepts(ResourceLocation modelLocation) {\n if (!modelLocation.getResourceDomain().equals(\"remoteio\"))\n return false;\n\n final String path = modelLocation.getResourcePath();\n\n for (Map.Entry<Predicate<String>, IModel> entry : modelRegistry.entrySet()) {\n if (entry.getKey().test(path))\n return true;\n }\n\n return false;\n }\n\n @Override\n public IModel loadModel(ResourceLocation modelLocation) throws Exception {\n final String path = modelLocation.getResourcePath();\n\n for (Map.Entry<Predicate<String>, IModel> entry : modelRegistry.entrySet()) {\n if (entry.getKey().test(path))\n return entry.getValue();\n }\n\n return null;\n }\n\n @Override\n public void onResourceManagerReload(IResourceManager resourceManager) {\n\n }\n}", "public class RenderTileRemoteInterface extends TileEntitySpecialRenderer<TileRemoteInterface> {\n\n @Override\n public void renderTileEntityAt(TileRemoteInterface te, double x, double y, double z, float partialTicks, int destroyStage) {\n if (te.getRemoteState() != null) {\n bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);\n\n GlStateManager.pushMatrix();\n GlStateManager.translate(x, y, z);\n\n TileEntity remote = getWorld().getTileEntity(te.getRemotePosition());\n if (remote != null) {\n try {\n TileEntityRendererDispatcher.instance.renderTileEntityAt(remote, 0, 0, 0, partialTicks);\n } catch (Exception ex) {\n FMLLog.warning(\"Failed to render \" + remote.getClass().getSimpleName() + \". Reason: \" + ex.getLocalizedMessage());\n }\n }\n\n GlStateManager.popMatrix();\n }\n }\n}", "public class RenderState {\n\n public static final RenderState BLANK = new RenderState(null, null, false, false);\n\n // Horrible, I know, but it works, I guess\n public IBlockState blockState;\n public IBlockState extendedBlockState;\n\n public boolean camouflage = false;\n public boolean tileRender = false;\n\n public RenderState() {\n\n }\n\n public RenderState(IBlockState blockState, IBlockState extendedBlockState, boolean camouflage, boolean tileRender) {\n this.blockState = blockState;\n this.extendedBlockState = extendedBlockState;\n this.camouflage = camouflage;\n this.tileRender = tileRender;\n }\n\n @Override\n public String toString() {\n return \"{ \" + blockState + \" }\";\n }\n}", "public class CActivateBlock implements IMessage {\n\n public BlockPos blockPos;\n\n public CActivateBlock() {\n\n }\n\n public CActivateBlock(BlockPos blockPos) {\n this.blockPos = blockPos;\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n buf.writeLong(blockPos.toLong());\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n blockPos = BlockPos.fromLong(buf.readLong());\n }\n\n public static class Handler implements IMessageHandler<CActivateBlock, IMessage> {\n\n @Override\n public IMessage onMessage(final CActivateBlock message, MessageContext ctx) {\n PacketHandler.addScheduledTask(ctx.netHandler, () -> handleMessage(message, ctx));\n return null;\n }\n\n private void handleMessage(CActivateBlock message, MessageContext ctx) {\n RemoteIO.proxy.handleClientBlockActivationMessage(message); //TODO: Find a better way?\n }\n }\n}", "public class ClientProxyPlayer extends EntityPlayerSP {\n\n private EntityPlayerSP parentPlayer;\n public ClientProxyPlayer(EntityPlayerSP parentPlayer) {\n super(Minecraft.getMinecraft(),parentPlayer.worldObj, parentPlayer.connection, parentPlayer.getStatFileWriter());\n }\n\n @Override\n public float getDistanceToEntity(Entity entity) {\n return 6;\n }\n\n @Override\n public double getDistanceSq(double x, double y, double z) {\n return 6;\n }\n\n @Override\n public double getDistance(double x, double y, double z) {\n return 6;\n }\n\n @Override\n public double getDistanceSqToEntity(Entity entity) {\n return 6;\n }\n}", "public class TileRemoteInterface extends TileCore implements ITickable, IFrequencyProvider {\n\n private BlockPos remotePosition;\n private int frequency = 0;\n\n @Override\n public void writeToDisk(NBTTagCompound compound) {\n compound.setInteger(\"_frequency\", frequency);\n }\n\n @Override\n public void readFromDisk(NBTTagCompound compound) {\n frequency = compound.getInteger(\"_frequency\");\n }\n\n @Override\n public void writeDescription(NBTTagCompound compound) {\n if (remotePosition != null)\n compound.setLong(\"_remote_position\", remotePosition.toLong());\n\n compound.setInteger(\"_frequency\", frequency);\n }\n\n @Override\n public void readDescription(NBTTagCompound compound) {\n if (compound.hasKey(\"_remote_position\"))\n remotePosition = BlockPos.fromLong(compound.getLong(\"_remote_position\"));\n else\n remotePosition = null;\n\n frequency = compound.getInteger(\"_frequency\");\n }\n\n @Override\n public void onLoad() {\n if (!worldObj.isRemote) {\n remotePosition = DeviceRegistry.getWatchedBlock(worldObj.provider.getDimension(), getFrequency());\n }\n }\n\n @Override\n public void update() {\n if (!worldObj.isRemote) {\n BlockPos pos = DeviceRegistry.getWatchedBlock(worldObj.provider.getDimension(), getFrequency());\n if (pos == null) {\n if (remotePosition != null) {\n this.remotePosition = null;\n\n notifyNeighbors();\n markDirtyAndNotify();\n }\n } else if (!pos.equals(remotePosition)) {\n this.remotePosition = pos;\n\n notifyNeighbors();\n markDirtyAndNotify();\n }\n }\n }\n\n @Override\n public boolean hasFastRenderer() {\n TileEntity remote = getRemoteTile();\n if (remote != null)\n return remote.hasFastRenderer();\n else\n return false;\n }\n\n @Override\n public int getFrequency() {\n return frequency;\n }\n\n @Override\n public void setFrequency(int frequency) {\n this.frequency = frequency;\n\n notifyNeighbors();\n markDirtyAndNotify();\n }\n\n @Override\n public BlockPos getPosition() {\n return pos;\n }\n\n public BlockPos getRemotePosition() {\n return remotePosition;\n }\n\n public IBlockState getRemoteState() {\n if (remotePosition != null) {\n IBlockState state = worldObj.getBlockState(remotePosition);\n if (state.getBlock().isAir(state, worldObj, remotePosition))\n return null;\n\n if (state.getBlock() == ModBlocks.analyzer || state.getBlock() == ModBlocks.remote_interface)\n return null;\n\n return state;\n }\n else\n return null;\n }\n\n private TileEntity getRemoteTile() {\n return getRemoteState() == null ? null : worldObj.getTileEntity(getRemotePosition());\n }\n\n @SideOnly(Side.CLIENT)\n public IExtendedBlockState getExtendedBlockState(IBlockState state) {\n IBlockState connected = getRemoteState();\n if (connected == null) {\n return ((IExtendedBlockState) state)\n .withProperty(BlockRemoteInterface.RENDER_STATE, RenderState.BLANK);\n }\n\n TileEntity tile = worldObj.getTileEntity(getRemotePosition());\n boolean tileRender = false;\n if (tile != null) {\n tileRender = TileEntityRendererDispatcher.instance.getSpecialRenderer(tile) != null;\n }\n\n RenderState renderState = new RenderState();\n renderState.blockState = connected.getActualState(worldObj, getRemotePosition());\n renderState.extendedBlockState = connected.getBlock().getExtendedState(renderState.blockState, worldObj, getRemotePosition());\n renderState.camouflage = true;\n renderState.tileRender = tileRender;\n\n return ((IExtendedBlockState) state)\n .withProperty(BlockRemoteInterface.RENDER_STATE, renderState);\n }\n\n /* START CAPABILITY HANDLING */\n\n @Override\n public boolean hasCapability(Capability<?> capability, EnumFacing facing) {\n TileEntity remoteTile = getRemoteTile();\n return remoteTile != null && remoteTile.hasCapability(capability, facing);\n }\n\n @Override\n public <T> T getCapability(Capability<T> capability, EnumFacing facing) {\n return getRemoteTile().getCapability(capability, facing);\n }\n}" ]
import me.dmillerw.remoteio.RemoteIO; import me.dmillerw.remoteio.block.BlockRemoteInterface; import me.dmillerw.remoteio.block.ModBlocks; import me.dmillerw.remoteio.client.model.loader.BaseModelLoader; import me.dmillerw.remoteio.client.render.RenderTileRemoteInterface; import me.dmillerw.remoteio.lib.property.RenderState; import me.dmillerw.remoteio.network.packet.client.CActivateBlock; import me.dmillerw.remoteio.network.player.ClientProxyPlayer; import me.dmillerw.remoteio.tile.TileRemoteInterface; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import javax.annotation.Nullable;
package me.dmillerw.remoteio.core.proxy; /** * Created by dmillerw */ public class ClientProxy extends CommonProxy implements IProxy { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event);
ModelLoaderRegistry.registerLoader(new BaseModelLoader());
3
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/activities/ForecastCityActivity.java
[ "@Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION)\npublic abstract class AppDatabase extends RoomDatabase {\n public static final String DB_NAME = \"PF_WEATHER_DB.db\";\n static final int VERSION = 7;\n static final String TAG = AppDatabase.class.getSimpleName();\n\n // DAOs\n public abstract CityDao cityDao();\n public abstract CityToWatchDao cityToWatchDao();\n public abstract CurrentWeatherDao currentWeatherDao();\n\n public abstract ForecastDao forecastDao();\n\n public abstract WeekForecastDao weekForecastDao();\n\n // INSTANCE\n private static final Object databaseLock = new Object();\n private static volatile AppDatabase INSTANCE;\n\n /**\n * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context.\n * @param context to be injected into the ContextAwareMigrations\n * @return an array of Migrations, this can not be empty\n */\n public static Migration[] getMigrations(Context context) {\n Migration[] MIGRATIONS = new Migration[]{\n new Migration_1_2(),\n new Migration_2_3(),\n new Migration_3_4(),\n new Migration_4_5(),\n new Migration_5_6(),\n new Migration_6_7()\n // Add new migrations here\n };\n\n for(Migration m : MIGRATIONS) {\n if(m instanceof ContextAwareMigration) {\n ((ContextAwareMigration) m).injectContext(context);\n }\n }\n return MIGRATIONS;\n }\n\n public static AppDatabase getInstance(Context context) {\n if(INSTANCE == null) {\n synchronized (databaseLock) {\n if(INSTANCE == null) {\n INSTANCE = buildDatabase(context);\n }\n }\n }\n return INSTANCE;\n }\n\n private static AppDatabase buildDatabase(final Context context) {\n Migration[] MIGRATIONS = getMigrations(context);\n\n return Room.databaseBuilder(context, AppDatabase.class, DB_NAME)\n .addMigrations(MIGRATIONS)\n .addCallback(new Callback() {\n @Override\n public void onCreate(@NonNull SupportSQLiteDatabase db) {\n super.onCreate(db);\n\n // disable WAL because of the upcoming big transaction\n db.setTransactionSuccessful();\n db.endTransaction();\n db.disableWriteAheadLogging();\n db.beginTransaction();\n\n int cityCount = 0;\n Cursor c = db.query(\"SELECT count(*) FROM CITIES\");\n if(c != null) {\n if(c.moveToFirst()) {\n cityCount = c.getInt(c.getColumnIndex(\"count(*)\"));\n }\n c.close();\n }\n\n Log.d(TAG, \"City count: \" + cityCount);\n if(cityCount == 0) {\n fillCityDatabase(context, db);\n }\n\n // TODO: DEBUG ONLY - REMOVE WHEN DONE\n c = db.query(\"SELECT count(*) FROM CITIES\");\n if(c != null) {\n if(c.moveToFirst()) {\n cityCount = c.getInt(c.getColumnIndex(\"count(*)\"));\n }\n c.close();\n }\n Log.d(TAG, \"City count: \" + cityCount);\n }\n })\n .allowMainThreadQueries()\n .fallbackToDestructiveMigration()\n .build();\n }\n\n public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) {\n long startInsertTime = System.currentTimeMillis();\n\n InputStream inputStream = context.getResources().openRawResource(R.raw.city_list);\n try {\n FileReader fileReader = new FileReader();\n final List<City> cities = fileReader.readCitiesFromFile(inputStream);\n\n if (cities.size() > 0) {\n for (City c : cities) {\n ContentValues values = new ContentValues();\n values.put(\"cities_id\", c.getCityId());\n values.put(\"city_name\", c.getCityName());\n values.put(\"country_code\", c.getCountryCode());\n values.put(\"longitude\", c.getLongitude());\n values.put(\"latitude\", c.getLatitude());\n database.insert(\"CITIES\", SQLiteDatabase.CONFLICT_REPLACE, values);\n }\n }\n\n inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n long endInsertTime = System.currentTimeMillis();\n Log.d(\"debug_info\", \"Time for insert:\" + (endInsertTime - startInsertTime));\n }\n}", "@SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,\n RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD})\n\n/**\n * This class represents the database model for current weather data of cities.\n */\n@Entity(tableName = \"CURRENT_WEATHER\", foreignKeys = {\n @ForeignKey(entity = City.class,\n parentColumns = {\"cities_id\"},\n childColumns = {\"city_id\"},\n onDelete = ForeignKey.CASCADE)})\npublic class CurrentWeatherData {\n\n @PrimaryKey(autoGenerate = true)\n @ColumnInfo(name = \"current_weather_id\")\n private int id;\n @ColumnInfo(name = \"city_id\")\n private int city_id;\n @ColumnInfo(name = \"time_of_measurement\")\n private long timestamp;\n @ColumnInfo(name = \"weather_id\")\n private int weatherID;\n @ColumnInfo(name = \"temperature_current\")\n private float temperatureCurrent;\n @ColumnInfo(name = \"temperature_min\")\n private float temperatureMin;//TODO: Remove, not available in one call api\n @ColumnInfo(name = \"temperature_max\")\n private float temperatureMax;//TODO: Remove, not available in one call api\n @ColumnInfo(name = \"humidity\")\n private float humidity;\n @ColumnInfo(name = \"pressure\")\n private float pressure;\n @ColumnInfo(name = \"wind_speed\")\n private float windSpeed;\n @ColumnInfo(name = \"wind_direction\")\n private float windDirection;\n @ColumnInfo(name = \"cloudiness\")\n private float cloudiness;\n @ColumnInfo(name = \"time_sunrise\")\n private long timeSunrise;\n @ColumnInfo(name = \"time_sunset\")\n private long timeSunset;\n @ColumnInfo(name = \"timezone_seconds\")\n private int timeZoneSeconds;\n @ColumnInfo(name = \"rain60min\")\n private String rain60min;\n\n @Ignore\n private String city_name;\n\n public CurrentWeatherData() {\n this.city_id = Integer.MIN_VALUE;\n }\n\n @Ignore\n public CurrentWeatherData(int id, int city_id, long timestamp, int weatherID, float temperatureCurrent, float temperatureMin, float temperatureMax, float humidity, float pressure, float windSpeed, float windDirection, float cloudiness, long timeSunrise, long timeSunset, int timeZoneSeconds) {\n this.id = id;\n this.city_id = city_id;\n this.timestamp = timestamp;\n this.weatherID = weatherID;\n this.temperatureCurrent = temperatureCurrent;\n this.temperatureMin = temperatureMin;\n this.temperatureMax = temperatureMax;\n this.humidity = humidity;\n this.pressure = pressure;\n this.windSpeed = windSpeed;\n this.windDirection = windDirection;\n this.cloudiness = cloudiness;\n this.timeSunrise = timeSunrise;\n this.timeSunset = timeSunset;\n this.timeZoneSeconds = timeZoneSeconds;\n this.rain60min = rain60min;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getCity_id() {\n return city_id;\n }\n\n public void setCity_id(int city_id) {\n this.city_id = city_id;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public int getWeatherID() {\n return weatherID;\n }\n\n public void setWeatherID(int weatherID) {\n this.weatherID = weatherID;\n }\n\n public float getTemperatureCurrent() {\n return temperatureCurrent;\n }\n\n public void setTemperatureCurrent(float temperatureCurrent) {\n this.temperatureCurrent = temperatureCurrent;\n }\n\n public float getTemperatureMin() {\n return temperatureMin;\n }\n\n public void setTemperatureMin(float temperatureMin) {\n this.temperatureMin = temperatureMin;\n }\n\n public float getTemperatureMax() {\n return temperatureMax;\n }\n\n public void setTemperatureMax(float temperatureMax) {\n this.temperatureMax = temperatureMax;\n }\n\n public float getHumidity() {\n return humidity;\n }\n\n public void setHumidity(float humidity) {\n this.humidity = humidity;\n }\n\n public float getPressure() {\n return pressure;\n }\n\n public void setPressure(float pressure) {\n this.pressure = pressure;\n }\n\n public float getWindSpeed() {\n return windSpeed;\n }\n\n public void setWindSpeed(float windSpeed) {\n this.windSpeed = windSpeed;\n }\n\n public float getWindDirection() {\n return windDirection;\n }\n\n public void setWindDirection(float windDirection) {\n this.windDirection = windDirection;\n }\n\n public float getCloudiness() {\n return cloudiness;\n }\n\n public void setCloudiness(float cloudiness) {\n this.cloudiness = cloudiness;\n }\n\n public long getTimeSunrise() {\n return timeSunrise;\n }\n\n public void setTimeSunrise(long timeSunrise) {\n this.timeSunrise = timeSunrise;\n }\n\n public long getTimeSunset() {\n return timeSunset;\n }\n\n public void setTimeSunset(long timeSunset) {\n this.timeSunset = timeSunset;\n }\n\n public String getCity_name() {\n return city_name;\n }\n\n public void setCity_name(String city_name) {\n this.city_name = city_name;\n }\n\n public int getTimeZoneSeconds() {\n return timeZoneSeconds;\n }\n\n public void setTimeZoneSeconds(int timeZoneSeconds) {\n this.timeZoneSeconds = timeZoneSeconds;\n }\n\n public String getRain60min() {\n return rain60min;\n }\n\n public void setRain60min(String rain60min) {\n this.rain60min = rain60min;\n }\n}", "@SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,\n RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, RoomWarnings.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED})\n\n/**\n * This class is the database model for the forecasts table.\n */\n@Entity(tableName = \"FORECASTS\", foreignKeys = {\n @ForeignKey(entity = City.class,\n parentColumns = {\"cities_id\"},\n childColumns = {\"city_id\"},\n onDelete = ForeignKey.CASCADE)})\npublic class Forecast {\n\n public static final float NO_RAIN_VALUE = 0;\n\n @PrimaryKey(autoGenerate = true) @ColumnInfo(name = \"forecast_id\") private int id;\n @ColumnInfo(name = \"city_id\") private int city_id;\n @ColumnInfo(name = \"time_of_measurement\") private long timestamp;\n @ColumnInfo(name = \"forecast_for\") private long forecastTime;\n @ColumnInfo(name = \"weather_id\") private int weatherID;\n @ColumnInfo(name = \"temperature_current\") private float temperature;\n @ColumnInfo(name = \"humidity\") private float humidity;\n @ColumnInfo(name = \"pressure\") private float pressure;\n @ColumnInfo(name = \"wind_speed\") private float windSpeed;\n @ColumnInfo(name = \"wind_direction\") private float windDirection;\n @ColumnInfo(name = \"precipitation\")\n private float rainValue;\n @ColumnInfo(name = \"rain_probability\")\n private float rainProbability;\n @Embedded\n private City city;\n\n public Forecast() { }\n\n @Ignore\n public Forecast(int id, int city_id, long timestamp, long forecastFor, int weatherID, float temperature, float humidity,\n float pressure, float windSpeed, float windDirection, float rainValue, float rainProbability) {\n this.id = id;\n this.city_id = city_id;\n this.timestamp = timestamp;\n this.forecastTime = forecastFor;\n this.weatherID = weatherID;\n this.temperature = temperature;\n this.humidity = humidity;\n this.pressure = pressure;\n this.windSpeed = windSpeed;\n this.windDirection = windDirection;\n this.rainValue = rainValue;\n this.rainProbability = rainProbability;\n }\n\n public float getWindDirection() {\n return windDirection;\n }\n\n public void setWindDirection(float windDirection) {\n this.windDirection = windDirection;\n }\n\n public float getWindSpeed() {\n return windSpeed;\n }\n\n public void setWindSpeed(float speed) {\n windSpeed = speed;\n }\n\n /**\n * @return Returns the ID of the record (which uniquely identifies the record).\n */\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n /**\n * @return Returns the date and time for the forecast.\n */\n public long getForecastTime() {\n return forecastTime;\n }\n\n /**\n * @return Returns the local time for the forecast in UTC epoch\n */\n public long getLocalForecastTime(Context context) {\n AppDatabase dbhelper = AppDatabase.getInstance(context);\n CurrentWeatherData data = dbhelper.currentWeatherDao().getCurrentWeatherByCityId(city_id);\n int timezoneseconds = 0;\n if (data != null) {\n timezoneseconds = data.getTimeZoneSeconds();\n } else {\n Toast.makeText(context, R.string.no_forecast_warning, Toast.LENGTH_SHORT).show();\n }\n return forecastTime + timezoneseconds * 1000L;\n }\n\n /**\n * @param forecastFor The point of time for the forecast.\n */\n public void setForecastTime(long forecastFor) {\n this.forecastTime = forecastFor;\n }\n\n /**\n * @return Returns the point of time when the data was inserted into the database in Unix, UTC.\n */\n public long getTimestamp() {\n return timestamp;\n }\n\n /**\n * @param timestamp The point of time to set when the data was inserted into the database in\n * Unix, UTC.\n */\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public int getCity_id() {\n return city_id;\n }\n\n public void setCity_id(int city_id) {\n this.city_id = city_id;\n }\n\n /**\n * @return Returns the weather condition ID.\n */\n public int getWeatherID() {\n return weatherID;\n }\n\n /**\n * @param weatherID The weather condition ID to set.\n */\n public void setWeatherID(int weatherID) {\n this.weatherID = weatherID;\n }\n\n /**\n * @return Returns the current temperature in Celsius.\n */\n public float getTemperature() {\n return temperature;\n }\n\n /**\n * @param temperature The current temperature to set in Celsius.\n */\n public void setTemperature(float temperature) {\n this.temperature = temperature;\n }\n\n /**\n * @return Returns the humidity value in percent.\n */\n public float getHumidity() {\n return humidity;\n }\n\n /**\n * @param humidity The humidity value in percent to set.\n */\n public void setHumidity(float humidity) {\n this.humidity = humidity;\n }\n\n /**\n * @return Returns the air pressure value in hectopascal (hPa).\n */\n public float getPressure() {\n return pressure;\n }\n\n /**\n * @param pressure The air pressure value in hectopascal (hPa) to set.\n */\n public void setPressure(float pressure) {\n this.pressure = pressure;\n }\n\n public String getCity_name() {\n return city.getCityName();\n }\n\n public void setCity_name(String city_name) {\n this.city.setCityName(city_name);\n }\n\n public float getRainValue() {\n return rainValue;\n }\n\n public void setRainValue(float RainValue) {\n rainValue = RainValue;\n }\n\n public float getRainProbability() {\n return rainProbability;\n }\n\n public void setRainProbability(float rainProbability) {\n this.rainProbability = rainProbability;\n }\n\n public City getCity() {\n return city;\n }\n\n public void setCity(City city) {\n this.city = city;\n }\n}", "@SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED,\n RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, RoomWarnings.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED})\n\n/**\n * This class is the database model for the Weekforecasts table.\n */\n@Entity(tableName = \"WEEKFORECASTS\", foreignKeys = {\n @ForeignKey(entity = City.class,\n parentColumns = {\"cities_id\"},\n childColumns = {\"city_id\"},\n onDelete = ForeignKey.CASCADE)})\npublic class WeekForecast {\n\n\n @PrimaryKey(autoGenerate = true)\n @ColumnInfo(name = \"forecast_id\")\n private int id;\n @ColumnInfo(name = \"city_id\")\n private int city_id;\n @ColumnInfo(name = \"time_of_measurement\")\n private long timestamp;\n @ColumnInfo(name = \"forecastTime\")\n private long forecastTime;\n @ColumnInfo(name = \"weather_id\")\n private int weatherID;\n @ColumnInfo(name = \"temperature_current\")\n private float temperature;\n @ColumnInfo(name = \"temperature_min\")\n private float temperature_min;\n @ColumnInfo(name = \"temperature_max\")\n private float temperature_max;\n @ColumnInfo(name = \"humidity\")\n private float humidity;\n @ColumnInfo(name = \"pressure\")\n private float pressure;\n @ColumnInfo(name = \"precipitation\")\n private float precipitation;\n @ColumnInfo(name = \"rain_probability\")\n private float rain_probability;\n @ColumnInfo(name = \"wind_speed\")\n private float wind_speed;\n @ColumnInfo(name = \"wind_direction\")\n private float wind_direction;\n @ColumnInfo(name = \"uv_index\")\n private float uv_index;\n @Embedded\n private City city;\n\n public WeekForecast() {\n }\n\n @Ignore\n public WeekForecast(int id, int city_id, long timestamp, long forecastTime, int weatherID, float temperature, float temperature_min, float temperature_max, float humidity, float pressure, float precipitation, float wind_speed, float wind_direction, float uv_index, float rain_probability) {\n this.id = id;\n this.city_id = city_id;\n this.timestamp = timestamp;\n this.forecastTime = forecastTime;\n this.weatherID = weatherID;\n this.temperature = temperature;\n this.temperature_min = temperature_min;\n this.temperature_max = temperature_max;\n this.humidity = humidity;\n this.pressure = pressure;\n this.precipitation = precipitation;\n this.wind_speed = wind_speed;\n this.wind_direction = wind_direction;\n this.uv_index = uv_index;\n this.rain_probability = rain_probability;\n }\n\n\n /**\n * @return Returns the ID of the record (which uniquely identifies the record).\n */\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n /**\n * @return Returns the date and time for the forecast.\n */\n public long getForecastTime() {\n return forecastTime;\n }\n\n /**\n * @return Returns the local time for the forecast in UTC epoch\n */\n public long getLocalForecastTime(Context context) {\n AppDatabase dbhelper = AppDatabase.getInstance(context);\n int timezoneseconds = dbhelper.currentWeatherDao().getCurrentWeatherByCityId(city_id).getTimeZoneSeconds();\n return forecastTime + timezoneseconds * 1000L;\n }\n\n /**\n * @param forecastFor The point of time for the forecast.\n */\n public void setForecastTime(long forecastFor) {\n this.forecastTime = forecastFor;\n }\n\n /**\n * @return Returns the point of time when the data was inserted into the database in Unix, UTC.\n */\n public long getTimestamp() {\n return timestamp;\n }\n\n /**\n * @param timestamp The point of time to set when the data was inserted into the database in\n * Unix, UTC.\n */\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public int getCity_id() {\n return city_id;\n }\n\n public void setCity_id(int city_id) {\n this.city_id = city_id;\n }\n\n /**\n * @return Returns the weather condition ID.\n */\n public int getWeatherID() {\n return weatherID;\n }\n\n /**\n * @param weatherID The weather condition ID to set.\n */\n public void setWeatherID(int weatherID) {\n this.weatherID = weatherID;\n }\n\n /**\n * @return Returns the current temperature in Celsius.\n */\n public float getTemperature() {\n return temperature;\n }\n\n /**\n * @param temperature The current temperature to set in Celsius.\n */\n public void setTemperature(float temperature) {\n this.temperature = temperature;\n }\n\n /**\n * @return Returns the min temperature in Celsius.\n */\n public float getMinTemperature() {\n return temperature_min;\n }\n\n /**\n * @param temperature_min The min temperature to set in Celsius.\n */\n public void setMinTemperature(float temperature_min) {\n this.temperature_min = temperature_min;\n }\n\n /**\n * @return Returns the max temperature in Celsius.\n */\n public float getMaxTemperature() {\n return temperature_max;\n }\n\n /**\n * @param temperature_max The max temperature to set in Celsius.\n */\n public void setMaxTemperature(float temperature_max) {\n this.temperature_max = temperature_max;\n }\n\n\n /**\n * @return Returns the humidity value in percent.\n */\n public float getHumidity() {\n return humidity;\n }\n\n /**\n * @param humidity The humidity value in percent to set.\n */\n public void setHumidity(float humidity) {\n this.humidity = humidity;\n }\n\n public float getPressure() {\n return pressure;\n }\n\n public void setPressure(float pressure) {\n this.pressure = pressure;\n }\n\n public float getPrecipitation() {\n return precipitation;\n }\n\n public void setPrecipitation(float precipitation) {\n this.precipitation = precipitation;\n }\n\n public float getWind_speed() {\n return wind_speed;\n }\n\n public void setWind_speed(float wind_speed) {\n this.wind_speed = wind_speed;\n }\n\n public float getWind_direction() {\n return wind_direction;\n }\n\n public void setWind_direction(float wind_direction) {\n this.wind_direction = wind_direction;\n }\n\n public float getUv_index() {\n return uv_index;\n }\n\n public void setUv_index(float uv_index) {\n this.uv_index = uv_index;\n }\n\n public float getTemperature_min() {\n return temperature_min;\n }\n\n public void setTemperature_min(float temperature_min) {\n this.temperature_min = temperature_min;\n }\n\n public float getTemperature_max() {\n return temperature_max;\n }\n\n public void setTemperature_max(float temperature_max) {\n this.temperature_max = temperature_max;\n }\n\n public City getCity() {\n return city;\n }\n\n public void setCity(City city) {\n this.city = city;\n }\n\n public float getRain_probability() {\n return rain_probability;\n }\n\n public void setRain_probability(float rain_probability) {\n this.rain_probability = rain_probability;\n }\n}", "public interface IUpdateableCityUI {\n void processNewWeatherData(CurrentWeatherData data);\n\n void updateForecasts(List<Forecast> forecasts);\n\n void updateWeekForecasts(List<WeekForecast> forecasts);\n\n void abortUpdate();\n}", "public class ViewUpdater {\n private static List<IUpdateableCityUI> subscribers = new ArrayList<>();\n\n public static void addSubscriber(IUpdateableCityUI sub) {\n if (!subscribers.contains(sub)) {\n subscribers.add(sub);\n }\n }\n\n public static void removeSubscriber(IUpdateableCityUI sub) {\n subscribers.remove(sub);\n }\n\n public static void updateCurrentWeatherData(CurrentWeatherData data) {\n ArrayList<IUpdateableCityUI> subcopy = new ArrayList<>(subscribers);\n for (IUpdateableCityUI sub : subcopy) {\n sub.processNewWeatherData(data);\n }\n }\n\n public static void updateWeekForecasts(List<WeekForecast> forecasts) {\n for (IUpdateableCityUI sub : subscribers) {\n sub.updateWeekForecasts(forecasts);\n }\n }\n\n public static void updateForecasts(List<Forecast> forecasts) {\n for (IUpdateableCityUI sub : subscribers) {\n sub.updateForecasts(forecasts);\n }\n }\n\n public static void abortUpdate() {\n for (IUpdateableCityUI sub : subscribers) {\n sub.abortUpdate();\n }\n }\n}", "public class WeatherPagerAdapter extends FragmentStatePagerAdapter implements IUpdateableCityUI {\n\n private Context mContext;\n\n private AppDatabase database;\n AppPreferencesManager prefManager;\n long lastUpdateTime;\n\n private List<CityToWatch> cities;\n private List<CurrentWeatherData> currentWeathers;\n\n private static int[] mDataSetTypes = {OVERVIEW, DETAILS, DAY, WEEK, CHART}; //TODO Make dynamic from Settings\n private static int[] errorDataSetTypes = {ERROR};\n\n public WeatherPagerAdapter(Context context, FragmentManager supportFragmentManager) {\n super(supportFragmentManager);\n this.mContext = context;\n this.prefManager = new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(context));\n this.database = AppDatabase.getInstance(context);\n this.currentWeathers = database.currentWeatherDao().getAll();\n this.cities = database.cityToWatchDao().getAll();\n try {\n cities = database.cityToWatchDao().getAll();\n Collections.sort(cities, new Comparator<CityToWatch>() {\n @Override\n public int compare(CityToWatch o1, CityToWatch o2) {\n return o1.getRank() - o2.getRank();\n }\n\n });\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n @NotNull\n @Override\n public WeatherCityFragment getItem(int position) {\n CurrentWeatherData cityWeather = getDataForID(cities.get(position).getCityId());\n if (cityWeather == null) {\n cityWeather = new CurrentWeatherData();\n cityWeather.setCity_id(cities.get(position).getCityId());\n cityWeather.setTimestamp(System.currentTimeMillis() / 1000);\n cityWeather.setWeatherID(0);\n cityWeather.setTemperatureCurrent(0);\n cityWeather.setHumidity(0);\n cityWeather.setPressure(0);\n cityWeather.setWindSpeed(0);\n cityWeather.setWindDirection(0);\n cityWeather.setCloudiness(0);\n cityWeather.setTimeSunrise(System.currentTimeMillis() / 1000);\n cityWeather.setTimeSunset(System.currentTimeMillis() / 1000);\n cityWeather.setTimeZoneSeconds(0);\n cityWeather.setRain60min(\"000000000000\");\n }\n return WeatherCityFragment.newInstance(cityWeather, mDataSetTypes);\n }\n\n private CurrentWeatherData getDataForID(int cityID) {\n for (CurrentWeatherData data : currentWeathers) {\n if (data.getCity_id() == cityID) return data;\n }\n return null;\n }\n\n @Override\n public int getCount() {\n return cities.size();\n }\n\n @Override\n public CharSequence getPageTitle(int position) { //TODO: Remove, no longer needed. City is shown on TAB, time is now shown in card details, as there is more space\n// GregorianCalendar calendar = new GregorianCalendar();\n// SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm\");\n// dateFormat.setCalendar(calendar);\n// calendar.setTimeInMillis(lastUpdateTime*1000);\n if (cities.size() == 0) {\n return mContext.getString(R.string.app_name);\n }\n return cities.get(position).getCityName(); // + \" (\" + dateFormat.format(calendar.getTime()) + \")\";\n }\n\n //TODO: Remove, no longer needed. City is shown on TAB, time is now shown in card details, as there is more space\n public CharSequence getPageTitleForActionBar(int position) {\n\n int zoneseconds = 0;\n //fallback to last time the weather data was updated\n long time = lastUpdateTime;\n int currentCityId = cities.get(position).getCityId();\n //search for current city\n //TODO could time get taken from an old weatherData or is it removed on Update?\n for (CurrentWeatherData weatherData : currentWeathers) {\n if (weatherData.getCity_id() == currentCityId) {\n //set time to last update time for the city and zoneseconds to UTC difference (in seconds)\n time = weatherData.getTimestamp();\n zoneseconds += weatherData.getTimeZoneSeconds();\n break;\n }\n }\n //for formatting into time respective to UTC/GMT\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm\");\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n Date updateTime = new Date((time + zoneseconds) * 1000L);\n return String.format(\"%s (%s)\", getPageTitle(position), dateFormat.format(updateTime));\n }\n\n public void refreshData(Boolean asap) {\n Intent intent = new Intent(mContext, UpdateDataService.class);\n intent.setAction(UpdateDataService.UPDATE_ALL_ACTION);\n intent.putExtra(SKIP_UPDATE_INTERVAL, asap);\n enqueueWork(mContext, UpdateDataService.class, 0, intent);\n }\n\n public void refreshSingleData(Boolean asap, int cityId) {\n Intent intent = new Intent(mContext, UpdateDataService.class);\n intent.setAction(UpdateDataService.UPDATE_SINGLE_ACTION);\n intent.putExtra(SKIP_UPDATE_INTERVAL, asap);\n intent.putExtra(\"cityId\", cityId);\n enqueueWork(mContext, UpdateDataService.class, 0, intent);\n }\n\n @Override\n public void processNewWeatherData(CurrentWeatherData data) {\n //TODO lastupdatetime might be used for more cities than it reflects\n // (update could be for any city, still other cities don't get updated)\n lastUpdateTime = System.currentTimeMillis() / 1000;\n int id = data.getCity_id();\n CurrentWeatherData old = getDataForID(id);\n if (old != null) currentWeathers.remove(old);\n currentWeathers.add(data);\n notifyDataSetChanged();\n }\n\n @Override\n public void updateForecasts(List<Forecast> forecasts) {\n //empty because Fragments are subscribers themselves\n }\n\n @Override\n public void updateWeekForecasts(List<WeekForecast> forecasts) {\n //empty because Fragments are subscribers themselves\n }\n\n @Override\n public void abortUpdate() {\n //empty because doesn't need to change something if update is aborted\n }\n\n public int getCityIDForPos(int pos) {\n CityToWatch city = cities.get(pos);\n return city.getCityId();\n }\n\n public int getPosForCityID(int cityID) {\n for (int i = 0; i < cities.size(); i++) {\n CityToWatch city = cities.get(i);\n if (city.getCityId() == cityID) {\n return i;\n }\n }\n return 0;\n }\n\n public boolean hasCityInside(int cityID) {\n for (int i = 0; i < cities.size(); i++) {\n CityToWatch city = cities.get(i);\n if (city.getCityId() == cityID) {\n return true;\n }\n }\n return false;\n }\n\n public float getLatForPos(int pos) {\n CityToWatch city = cities.get(pos);\n return city.getLatitude();\n }\n\n public float getLonForPos(int pos) {\n CityToWatch city = cities.get(pos);\n return city.getLongitude();\n }\n\n public void addCityFromDB(int cityID) {\n CityToWatch newCity = database.cityToWatchDao().getCityToWatchById(cityID);\n if (newCity != null) {\n cities.add(cities.size(), newCity);\n notifyDataSetChanged();\n }\n }\n\n\n}" ]
import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.TextView; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.database.AppDatabase; import org.secuso.privacyfriendlyweather.database.data.CurrentWeatherData; import org.secuso.privacyfriendlyweather.database.data.Forecast; import org.secuso.privacyfriendlyweather.database.data.WeekForecast; import org.secuso.privacyfriendlyweather.ui.updater.IUpdateableCityUI; import org.secuso.privacyfriendlyweather.ui.updater.ViewUpdater; import org.secuso.privacyfriendlyweather.ui.viewPager.WeatherPagerAdapter; import java.util.List;
package org.secuso.privacyfriendlyweather.activities; public class ForecastCityActivity extends BaseActivity implements IUpdateableCityUI { private WeatherPagerAdapter pagerAdapter; private MenuItem refreshActionButton; private MenuItem rainviewerButton; private int cityId = -1; private ViewPager viewPager; private TextView noCityText; public static boolean stopTurning = false; @Override protected void onPause() { super.onPause();
ViewUpdater.removeSubscriber(this);
5
mruffalo/seal
test/generator/errors/LinearIncreasingErrorGeneratorTest.java
[ "public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator\n{\n\tRandom random = new Random();\n\n\t@Override\n\tpublic CharSequence generateSequence(Options o)\n\t{\n\t\tFragmentErrorGenerator eg = new UniformErrorGenerator(o.characters,\n\t\t\to.repeatErrorProbability);\n\t\tfinal CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength);\n\t\tStringBuilder sb = new StringBuilder(o.length);\n\t\tint[] repeatedSequenceIndices = new int[o.repeatCount];\n\t\tint nonRepeatedLength = o.length - o.repeatCount * o.repeatLength;\n\t\tif (nonRepeatedLength > 0)\n\t\t{\n\t\t\tfor (int i = 0; i < o.repeatCount; i++)\n\t\t\t{\n\t\t\t\trepeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength);\n\t\t\t}\n\t\t\tArrays.sort(repeatedSequenceIndices);\n\t\t\tsb.append(generateSequence(o.characters, nonRepeatedLength));\n\t\t}\n\t\tint repeatStart = 0;\n\t\tfor (int i = 0; i < o.repeatCount; i++)\n\t\t{\n\t\t\tif (verbose)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++)\n\t\t\t\t{\n\t\t\t\t\tSystem.out.print(\" \");\n\t\t\t\t}\n\t\t\t\tSystem.out.print(repeatedSequence);\n\t\t\t\trepeatStart = repeatedSequenceIndices[i];\n\t\t\t}\n\t\t\tCharSequence currentRepeatedSequence;\n\t\t\tif (o.repeatErrorProbability > 0.0)\n\t\t\t{\n\t\t\t\tcurrentRepeatedSequence = eg.generateErrors(repeatedSequence);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrentRepeatedSequence = repeatedSequence;\n\t\t\t}\n\t\t\tsb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence);\n\t\t}\n\t\tString string = sb.toString();\n\t\tif (verbose)\n\t\t{\n\t\t\tSystem.out.println();\n\t\t\tSystem.out.println(string);\n\t\t}\n\t\treturn string;\n\t}\n\n\t/**\n\t * Standalone debug method\n\t * \n\t * @param args\n\t */\n\t@SuppressWarnings(\"unused\")\n\tpublic static void main(String[] args)\n\t{\n\t\tif (args.length < 3)\n\t\t{\n\t\t\tSystem.err.printf(\"*** Usage: %s m r l e\",\n\t\t\t\tSeqGenSingleSequenceMultipleRepeats.class.getCanonicalName());\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tOptions o = new Options();\n\t\to.length = Integer.parseInt(args[0]);\n\t\to.repeatCount = Integer.parseInt(args[1]);\n\t\to.repeatLength = Integer.parseInt(args[2]);\n\t\to.repeatErrorProbability = Double.parseDouble(args[3]);\n\t\tSequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats();\n\t\tgenerator.setVerboseOutput(true);\n\t\tCharSequence generated = generator.generateSequence(o);\n\t}\n}", "public abstract class SequenceGenerator\n{\n\tpublic static final String NUCLEOTIDES = \"ACGT\";\n\tpublic static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = \"ACGTURYKMSWBDHVNX-\";\n\tpublic static final String AMINO_ACID_ALLOWED_CHARACTERS = \"ABCDEFGHIKLMNOPQRSTUVWYZX*-\";\n\n\tprotected boolean verbose;\n\n\tpublic static class Options\n\t{\n\t\t/**\n\t\t * Characters in the generated sequence come from here\n\t\t */\n\t\tpublic String characters = NUCLEOTIDES;\n\t\tpublic int length;\n\t\tpublic int repeatCount;\n\t\tpublic int repeatLength;\n\t\t/**\n\t\t * Each character in each repeat will be substituted with a random\n\t\t * choice from {@link #characters} at this probability\n\t\t */\n\t\tpublic double repeatErrorProbability;\n\t}\n\n\t/**\n\t * Generates a single sequence with the provided length from the given\n\t * characters. XXX Make this protected again after fixing all of the\n\t * horrible design decisions I've recently made\n\t * \n\t * @param sample\n\t * @param length\n\t * @return\n\t */\n\tpublic static CharSequence generateSequence(String sample, int length)\n\t{\n\t\tRandom random = new Random();\n\t\tStringBuilder sb = new StringBuilder(length);\n\t\tfor (int i = 0; i < length; i++)\n\t\t{\n\t\t\tint index = random.nextInt(sample.length());\n\t\t\tsb.append(sample.substring(index, index + 1));\n\t\t}\n\t\treturn sb;\n\t}\n\n\t/**\n\t * Controls whether debugging information will be printed to\n\t * <code>System.err</code>. TODO: Maybe allow a separate\n\t * {@link java.io.OutputStream} to be specified.\n\t * \n\t * @param verbose_\n\t */\n\tpublic void setVerboseOutput(boolean verbose_)\n\t{\n\t\tverbose = verbose_;\n\t}\n\n\t/**\n\t * Generates a sequence according to the provided options\n\t * \n\t * @param o\n\t * Options specifying length, repeat count, repeat length,\n\t * characters to sample, error rate, etc.\n\t * @return\n\t */\n\tpublic abstract CharSequence generateSequence(Options o);\n}", "public static class Options\n{\n\t/**\n\t * Characters in the generated sequence come from here\n\t */\n\tpublic String characters = NUCLEOTIDES;\n\tpublic int length;\n\tpublic int repeatCount;\n\tpublic int repeatLength;\n\t/**\n\t * Each character in each repeat will be substituted with a random\n\t * choice from {@link #characters} at this probability\n\t */\n\tpublic double repeatErrorProbability;\n}", "public abstract class FragmentErrorGenerator\n{\n\t/**\n\t * Used to determine which character to randomly insert/switch\n\t */\n\tprotected final Random characterChoiceRandomizer;\n\t/**\n\t * Intended for use by each generator to determine whether to introduce an\n\t * error (e.g. substitute a character, start an indel)\n\t */\n\tprotected final Random random;\n\tprotected final String allowedCharacters;\n\tprotected boolean verbose;\n\n\tpublic FragmentErrorGenerator(String allowedCharacters_)\n\t{\n\t\tallowedCharacters = allowedCharacters_;\n\t\tcharacterChoiceRandomizer = new Random();\n\t\trandom = new Random();\n\t}\n\n\tpublic abstract CharSequence generateErrors(CharSequence sequence);\n\n\tpublic Fragment generateErrors(Fragment fragment)\n\t{\n\t\tString s = fragment.toString();\n\t\tFragment errored = new Fragment(generateErrors(s).toString());\n\t\terrored.clonePositionsAndReadQuality(fragment);\n\t\tfor (int i = 0; i < errored.getSequence().length(); i++)\n\t\t{\n\t\t\terrored.setReadQuality(i, getQuality(i, errored.getSequence().length()));\n\t\t}\n\t\treturn errored;\n\t}\n\n\tpublic List<? extends Fragment> generateErrors(List<? extends Fragment> fragments)\n\t{\n\t\tList<Fragment> list = new ArrayList<Fragment>(fragments.size());\n\t\tfor (Fragment fragment : fragments)\n\t\t{\n\t\t\tlist.add(generateErrors(fragment));\n\t\t}\n\t\treturn list;\n\t}\n\n\t/**\n\t * @deprecated You should probably use\n\t * {@link Fragmentizer#fragmentizeToFile(CharSequence, generator.Fragmentizer.Options, File)}\n\t * and set the {@link Fragmentizer.Options#errorGenerators}\n\t * field appropriately instead of using this.\n\t * @param errorGenerators\n\t * @param fragmentList\n\t * @param fragmentFile\n\t */\n\t@Deprecated\n\tpublic static void generateErrorsToFile(List<FragmentErrorGenerator> errorGenerators,\n\t\tList<? extends Fragment> fragmentList, File fragmentFile)\n\t{\n\t\ttry\n\t\t{\n\t\t\tFastqWriter w = new FastqWriter(new FileWriter(fragmentFile));\n\t\t\tfor (int i = 0; i < fragmentList.size(); i++)\n\t\t\t{\n\t\t\t\tFragment f = fragmentList.get(i);\n\t\t\t\tfor (FragmentErrorGenerator eg : errorGenerators)\n\t\t\t\t{\n\t\t\t\t\tf = eg.generateErrors(f);\n\t\t\t\t}\n\t\t\t\tw.writeFragment(f, 0, i);\n\t\t\t}\n\t\t\tw.close();\n\t\t}\n\t\tcatch (IOException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic abstract int getQuality(int position, int length);\n\n\tpublic static int phredScaleProbability(double errorProbability)\n\t{\n\t\treturn (int) (-10 * Math.log10(errorProbability));\n\t}\n\n\tpublic void setVerboseOutput(boolean verbose_)\n\t{\n\t\tverbose = verbose_;\n\t}\n}", "public class LinearIncreasingErrorGenerator extends SubstitutionErrorGenerator\n{\n\tprivate double beginErrorProbabilityMin;\n\tprivate double beginErrorProbabilityMax;\n\tprivate double endErrorProbabilityMin;\n\tprivate double endErrorProbabilityMax;\n\tprivate double errorProbabilityStdDev;\n\tprivate Random random = new Random();\n\n\tpublic LinearIncreasingErrorGenerator(String allowedCharacters_, double beginErrorProbabilityMin_,\n\t\t\tdouble beginErrorProbabilityMax_, double endErrorProbabilityMin_,\n\t\t\tdouble endErrorProbabilityMax_, double errorProbabilityStdDev_)\n\t{\n\t\tsuper(allowedCharacters_);\n\t\tsetBeginErrorProbabilityMin(beginErrorProbabilityMin_);\n\t\tsetBeginErrorProbabilityMax(beginErrorProbabilityMax_);\n\t\tsetEndErrorProbabilityMin(endErrorProbabilityMin_);\n\t\tsetEndErrorProbabilityMax(endErrorProbabilityMax_);\n\t\tsetErrorProbabilityStdDev(errorProbabilityStdDev_);\n\t}\n\n\tpublic double getBeginErrorProbabilityMin()\n\t{\n\t\treturn beginErrorProbabilityMin;\n\t}\n\n\tpublic void setBeginErrorProbabilityMin(double beginErrorProbability_)\n\t{\n\t\tif (beginErrorProbability_ <= 1.0 && beginErrorProbability_ >= 0.0)\n\t\t{\n\t\t\tbeginErrorProbabilityMin = beginErrorProbability_;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// TODO: be nicer about this :)\n\t\t\tthrow new IllegalArgumentException(\"error probability must be >= 0.0 and <= 1.0\");\n\t\t}\n\t}\n\n\tpublic double getBeginErrorProbabilityMax()\n\t{\n\t\treturn beginErrorProbabilityMax;\n\t}\n\n\tpublic void setBeginErrorProbabilityMax(double beginErrorProbabilityMax_)\n\t{\n\t\tif (beginErrorProbabilityMax_ <= 1.0 && beginErrorProbabilityMax_ >= 0.0)\n\t\t{\n\t\t\tbeginErrorProbabilityMax = beginErrorProbabilityMax_;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// TODO: be nicer about this :)\n\t\t\tthrow new IllegalArgumentException(\"error probability must be >= 0.0 and <= 1.0\");\n\t\t}\n\t}\n\n\tpublic double getEndErrorProbabilityMin()\n\t{\n\t\treturn endErrorProbabilityMin;\n\t}\n\n\tpublic void setEndErrorProbabilityMin(double endErrorProbabilityMin_)\n\t{\n\t\tif (endErrorProbabilityMin_ <= 1.0 && endErrorProbabilityMin_ >= 0.0)\n\t\t{\n\t\t\tendErrorProbabilityMin = endErrorProbabilityMin_;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// TODO: be nicer about this :)\n\t\t\tthrow new IllegalArgumentException(\"error probability must be >= 0.0 and <= 1.0\");\n\t\t}\n\t}\n\n\tpublic double getEndErrorProbabilityMax()\n\t{\n\t\treturn endErrorProbabilityMax;\n\t}\n\n\tpublic void setEndErrorProbabilityMax(double endErrorProbability_)\n\t{\n\t\tif (endErrorProbability_ <= 1.0 && endErrorProbability_ >= 0.0)\n\t\t{\n\t\t\tendErrorProbabilityMax = endErrorProbability_;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// TODO: be nicer about this :)\n\t\t\tthrow new IllegalArgumentException(\"error probability must be >= 0.0 and <= 1.0\");\n\t\t}\n\t}\n\n\tpublic double getErrorProbabilityStdDev()\n\t{\n\t\treturn errorProbabilityStdDev;\n\t}\n\n\tpublic void setErrorProbabilityStdDev(double errorProbabilityStdDev_)\n\t{\n\t\tif (errorProbabilityStdDev_ <= 1.0 && errorProbabilityStdDev_ >= 0.0)\n\t\t{\n\t\t\terrorProbabilityStdDev = errorProbabilityStdDev_;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// TODO: be nicer about this :)\n\t\t\tthrow new IllegalArgumentException(\"error std.dev must be >= 0.0\");\n\t\t}\n\t}\n\n\t@Override\n\tpublic CharSequence generateErrors(CharSequence sequence)\n\t{\n\t\t// TODO clean this up\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Fragment generateErrors(Fragment fragment)\n\t{\n\t\tif (verbose)\n\t\t{\n\t\t\tSystem.err.println();\n\t\t\tSystem.err.printf(\"Original sequence: %s%n\", fragment.getSequence());\n\t\t\tSystem.err.print(\" \");\n\t\t}\n\t\tCharSequence sequence = fragment.getSequence();\n\t\tStringBuilder sb = new StringBuilder(sequence.length());\n\t\tStringBuilder errorIndicator = new StringBuilder(sequence.length());\n\t\tdouble errorProbBegin = random.nextDouble() * (beginErrorProbabilityMax - beginErrorProbabilityMin) +\n\t\t\t\tbeginErrorProbabilityMin;\n\t\tdouble errorProbEnd = random.nextDouble() * (endErrorProbabilityMax - endErrorProbabilityMin) +\n\t\t\t\tendErrorProbabilityMin;\n\t\tif (errorProbEnd < errorProbBegin)\n\t\t{\n\t\t\terrorProbEnd = errorProbBegin;\n\t\t}\n\t\tdouble[] qualities = new double[sequence.length()];\n\t\tfor (int i = 0; i < sequence.length(); i++)\n\t\t{\n\t\t\tchar orig = sequence.charAt(i);\n\t\t\tdouble substitutionProbability =\n\t\t\t\t\tgetSubstitutionProbability(i, sequence.length(), errorProbBegin, errorProbEnd);\n\t\t\tqualities[i] = substitutionProbability;\n\t\t\tif (random.nextDouble() <= substitutionProbability)\n\t\t\t{\n\t\t\t\tsb.append(chooseRandomReplacementCharacter(orig));\n\t\t\t\terrorIndicator.append(\"X\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsb.append(orig);\n\t\t\t\terrorIndicator.append(\" \");\n\t\t\t}\n\t\t}\n\t\tif (verbose)\n\t\t{\n\t\t\tSystem.err.println(errorIndicator.toString());\n\t\t\tSystem.err.printf(\"New sequence: %s%n%n\", sb.toString());\n\t\t}\n\t\tFragment f = new Fragment(sb.toString());\n\t\tf.clonePositionsAndReadQuality(fragment);\n\t\tfor (int i = 0; i < sequence.length(); i++)\n\t\t{\n\t\t\tf.setReadQuality(i, phredScaleProbability(qualities[i]));\n\t\t}\n\t\treturn f;\n\t}\n\n\tprotected double getSubstitutionProbability(int position, int length, double begin, double end)\n\t{\n\t\tdouble linear_combination = begin + (end - begin) * ((double) position / (double) length);\n\t\tdouble gaussian_noise = random.nextGaussian() * errorProbabilityStdDev;\n\t\tdouble sum = linear_combination + gaussian_noise;\n\t\treturn Math.max(0.0, Math.min(sum, 1.0));\n\t}\n\n\t/**\n\t * TODO figure out the best way to remove this\n\t *\n\t * @param position\n\t * @param length\n\t * @return\n\t */\n\t@Override\n\tprotected double getSubstitutionProbability(int position, int length)\n\t{\n\t\treturn 0.0;\n\t}\n}" ]
import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator; import generator.SequenceGenerator.Options; import generator.errors.FragmentErrorGenerator; import generator.errors.LinearIncreasingErrorGenerator; import org.junit.Test;
package generator.errors; public class LinearIncreasingErrorGeneratorTest { @Test public void testGenerateErrors() {
SeqGenSingleSequenceMultipleRepeats sg = new SeqGenSingleSequenceMultipleRepeats();
0
Neutrinet/ISP-ng
src/main/java/be/neutrinet/ispng/DNS.java
[ "public class RequestHandler {\n\n static final int FLAG_DNSSECOK = 1;\n static final int FLAG_SIGONLY = 2;\n private Map<Integer, Cache> caches = new HashMap<>();\n\n public Cache getCache(int dclass) {\n Cache c = caches.get(dclass);\n if (c == null) {\n c = new Cache(dclass);\n caches.put(dclass, c);\n }\n return c;\n }\n\n public Zone findBestZone(Name name) {\n Zone foundzone = null;\n foundzone = DNS.zones.get(name);\n if (foundzone != null)\n return foundzone;\n int labels = name.labels();\n for (int i = 1; i < labels; i++) {\n Name tname = new Name(name, i);\n foundzone = DNS.zones.get(tname);\n if (foundzone != null)\n return foundzone;\n }\n return null;\n }\n\n public RRset findExactMatch(Name name, int type, int dclass, boolean glue) {\n Zone zone = findBestZone(name);\n if (zone != null)\n return zone.findExactMatch(name, type);\n else {\n RRset[] rrsets;\n Cache cache = getCache(dclass);\n if (glue)\n rrsets = cache.findAnyRecords(name, type);\n else\n rrsets = cache.findRecords(name, type);\n if (rrsets == null)\n return null;\n else\n return rrsets[0]; /* not quite right */\n }\n }\n\n void addRRset(Name name, Message response, RRset rrset, int section, int flags) {\n for (int s = 1; s <= section; s++)\n if (response.findRRset(name, rrset.getType(), s))\n return;\n if ((flags & FLAG_SIGONLY) == 0) {\n Iterator it = rrset.rrs();\n while (it.hasNext()) {\n Record r = (Record) it.next();\n if (r.getName().isWild() && !name.isWild())\n r = r.withName(name);\n response.addRecord(r, section);\n }\n }\n if ((flags & (FLAG_SIGONLY | FLAG_DNSSECOK)) != 0) {\n Iterator it = rrset.sigs();\n while (it.hasNext()) {\n Record r = (Record) it.next();\n if (r.getName().isWild() && !name.isWild())\n r = r.withName(name);\n response.addRecord(r, section);\n }\n }\n }\n\n private final void addSOA(Message response, Zone zone) {\n response.addRecord(zone.getSOA(), Section.AUTHORITY);\n }\n\n private final void addNS(Message response, Zone zone, int flags) {\n RRset nsRecords = zone.getNS();\n addRRset(nsRecords.getName(), response, nsRecords,\n Section.AUTHORITY, flags);\n }\n\n private final void addCacheNS(Message response, Cache cache, Name name) {\n SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT);\n if (!sr.isDelegation())\n return;\n RRset nsRecords = sr.getNS();\n Iterator it = nsRecords.rrs();\n while (it.hasNext()) {\n Record r = (Record) it.next();\n response.addRecord(r, Section.AUTHORITY);\n }\n }\n\n private void addGlue(Message response, Name name, int flags) {\n RRset a = findExactMatch(name, Type.A, DClass.IN, true);\n if (a == null)\n return;\n addRRset(name, response, a, Section.ADDITIONAL, flags);\n }\n\n private void addAdditional2(Message response, int section, int flags) {\n Record[] Records = response.getSectionArray(section);\n for (Record r : Records) {\n Name glueName = r.getAdditionalName();\n if (glueName != null)\n addGlue(response, glueName, flags);\n }\n }\n\n private final void addAdditional(Message response, int flags) {\n addAdditional2(response, Section.ANSWER, flags);\n addAdditional2(response, Section.AUTHORITY, flags);\n }\n\n byte addAnswer(Message response, Name name, int type, int dclass,\n int iterations, int flags) {\n SetResponse sr;\n byte rcode = Rcode.NOERROR;\n\n if (iterations > 6)\n return Rcode.NOERROR;\n\n if (type == Type.SIG || type == Type.RRSIG) {\n type = Type.ANY;\n flags |= FLAG_SIGONLY;\n }\n\n Zone zone = findBestZone(name);\n if (zone != null)\n sr = zone.findRecords(name, type);\n else {\n Cache cache = getCache(dclass);\n sr = cache.lookupRecords(name, type, Credibility.NORMAL);\n }\n\n if (sr.isUnknown()) {\n addCacheNS(response, getCache(dclass), name);\n }\n if (sr.isNXDOMAIN()) {\n response.getHeader().setRcode(Rcode.NXDOMAIN);\n if (zone != null) {\n addSOA(response, zone);\n if (iterations == 0)\n response.getHeader().setFlag(Flags.AA);\n }\n rcode = Rcode.NXDOMAIN;\n } else if (sr.isNXRRSET()) {\n if (zone != null) {\n addSOA(response, zone);\n if (iterations == 0)\n response.getHeader().setFlag(Flags.AA);\n }\n } else if (sr.isDelegation()) {\n RRset nsRecords = sr.getNS();\n addRRset(nsRecords.getName(), response, nsRecords,\n Section.AUTHORITY, flags);\n } else if (sr.isCNAME()) {\n CNAMERecord cname = sr.getCNAME();\n RRset rrset = new RRset(cname);\n addRRset(name, response, rrset, Section.ANSWER, flags);\n if (zone != null && iterations == 0)\n response.getHeader().setFlag(Flags.AA);\n rcode = addAnswer(response, cname.getTarget(),\n type, dclass, iterations + 1, flags);\n } else if (sr.isDNAME()) {\n DNAMERecord dname = sr.getDNAME();\n RRset rrset = new RRset(dname);\n addRRset(name, response, rrset, Section.ANSWER, flags);\n Name newname;\n try {\n newname = name.fromDNAME(dname);\n } catch (NameTooLongException e) {\n return Rcode.YXDOMAIN;\n }\n rrset = new RRset(new CNAMERecord(name, dclass, 0, newname));\n addRRset(name, response, rrset, Section.ANSWER, flags);\n if (zone != null && iterations == 0)\n response.getHeader().setFlag(Flags.AA);\n rcode = addAnswer(response, newname, type, dclass,\n iterations + 1, flags);\n } else if (sr.isSuccessful()) {\n RRset[] rrsets = sr.answers();\n for (RRset rrset : rrsets)\n addRRset(name, response, rrset,\n Section.ANSWER, flags);\n if (zone != null) {\n addNS(response, zone, flags);\n if (iterations == 0)\n response.getHeader().setFlag(Flags.AA);\n } else\n addCacheNS(response, getCache(dclass), name);\n }\n return rcode;\n }\n\n protected final byte[] doAXFR(Name name, Message query, TSIG tsig, TSIGRecord qtsig, Socket s) {\n Zone zone = DNS.zones.get(name);\n boolean first = true;\n if (zone == null)\n return errorMessage(query, Rcode.REFUSED);\n Iterator it = zone.AXFR();\n try {\n DataOutputStream dataOut;\n dataOut = new DataOutputStream(s.getOutputStream());\n int id = query.getHeader().getID();\n while (it.hasNext()) {\n RRset rrset = (RRset) it.next();\n Message response = new Message(id);\n Header header = response.getHeader();\n header.setFlag(Flags.QR);\n header.setFlag(Flags.AA);\n addRRset(rrset.getName(), response, rrset,\n Section.ANSWER, FLAG_DNSSECOK);\n if (tsig != null) {\n tsig.applyStream(response, qtsig, first);\n qtsig = response.getTSIG();\n }\n first = false;\n byte[] out = response.toWire();\n dataOut.writeShort(out.length);\n dataOut.write(out);\n }\n\n Logger.getLogger(getClass()).info(\"AXFR of \" + zone.getOrigin().toString() + \" to \" + s.getInetAddress().getCanonicalHostName() + \" completed\");\n } catch (IOException ex) {\n Logger.getLogger(getClass()).error(\"AXFR of \" + zone.getOrigin().toString() + \" failed\", ex);\n }\n try {\n s.close();\n } catch (IOException ex) {\n Logger.getLogger(getClass()).error(\"Failed to service AXFR\", ex);\n }\n return null;\n }\n\n /*\n * Note: a null return value means that the caller doesn't need to do\n * anything. Currently this only happens if this is an AXFR request over\n * TCP.\n */\n byte[] generateReply(Message query, byte[] in, int length, Socket s) throws IOException {\n Header header;\n boolean badversion;\n int maxLength;\n int flags = 0;\n\n header = query.getHeader();\n if (header.getFlag(Flags.QR))\n return null;\n if (header.getRcode() != Rcode.NOERROR)\n return errorMessage(query, Rcode.FORMERR);\n if (header.getOpcode() != Opcode.QUERY)\n return errorMessage(query, Rcode.NOTIMP);\n\n Record queryDNSRecord = query.getQuestion();\n\n TSIGRecord queryTSIG = query.getTSIG();\n TSIG tsig = null;\n if (queryTSIG != null) {\n tsig = DNS.TSIG.get(queryTSIG.getName().toString());\n if (tsig == null || tsig.verify(query, in, length, null) != Rcode.NOERROR) {\n Logger.getLogger(getClass()).warn(\"Invalid TSIG key from \" + s.getInetAddress().getCanonicalHostName());\n return formerrMessage(in);\n }\n } else {\n Logger.getLogger(getClass()).warn(\"DNS query without TSIG received from \" + s.getInetAddress().getCanonicalHostName());\n return formerrMessage(in);\n }\n\n OPTRecord queryOPT = query.getOPT();\n if (queryOPT != null && queryOPT.getVersion() > 0)\n badversion = true;\n\n if (s != null)\n maxLength = 65535;\n else if (queryOPT != null)\n maxLength = Math.max(queryOPT.getPayloadSize(), 512);\n else\n maxLength = 512;\n\n if (queryOPT != null && (queryOPT.getFlags() & ExtendedFlags.DO) != 0)\n flags = FLAG_DNSSECOK;\n\n Message response = new Message(query.getHeader().getID());\n response.getHeader().setFlag(Flags.QR);\n if (query.getHeader().getFlag(Flags.RD))\n response.getHeader().setFlag(Flags.RD);\n response.addRecord(queryDNSRecord, Section.QUESTION);\n\n Name name = queryDNSRecord.getName();\n int type = queryDNSRecord.getType();\n int dclass = queryDNSRecord.getDClass();\n if (type == Type.AXFR && s != null)\n return doAXFR(name, query, tsig, queryTSIG, s);\n if (!Type.isRR(type) && type != Type.ANY)\n return errorMessage(query, Rcode.NOTIMP);\n\n byte rcode = addAnswer(response, name, type, dclass, 0, flags);\n if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN)\n return errorMessage(query, rcode);\n\n addAdditional(response, flags);\n\n if (queryOPT != null) {\n int optflags = (flags == FLAG_DNSSECOK) ? ExtendedFlags.DO : 0;\n OPTRecord opt = new OPTRecord((short) 4096, rcode, (byte) 0,\n optflags);\n response.addRecord(opt, Section.ADDITIONAL);\n }\n\n response.setTSIG(tsig, Rcode.NOERROR, queryTSIG);\n return response.toWire(maxLength);\n }\n\n byte[] buildErrorMessage(Header header, int rcode, Record question) {\n Message response = new Message();\n response.setHeader(header);\n for (int i = 0; i < 4; i++)\n response.removeAllRecords(i);\n if (rcode == Rcode.SERVFAIL)\n response.addRecord(question, Section.QUESTION);\n header.setRcode(rcode);\n return response.toWire();\n }\n\n public byte[] formerrMessage(byte[] in) {\n Header header;\n try {\n header = new Header(in);\n } catch (IOException e) {\n return null;\n }\n return buildErrorMessage(header, Rcode.FORMERR, null);\n }\n\n public byte[] errorMessage(Message query, int rcode) {\n return buildErrorMessage(query.getHeader(), rcode,\n query.getQuestion());\n }\n}", "public class TCPServer implements Runnable {\n\n private InetAddress addr;\n private int port;\n private RequestHandler handler;\n private boolean run = true;\n\n public TCPServer(InetAddress addr, int port, RequestHandler handler) {\n this.addr = addr;\n this.port = port;\n this.handler = handler;\n }\n\n public void run() {\n try {\n ServerSocket sock = new ServerSocket(port, 128, addr);\n while (run) {\n final Socket s = sock.accept();\n Thread t;\n\n t = new Thread(new TCPClient(s, handler));\n t.start();\n }\n } catch (IOException ex) {\n Logger.getLogger(getClass()).error(\"Failed to open DNS TCP socket\", ex);\n }\n }\n}", "public class UDPServer implements Runnable {\n\n private boolean run = true;\n private InetAddress addr;\n private int port;\n private RequestHandler handler;\n\n public UDPServer(InetAddress addr, int port, RequestHandler handler) {\n this.addr = addr;\n this.port = port;\n this.handler = handler;\n }\n\n public void stop() {\n run = false;\n }\n\n @Override\n public void run() {\n try {\n DatagramSocket sock = new DatagramSocket(port, addr);\n final short udpLength = 512;\n byte[] in = new byte[udpLength];\n DatagramPacket indp = new DatagramPacket(in, in.length);\n DatagramPacket outdp = null;\n while (run) {\n indp.setLength(in.length);\n try {\n sock.receive(indp);\n } catch (InterruptedIOException e) {\n continue;\n }\n\n Message query;\n byte[] response = null;\n\n try {\n query = new Message(in);\n response = handler.generateReply(query, in, indp.getLength(), null);\n\n if (response == null)\n continue;\n } catch (IOException e) {\n response = handler.formerrMessage(in);\n }\n\n if (outdp == null)\n outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort());\n else {\n outdp.setData(response);\n outdp.setLength(response.length);\n outdp.setAddress(indp.getAddress());\n outdp.setPort(indp.getPort());\n }\n\n sock.send(outdp);\n }\n } catch (IOException e) {\n Logger.getLogger(getClass()).error(\"Failed to service request\", e);\n }\n }\n}", "public class ZoneBuilder {\n\n private final static String PREFIX = \"/ispng/dns/\";\n private final static SimpleDateFormat SERIAL_NUMBER_FORMAT = new SimpleDateFormat(\"YYYYMMDD\");\n public static Name SAME_AS_ROOT;\n\n static {\n try {\n SAME_AS_ROOT = Name.fromString(\"@\");\n } catch (Exception ex) {\n Logger.getLogger(ZoneBuilder.class).error(\"Something went terribly wrong\", ex);\n }\n }\n\n private KeptMap zones;\n private Map<String, KeptList<DNSRecord>> records = new HashMap<>();\n // TODO persist zone serial number suffix\n private Map<String, Integer> suffixes = new HashMap<>();\n private int ttl;\n private List<String> nameServers = new ArrayList<>();\n private Properties cfg;\n\n public void boot(Properties cfg) {\n this.cfg = cfg;\n this.ttl = Integer.parseInt(cfg.getProperty(\"zone.all.record.TTL\"));\n for (String part : cfg.getProperty(\"zone.all.nameservers\").split(\";\")) {\n this.nameServers.add(part.trim());\n }\n\n boot();\n }\n\n public void boot() {\n CuratorFramework cf = Zookeeper.get();\n\n try {\n String dir = \"/ispng/dns\";\n Zookeeper.ensurePathExists(dir);\n\n zones = new KeptMap(cf.getZookeeperClient().getZooKeeper(),\n PREFIX + \"zoneMap\", ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);\n } catch (Exception ex) {\n Logger.getLogger(getClass()).error(\"Failed to boot DNS zones\", ex);\n }\n }\n\n public void renderZonesToZK() {\n try {\n Map<String, List<DNSRecord>> zs = DNSRecords.buildZones();\n zones.clear();\n for (Map.Entry<String, List<DNSRecord>> entry : zs.entrySet()) {\n String label = entry.getKey();\n zones.put(label, DNSRecords.labelToZone.get(entry.getKey()));\n\n Zookeeper.ensurePathExists(PREFIX + \"zones\");\n\n KeptList<DNSRecord> kl = new KeptList<>(DNSRecord.class, Zookeeper.getZK(),\n PREFIX + \"zones/\" + label, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);\n kl.clear();\n kl.addAll(entry.getValue());\n\n records.put(label, kl);\n }\n\n } catch (Exception ex) {\n Logger.getLogger(getClass()).error(\"Failed to rebuild zone info from DB\", ex);\n }\n }\n\n public Map<Name, Zone> rebuildZones() {\n HashMap<Name, Zone> zones = new HashMap<>();\n try {\n for (Map.Entry<String, String> entry : this.zones.entrySet()) {\n KeptList<DNSRecord> kl = new KeptList<>(DNSRecord.class, Zookeeper.getZK(),\n PREFIX + \"zones/\" + entry.getKey(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);\n\n zones.put(Name.fromString(entry.getKey()), buildZone(entry.getValue(), kl));\n }\n } catch (Exception ex) {\n Logger.getLogger(getClass()).error(\"Failed to rebuild zones\", ex);\n }\n\n return zones;\n }\n\n public Zone buildZone(String zoneRoot, List<DNSRecord> DNSRecords) {\n try {\n ArrayList<Record> dnsRecords = new ArrayList<>();\n Name root = Name.fromString(zoneRoot);\n int suffix = suffixes.getOrDefault(zoneRoot, 1);\n int serial = Integer.parseInt(SERIAL_NUMBER_FORMAT.format(new Date()) + String.format(\"%02d\", suffix));\n suffixes.put(zoneRoot, suffix + 1);\n\n // SOA record\n dnsRecords.add(buildSOARecord(Name.concatenate(SAME_AS_ROOT, root), serial));\n\n // NS records\n for (String ns : nameServers) {\n dnsRecords.add(new NSRecord(Name.concatenate(SAME_AS_ROOT, root), DClass.IN, ttl, ensureFQDN(ns)));\n }\n\n // * records\n for (DNSRecord r : DNSRecords)\n dnsRecords.add(buildDNSRecord(root, r));\n\n return new Zone(root, dnsRecords.toArray(new Record[]{}));\n } catch (Exception ex) {\n Logger.getLogger(getClass()).error(\"Failed to build zone \" + zoneRoot, ex);\n }\n\n return null;\n }\n\n private SOARecord buildSOARecord(Name name, int serial) throws Exception {\n return new SOARecord(\n name,\n DClass.IN,\n ttl,\n ensureFQDN(cfg.getProperty(\"zone.all.soa.nameserver\")),\n ensureFQDN(cfg.getProperty(\"zone.all.soa.admin\")),\n serial,\n Integer.parseInt(cfg.getProperty(\"zone.all.soa.refresh\")),\n Integer.parseInt(cfg.getProperty(\"zone.all.soa.retry\")),\n Integer.parseInt(cfg.getProperty(\"zone.all.soa.expiry\")),\n Integer.parseInt(cfg.getProperty(\"zone.all.soa.nxdomainTTL\"))\n );\n }\n\n private Record buildDNSRecord(Name root, DNSRecord record) throws Exception {\n switch (record.getType()) {\n case DNSRecord.PTR:\n return new PTRRecord(Name.fromString(record.getName(), root),\n DClass.IN, record.getTtl(), ensureFQDN(record.getTarget()));\n case DNSRecord.NS:\n return new NSRecord(Name.fromString(record.getName(), root),\n DClass.IN, record.getTtl(), ensureFQDN(record.getTarget()));\n case DNSRecord.AAAA:\n return new AAAARecord(Name.fromString(record.getName(), root),\n DClass.IN, record.getTtl(), InetAddress.getByName(record.getTarget()));\n case DNSRecord.A:\n return new ARecord(Name.fromString(record.getName(), root),\n DClass.IN, record.getTtl(), InetAddress.getByName(record.getTarget()));\n default:\n throw new IllegalArgumentException(\"Invalid DNS record type\");\n }\n }\n\n public void addOrUpdate(DNSRecord r, String zoneLabel) {\n if (r.validate() && DNSRecords.getZoneMapping().containsKey(zoneLabel.toLowerCase())) {\n DNSRecords.getDaoForZone(zoneLabel).ifPresent((dao) -> {\n try {\n dao.createOrUpdate(r);\n\n // todo : atm a full zone rebuild is triggered per modification,\n // obviously that is not so good for performance\n renderZonesToZK();\n } catch (Exception ex) {\n Logger.getLogger(getClass()).error(\"Failed to modify dns record \" +\n r.getName() + \" in zone \" + zoneLabel, ex);\n }\n });\n } else {\n throw new IllegalArgumentException(\"Illegal DNSRecord and/or zone name\");\n }\n }\n\n public final Name ensureFQDN(String name) {\n if (!name.endsWith(\".\")) {\n name += \".\";\n }\n\n try {\n return Name.fromString(name);\n } catch (Exception ex) {\n Logger.getLogger(getClass()).error(\"Failed to get FQDN from \" + name, ex);\n }\n\n return null;\n }\n}", "public class Zookeeper {\n private static CuratorFramework cf;\n\n public static void boot(String connectionString) {\n ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);\n cf = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);\n cf.start();\n }\n\n public static CuratorFramework get() {\n if (cf == null) throw new IllegalStateException(\"Zookeeper has not been initialized\");\n return cf;\n }\n\n public static ZooKeeper getZK() throws Exception {\n return get().getZookeeperClient().getZooKeeper();\n }\n\n public static void ensurePathExists(String path) {\n try {\n Stat stat = cf.checkExists().forPath(path);\n if (stat == null)\n cf.create().creatingParentsIfNeeded().forPath(path, null);\n } catch (Exception ex) {\n Logger.getLogger(Zookeeper.class).error(\"Failed to create path \" + path, ex);\n }\n }\n}" ]
import be.neutrinet.ispng.dns.RequestHandler; import be.neutrinet.ispng.dns.TCPServer; import be.neutrinet.ispng.dns.UDPServer; import be.neutrinet.ispng.dns.ZoneBuilder; import be.neutrinet.ispng.util.Zookeeper; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.xbill.DNS.*; import java.io.FileInputStream; import java.net.InetAddress; import java.util.HashMap; import java.util.Map; import java.util.Properties;
package be.neutrinet.ispng; /** * Created by wannes on 1/24/15. */ public class DNS { public static Map<String, TSIG> TSIG = new HashMap<>(); public static Map<Name, Zone> zones = new HashMap<>(); public static Properties cfg; public static void main(String[] args) { try { Logger root = Logger.getRootLogger(); root.setLevel(Level.INFO); root.addAppender(new ConsoleAppender(VPN.LAYOUT)); cfg = new Properties(); cfg.load(new FileInputStream("dns.properties")); Zookeeper.boot(cfg.getProperty("zookeeper.connectionString")); String TSIGname = cfg.getProperty("tsig.name").toLowerCase() + "."; TSIG.put(TSIGname, new TSIG(cfg.getProperty("tsig.algorithm"), TSIGname, cfg.getProperty("tsig.key"))); ZoneBuilder zoneBuilder = new ZoneBuilder(); zoneBuilder.boot(cfg); zones = zoneBuilder.rebuildZones();
RequestHandler handler = new RequestHandler();
0
talklittle/reddit-is-fun
src/com/andrewshu/android/reddit/mail/InboxActivity.java
[ "public abstract class CaptchaCheckRequiredTask extends AsyncTask<Void, Void, Boolean> {\n\t\n\tprivate static final String TAG = \"CaptchaCheckRequiredTask\";\n\t\n\t// Captcha \"iden\"\n private static final Pattern CAPTCHA_IDEN_PATTERN\n \t= Pattern.compile(\"name=\\\"iden\\\" value=\\\"([^\\\"]+)\\\"\");\n // Group 2: Captcha image absolute path\n private static final Pattern CAPTCHA_IMAGE_PATTERN\n \t= Pattern.compile(\"<img class=\\\"capimage\\\"( alt=\\\"[^\\\"]*\\\")? src=\\\"(/captcha/[^\\\"]+)\\\"\");\n\n \n protected String _mCaptchaIden;\n protected String _mCaptchaUrl;\n \n private String _mCheckUrl;\n private HttpClient _mClient;\n \n\tpublic CaptchaCheckRequiredTask(String checkUrl, HttpClient client) {\n\t\t_mCheckUrl = checkUrl;\n\t\t_mClient = client;\n\t}\n\t\n\t@Override\n\tpublic Boolean doInBackground(Void... voidz) {\n\t\tHttpEntity entity = null;\n\t\tBufferedReader in = null;\n\t\ttry {\n\t\t\tHttpGet request = new HttpGet(_mCheckUrl);\n\t\t\tHttpResponse response = _mClient.execute(request);\n\t\t\tif (!Util.isHttpStatusOK(response)) {\n\t\t\t\tthrow new HttpException(\"bad HTTP response: \"+response);\n\t\t\t}\n\t\t\tentity = response.getEntity();\n \t\tin = new BufferedReader(new InputStreamReader(entity.getContent()));\n \tString line;\n \t\n \twhile ((line = in.readLine()) != null) {\n\t \tMatcher idenMatcher = CAPTCHA_IDEN_PATTERN.matcher(line);\n\t \tMatcher urlMatcher = CAPTCHA_IMAGE_PATTERN.matcher(line);\n\t \tif (idenMatcher.find() && urlMatcher.find()) {\n\t \t\t_mCaptchaIden = idenMatcher.group(1);\n\t \t\t_mCaptchaUrl = urlMatcher.group(2);\n\t \t\tsaveState();\n\t \t\treturn true;\n\t \t}\n \t}\n \t\n \t\t_mCaptchaIden = null;\n \t\t_mCaptchaUrl = null;\n \t\tsaveState();\n \t\treturn false;\n \t\t\n\t\t} catch (Exception e) {\n\t\t\tif (Constants.LOGGING) Log.e(TAG, \"Error accessing \"+_mCheckUrl+\" to check for CAPTCHA\", e);\n \t} finally {\n \t\tif (in != null) {\n \t\t\ttry {\n \t\t\t\tin.close();\n \t\t\t} catch (Exception e2) {\n \t\t\t\tif (Constants.LOGGING) Log.e(TAG, \"in.Close()\", e2);\n \t\t\t}\n \t\t}\n \t\tif (entity != null) {\n \t\t\ttry {\n \t\t\t\tentity.consumeContent();\n \t\t\t} catch (Exception e2) {\n \t\t\t\tif (Constants.LOGGING) Log.e(TAG, \"entity.consumeContent()\", e2);\n \t\t\t}\n \t\t}\n\t\t}\n \t// mCaptchaIden and mCaptchaUrl are null if not required\n \t// so on error, set them to some non-null dummy value\n \t_mCaptchaIden = \"\";\n \t_mCaptchaUrl = \"\";\n \tsaveState();\n\t\treturn null;\n\t}\n\t\n\tabstract protected void saveState();\n}", "public abstract class CaptchaDownloadTask extends AsyncTask<Void, Void, Drawable> {\n\t\n\tprivate static final String TAG = \"CaptchaDownloadTask\";\n\t\n\tprivate String _mCaptchaUrl;\n\tprivate HttpClient _mClient;\n\t\n\tpublic CaptchaDownloadTask(String captchaUrl, HttpClient client) {\n\t\t_mCaptchaUrl = captchaUrl;\n\t\t_mClient = client;\n\t}\n\t@Override\n\tpublic Drawable doInBackground(Void... voidz) {\n\t\ttry {\n\t\t\tHttpGet request = new HttpGet(Constants.REDDIT_BASE_URL + \"/\" + _mCaptchaUrl);\n\t\t\tHttpResponse response = _mClient.execute(request);\n \t\n\t\t\tInputStream in = response.getEntity().getContent();\n\t\t\t\n\t\t\t//get image as bitmap\n\t\t\tBitmap captchaOrg = BitmapFactory.decodeStream(in);\n\n\t\t\t// create matrix for the manipulation\n\t\t\tMatrix matrix = new Matrix();\n\t\t\t// resize the bit map\n\t\t\tmatrix.postScale(2f, 2f);\n\n\t\t\t// recreate the new Bitmap\n\t\t\tBitmap resizedBitmap = Bitmap.createScaledBitmap (captchaOrg,\n\t\t\t\t\tcaptchaOrg.getWidth() * 3, captchaOrg.getHeight() * 3, true);\n\t\t \n\t\t\tBitmapDrawable bmd = new BitmapDrawable(resizedBitmap);\n\t\t\t\n\t\t\treturn bmd;\n\t\t\n\t\t} catch (Exception e) {\n\t\t\tif (Constants.LOGGING) Log.e(TAG, \"download captcha\", e);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\n}", "public class Common {\n\t\n\tprivate static final String TAG = \"Common\";\n\t\n\t// 1:subreddit 2:threadId 3:commentId\n\tprivate static final Pattern COMMENT_LINK = Pattern.compile(Constants.COMMENT_PATH_PATTERN_STRING);\n\tprivate static final Pattern REDDIT_LINK = Pattern.compile(Constants.REDDIT_PATH_PATTERN_STRING);\n\tprivate static final Pattern USER_LINK = Pattern.compile(Constants.USER_PATH_PATTERN_STRING);\n\tprivate static final ObjectMapper mObjectMapper = new ObjectMapper();\n\t\n\tpublic static void showErrorToast(String error, int duration, Context context) {\n\t\tLayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\tToast t = new Toast(context);\n\t\tt.setDuration(duration);\n\t\tView v = inflater.inflate(R.layout.error_toast, null);\n\t\tTextView errorMessage = (TextView) v.findViewById(R.id.errorMessage);\n\t\terrorMessage.setText(error);\n\t\tt.setView(v);\n\t\tt.show();\n\t}\n\t\n public static boolean shouldLoadThumbnails(Activity activity, RedditSettings settings) {\n \t//check for wifi connection and wifi thumbnail setting\n \tboolean thumbOkay = true;\n \tif (settings.isLoadThumbnailsOnlyWifi())\n \t{\n \t\tthumbOkay = false;\n \t\tConnectivityManager connMan = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);\n \t\tNetworkInfo netInfo = connMan.getActiveNetworkInfo();\n \t\tif (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.isConnected()) {\n \t\t\tthumbOkay = true;\n \t\t}\n \t}\n \treturn settings.isLoadThumbnails() && thumbOkay;\n }\n \n\t/**\n * Set the Drawable for the list selector etc. based on the current theme.\n */\n\tpublic static void updateListDrawables(ListActivity la, int theme) {\n\t\tListView lv = la.getListView();\n\t\tif (Util.isLightTheme(theme)) {\n\t\t\tlv.setBackgroundResource(android.R.color.background_light);\n \t\tlv.setSelector(R.drawable.list_selector_blue);\n \t} else /* if (Common.isDarkTheme(theme)) */ {\n \t\tlv.setSelector(android.R.drawable.list_selector_background);\n \t}\n\t}\n\t\n public static void updateNextPreviousButtons(ListActivity act, View nextPreviousView,\n \t\tString after, String before, int count, RedditSettings settings,\n \t\tOnClickListener downloadAfterOnClickListener, OnClickListener downloadBeforeOnClickListener) {\n \tboolean shouldShow = after != null || before != null;\n \tButton nextButton = null;\n \tButton previousButton = null;\n \t\n \t// If alwaysShowNextPrevious, use the navbar\n \tif (settings.isAlwaysShowNextPrevious()) {\n \tnextPreviousView = act.findViewById(R.id.next_previous_layout);\n \tif (nextPreviousView == null)\n \t\treturn;\n \tView nextPreviousBorder = act.findViewById(R.id.next_previous_border_top);\n \t\n\t\t\tif (shouldShow) {\n\t\t \tif (nextPreviousView != null && nextPreviousBorder != null) {\n\t\t\t \tif (Util.isLightTheme(settings.getTheme())) {\n\t\t\t \t\tnextPreviousView.setBackgroundResource(android.R.color.background_light);\n\t\t\t \t\tnextPreviousBorder.setBackgroundResource(R.color.black);\n\t\t\t \t} else {\n\t\t\t \t\tnextPreviousBorder.setBackgroundResource(R.color.white);\n\t\t\t \t}\n\t\t\t \tnextPreviousView.setVisibility(View.VISIBLE);\n\t\t \t}\n\t\t\t\t// update the \"next 25\" and \"prev 25\" buttons\n\t\t \tnextButton = (Button) act.findViewById(R.id.next_button);\n\t\t \tpreviousButton = (Button) act.findViewById(R.id.previous_button);\n\t\t\t} else {\n\t\t\t\tnextPreviousView.setVisibility(View.GONE);\n\t \t}\n \t}\n \t// Otherwise we are using the ListView footer\n \telse {\n \t\tif (nextPreviousView == null)\n \t\t\treturn;\n \t\tif (shouldShow && nextPreviousView.getVisibility() != View.VISIBLE) {\n\t \t\tnextPreviousView.setVisibility(View.VISIBLE);\n \t\t} else if (!shouldShow && nextPreviousView.getVisibility() == View.VISIBLE) {\n \t\t\tnextPreviousView.setVisibility(View.GONE);\n \t\t}\n\t\t\t// update the \"next 25\" and \"prev 25\" buttons\n\t \tnextButton = (Button) nextPreviousView.findViewById(R.id.next_button);\n\t \tpreviousButton = (Button) nextPreviousView.findViewById(R.id.previous_button);\n \t}\n \tif (nextButton != null) {\n\t \tif (after != null) {\n\t \t\tnextButton.setVisibility(View.VISIBLE);\n\t \t\tnextButton.setOnClickListener(downloadAfterOnClickListener);\n\t \t} else {\n\t \t\tnextButton.setVisibility(View.INVISIBLE);\n\t \t}\n \t}\n \tif (previousButton != null) {\n\t \tif (before != null && count != Constants.DEFAULT_THREAD_DOWNLOAD_LIMIT) {\n\t \t\tpreviousButton.setVisibility(View.VISIBLE);\n\t \t\tpreviousButton.setOnClickListener(downloadBeforeOnClickListener);\n\t \t} else {\n\t \t\tpreviousButton.setVisibility(View.INVISIBLE);\n\t \t}\n \t}\n }\n \n public static void setTextColorFromTheme(int theme, Resources resources, TextView... textViews) {\n \tint color;\n \tif (Util.isLightTheme(theme))\n \t\tcolor = resources.getColor(R.color.reddit_light_dialog_text_color);\n \telse\n \t\tcolor = resources.getColor(R.color.reddit_dark_dialog_text_color);\n \tfor (TextView textView : textViews)\n \t\ttextView.setTextColor(color);\n }\n \n \n\t\n static void clearCookies(RedditSettings settings, HttpClient client, Context context) {\n settings.setRedditSessionCookie(null);\n\n RedditIsFunHttpClientFactory.getCookieStore().clear();\n CookieSyncManager.getInstance().sync();\n \n SharedPreferences sessionPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n \tSharedPreferences.Editor editor = sessionPrefs.edit();\n \teditor.remove(\"reddit_sessionValue\");\n \teditor.remove(\"reddit_sessionDomain\");\n \teditor.remove(\"reddit_sessionPath\");\n \teditor.remove(\"reddit_sessionExpiryDate\");\n editor.commit();\n }\n \n \n public static void doLogout(RedditSettings settings, HttpClient client, Context context) {\n \tclearCookies(settings, client, context);\n \tCacheInfo.invalidateAllCaches(context);\n \tsettings.setUsername(null);\n }\n \n \n /**\n * Get a new modhash by scraping and return it\n * \n * @param client\n * @return\n */\n public static String doUpdateModhash(HttpClient client) {\n final Pattern MODHASH_PATTERN = Pattern.compile(\"modhash: '(.*?)'\");\n \tString modhash;\n \tHttpEntity entity = null;\n // The pattern to find modhash from HTML javascript area\n \ttry {\n \t\tHttpGet httpget = new HttpGet(Constants.MODHASH_URL);\n \t\tHttpResponse response = client.execute(httpget);\n \t\t\n \t\t// For modhash, we don't care about the status, since the 404 page has the info we want.\n// \t\tstatus = response.getStatusLine().toString();\n// \tif (!status.contains(\"OK\"))\n// \t\tthrow new HttpException(status);\n \t\n \tentity = response.getEntity();\n\n \tBufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));\n \t// modhash should appear within first 1200 chars\n \tchar[] buffer = new char[1200];\n \tin.read(buffer, 0, 1200);\n \tin.close();\n \tString line = String.valueOf(buffer);\n \tentity.consumeContent();\n \t\n \tif (StringUtils.isEmpty(line)) {\n \t\tthrow new HttpException(\"No content returned from doUpdateModhash GET to \"+Constants.MODHASH_URL);\n \t}\n \tif (line.contains(\"USER_REQUIRED\")) {\n \t\tthrow new Exception(\"User session error: USER_REQUIRED\");\n \t}\n \t\n \tMatcher modhashMatcher = MODHASH_PATTERN.matcher(line);\n \tif (modhashMatcher.find()) {\n \t\tmodhash = modhashMatcher.group(1);\n \t\tif (StringUtils.isEmpty(modhash)) {\n \t\t\t// Means user is not actually logged in.\n \t\t\treturn null;\n \t\t}\n \t} else {\n \t\tthrow new Exception(\"No modhash found at URL \"+Constants.MODHASH_URL);\n \t}\n\n \tif (Constants.LOGGING) Common.logDLong(TAG, line);\n \t\n \tif (Constants.LOGGING) Log.d(TAG, \"modhash: \"+modhash);\n \treturn modhash;\n \t\n \t} catch (Exception e) {\n \t\tif (entity != null) {\n \t\t\ttry {\n \t\t\t\tentity.consumeContent();\n \t\t\t} catch (Exception e2) {\n \t\t\t\tif (Constants.LOGGING) Log.e(TAG, \"entity.consumeContent()\", e);\n \t\t\t}\n \t\t}\n \t\tif (Constants.LOGGING) Log.e(TAG, \"doUpdateModhash()\", e);\n \t\treturn null;\n \t}\n }\n \n public static String checkResponseErrors(HttpResponse response, HttpEntity entity) {\n \tString status = response.getStatusLine().toString();\n \tString line;\n \t\n \tif (!status.contains(\"OK\")) {\n \t\treturn \"HTTP error. Status = \"+status;\n \t}\n \t\n \ttry {\n \t\tBufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));\n \t\tline = in.readLine();\n \t\tif (Constants.LOGGING) Common.logDLong(TAG, line);\n \tin.close();\n \t} catch (IOException e) {\n \t\tif (Constants.LOGGING) Log.e(TAG, \"IOException\", e);\n \t\treturn \"Error reading retrieved data.\";\n \t}\n \t\n \tif (StringUtils.isEmpty(line)) {\n \t\treturn \"API returned empty data.\";\n \t}\n \tif (line.contains(\"WRONG_PASSWORD\")) {\n \t\treturn \"Wrong password.\";\n \t}\n \tif (line.contains(\"USER_REQUIRED\")) {\n \t\t// The modhash probably expired\n \t\treturn \"Login expired.\";\n \t}\n \tif (line.contains(\"SUBREDDIT_NOEXIST\")) {\n \t\treturn \"That subreddit does not exist.\";\n \t}\n \tif (line.contains(\"SUBREDDIT_NOTALLOWED\")) {\n \t\treturn \"You are not allowed to post to that subreddit.\";\n \t}\n \t\n \treturn null;\n }\n \n\n\tpublic static String checkIDResponse(HttpResponse response, HttpEntity entity) throws CaptchaException, Exception {\n\t // Group 1: fullname. Group 2: kind. Group 3: id36.\n\t final Pattern NEW_ID_PATTERN = Pattern.compile(\"\\\"id\\\": \\\"((.+?)_(.+?))\\\"\");\n\t // Group 1: whole error. Group 2: the time part\n\t final Pattern RATELIMIT_RETRY_PATTERN = Pattern.compile(\"(you are trying to submit too fast. try again in (.+?)\\\\.)\");\n\n\t String status = response.getStatusLine().toString();\n \tString line;\n \t\n \tif (!status.contains(\"OK\")) {\n \t\tthrow new Exception(\"HTTP error. Status = \"+status);\n \t}\n \t\n \ttry {\n \t\tBufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));\n \t\tline = in.readLine();\n \t\tif (Constants.LOGGING) Common.logDLong(TAG, line);\n \tin.close();\n \t} catch (IOException e) {\n \t\tif (Constants.LOGGING) Log.e(TAG, \"IOException\", e);\n \t\tthrow new Exception(\"Error reading retrieved data.\");\n \t}\n \t\n \tif (StringUtils.isEmpty(line)) {\n \t\tthrow new Exception(\"API returned empty data.\");\n \t}\n \tif (line.contains(\"WRONG_PASSWORD\")) {\n \t\tthrow new Exception(\"Wrong password.\");\n \t}\n \tif (line.contains(\"USER_REQUIRED\")) {\n \t\t// The modhash probably expired\n \t\tthrow new Exception(\"Login expired.\");\n \t}\n \tif (line.contains(\"SUBREDDIT_NOEXIST\")) {\n \t\tthrow new Exception(\"That subreddit does not exist.\");\n \t}\n \tif (line.contains(\"SUBREDDIT_NOTALLOWED\")) {\n \t\tthrow new Exception(\"You are not allowed to post to that subreddit.\");\n \t}\n \t\n \tString newId;\n \tMatcher idMatcher = NEW_ID_PATTERN.matcher(line);\n \tif (idMatcher.find()) {\n \t\tnewId = idMatcher.group(3);\n \t} else {\n \t\tif (line.contains(\"RATELIMIT\")) {\n \t\t// Try to find the # of minutes using regex\n \tMatcher rateMatcher = RATELIMIT_RETRY_PATTERN.matcher(line);\n \tif (rateMatcher.find())\n \t\tthrow new Exception(rateMatcher.group(1));\n \telse\n \t\tthrow new Exception(\"you are trying to submit too fast. try again in a few minutes.\");\n \t}\n \t\tif (line.contains(\"DELETED_LINK\")) {\n \t\t\tthrow new Exception(\"the link you are commenting on has been deleted\");\n \t\t}\n \t\tif (line.contains(\"BAD_CAPTCHA\")) {\n \t\t\tthrow new CaptchaException(\"Bad CAPTCHA. Try again.\");\n \t\t}\n \t// No id returned by reply POST.\n \t\treturn null;\n \t}\n \t\n \t// Getting here means success.\n \treturn newId;\n\t}\n \n\t\n public static void newMailNotification(Context context, String mailNotificationStyle, int count) {\n \tIntent nIntent = new Intent(context, InboxActivity.class);\n\t\tPendingIntent contentIntent = PendingIntent.getActivity(context, 0, nIntent, 0);\n\t\tNotification notification = new Notification(R.drawable.mail, Constants.HAVE_MAIL_TICKER, System.currentTimeMillis());\n\t\tif (Constants.PREF_MAIL_NOTIFICATION_STYLE_BIG_ENVELOPE.equals(mailNotificationStyle)) {\n\t\t\tRemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.big_envelope_notification);\n\t\t\tnotification.contentView = contentView;\n\t\t} else {\n\t\t\tnotification.setLatestEventInfo(context, Constants.HAVE_MAIL_TITLE,\n\t\t\t\t\tcount + (count == 1 ? \" unread message\" : \" unread messages\"), contentIntent);\n\t\t}\n\t\tnotification.defaults |= Notification.DEFAULT_SOUND;\n\t\tnotification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;\n\t\tnotification.contentIntent = contentIntent;\n\t\tNotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);\n\t\tnotificationManager.notify(Constants.NOTIFICATION_HAVE_MAIL, notification);\n }\n public static void cancelMailNotification(Context context) {\n \tNotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);\n\t\tnotificationManager.cancel(Constants.NOTIFICATION_HAVE_MAIL);\n }\n \n /**\n * \n * @param url\n * @param context\n * @param requireNewTask set this to true if context is not an Activity\n * @param bypassParser\n * @param useExternalBrowser\n */\n public static void launchBrowser(Context context, String url, String threadUrl,\n\t\t\tboolean requireNewTask, boolean bypassParser, boolean useExternalBrowser,\n\t\t\tboolean saveHistory) {\n \t\n \ttry {\n\t\t\tif (saveHistory) {\n\t\t\t\tBrowser.updateVisitedHistory(context.getContentResolver(), url, true);\n\t\t\t}\n \t} catch (Exception ex) {\n \t\tif (Constants.LOGGING) Log.i(TAG, \"Browser.updateVisitedHistory error\", ex);\n \t}\n \t\n \tUri uri = Uri.parse(url);\n \t\n \tif (!bypassParser) {\n \t\tif (Util.isRedditUri(uri)) {\n\t \t\tString path = uri.getPath();\n\t \t\tMatcher matcher = COMMENT_LINK.matcher(path);\n\t\t \tif (matcher.matches()) {\n\t\t \t\tif (matcher.group(3) != null || matcher.group(2) != null) {\n\t\t \t\t\tCacheInfo.invalidateCachedThread(context);\n\t\t \t\t\tIntent intent = new Intent(context, CommentsListActivity.class);\n\t\t \t\t\tintent.setData(uri);\n\t\t \t\t\tintent.putExtra(Constants.EXTRA_NUM_COMMENTS, Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);\n\t\t \t\t\tif (requireNewTask)\n\t\t \t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t\t \t\t\tcontext.startActivity(intent);\n\t\t \t\t\treturn;\n\t\t \t\t}\n\t\t \t}\n\t\t \tmatcher = REDDIT_LINK.matcher(path);\n\t\t \tif (matcher.matches()) {\n\t \t\t\tCacheInfo.invalidateCachedSubreddit(context);\n\t \t\t\tIntent intent = new Intent(context, ThreadsListActivity.class);\n\t \t\t\tintent.setData(uri);\n\t \t\t\tif (requireNewTask)\n\t \t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t \t\t\tcontext.startActivity(intent);\n\t \t\t\treturn;\n\t\t \t}\n\t\t \tmatcher = USER_LINK.matcher(path);\n\t\t \tif (matcher.matches()) {\n\t\t \t\tIntent intent = new Intent(context, ProfileActivity.class);\n\t\t \t\tintent.setData(uri);\n\t \t\t\tif (requireNewTask)\n\t \t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t \t\t\tcontext.startActivity(intent);\n\t \t\t\treturn;\n\t\t \t}\n\t \t} else if (Util.isRedditShortenedUri(uri)) {\n\t \t\tString path = uri.getPath();\n\t \t\tif (path.equals(\"\") || path.equals(\"/\")) {\n\t \t\t\tCacheInfo.invalidateCachedSubreddit(context);\n\t \t\t\tIntent intent = new Intent(context, ThreadsListActivity.class);\n\t \t\t\tintent.setData(uri);\n\t \t\t\tif (requireNewTask)\n\t \t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t \t\t\tcontext.startActivity(intent);\n\t \t\t} else {\n\t\t \t\t// Assume it points to a thread aka CommentsList\n\t \t\t\tCacheInfo.invalidateCachedThread(context);\n\t \t\t\tIntent intent = new Intent(context, CommentsListActivity.class);\n\t \t\t\tintent.setData(uri);\n\t \t\t\tintent.putExtra(Constants.EXTRA_NUM_COMMENTS, Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);\n\t \t\t\tif (requireNewTask)\n\t \t\t\t\tintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t \t\t\tcontext.startActivity(intent);\n\t \t\t}\n \t\t\treturn;\n\t \t}\n \t}\n \turi = Util.optimizeMobileUri(uri);\n \t\n \t// Some URLs should always be opened externally, if BrowserActivity doesn't support their content.\n \tif (Util.isYoutubeUri(uri) || Util.isAndroidMarketUri(uri))\n \t\tuseExternalBrowser = true;\n \t\n \tif (useExternalBrowser) {\n \t\tIntent browser = new Intent(Intent.ACTION_VIEW, uri);\n \t\tbrowser.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());\n\t\t\tif (requireNewTask)\n\t\t\t\tbrowser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t\t\tcontext.startActivity(browser);\n \t} else {\n\t \tIntent browser = new Intent(context, BrowserActivity.class);\n\t \tbrowser.setData(uri);\n\t \tif (threadUrl != null)\n\t \t\tbrowser.putExtra(Constants.EXTRA_THREAD_URL, threadUrl);\n\t\t\tif (requireNewTask)\n\t\t\t\tbrowser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t\t\tcontext.startActivity(browser);\n \t}\n\t}\n \n public static boolean isClicked(Context context, String url) {\n \tCursor cursor;\n \ttry {\n\t\t\tcursor = context.getContentResolver().query(\n\t\t\t\t\tBrowser.BOOKMARKS_URI,\n\t\t\t\t\tBrowser.HISTORY_PROJECTION,\n\t\t\t\t\tBrowser.HISTORY_PROJECTION[Browser.HISTORY_PROJECTION_URL_INDEX] + \"=?\",\n\t\t\t\t\tnew String[]{ url },\n\t\t\t\t\tnull\n\t\t\t);\n \t} catch (Exception ex) {\n \t\tif (Constants.LOGGING) Log.w(TAG, \"Error querying Android Browser for history; manually revoked permission?\", ex);\n \t\treturn false;\n \t}\n \t\n\t\tif (cursor != null) {\n\t boolean isClicked = cursor.moveToFirst(); // returns true if cursor is not empty\n\t cursor.close();\n\t return isClicked;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n }\n \n public static ObjectMapper getObjectMapper() {\n \treturn mObjectMapper;\n }\n \n\tpublic static void logDLong(String tag, String msg) {\n\t\tint c;\n\t\tboolean done = false;\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int k = 0; k < msg.length(); k += 80) {\n\t\t\tfor (int i = 0; i < 80; i++) {\n\t\t\t\tif (k + i >= msg.length()) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tc = msg.charAt(k + i);\n\t\t\t\tsb.append((char) c);\n\t\t\t}\n\t\t\tif (Constants.LOGGING) Log.d(tag, \"multipart log: \" + sb.toString());\n\t\t\tsb = new StringBuilder();\n\t\t\tif (done)\n\t\t\t\tbreak;\n\t\t}\n\t} \n \n public static String getSubredditId(String mSubreddit){\n \tString subreddit_id = null;\n \tJsonNode subredditInfo = \n \tRestJsonClient.connect(Constants.REDDIT_BASE_URL + \"/r/\" + mSubreddit + \"/.json?count=1\");\n \t \t\n \tif(subredditInfo != null){\n \t\tArrayNode children = (ArrayNode) subredditInfo.path(\"data\").path(\"children\");\n \t\tsubreddit_id = children.get(0).get(\"data\").get(\"subreddit_id\").getTextValue();\n \t}\n \treturn subreddit_id;\n }\n\n /** http://developer.android.com/guide/topics/ui/actionbar.html#Home */\n public static void goHome(Activity activity) {\n \t// app icon in action bar clicked; go home\n Intent intent = new Intent(activity, ThreadsListActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n activity.startActivity(intent);\n }\n}", "public class Constants {\n\t\n\tpublic static final boolean LOGGING = true;\n\t\n\tpublic static final boolean USE_COMMENTS_CACHE = false;\n\tpublic static final boolean USE_THREADS_CACHE = false;\n\tpublic static final boolean USE_SUBREDDITS_CACHE = true;\n\t\n\t// File containing the serialized variables of last subreddit viewed\n\tpublic static final String FILENAME_SUBREDDIT_CACHE = \"subreddit.dat\";\n\t// File containing the serialized variables of last comments viewed\n\tpublic static final String FILENAME_THREAD_CACHE = \"thread.dat\";\n\t// File containing a long integer System.currentTimeMillis(). Timestamp is shared among caches.\n\tpublic static final String FILENAME_CACHE_INFO = \"cacheinfo.dat\";\n\tpublic static final String[] FILENAMES_CACHE = {\n\t\tFILENAME_SUBREDDIT_CACHE, FILENAME_THREAD_CACHE, FILENAME_CACHE_INFO\n\t};\n\t\n public static final long MESSAGE_CHECK_MINIMUM_INTERVAL_MILLIS = 5 * 60 * 1000; // 5 minutes\n public static final String LAST_MAIL_CHECK_TIME_MILLIS_KEY = \"LAST_MAIL_CHECK_TIME_MILLIS_KEY\";\n\t\n\t// 1:subreddit 2:threadId 3:commentId\n\t// The following commented-out one is good, but tough to get right, e.g.,\n\t// http://www.reddit.com/eorhm vs. http://www.reddit.com/prefs, mobile, store, etc.\n\t// So, for now require the captured URLs to have /comments or /tb prefix.\n//\tpublic static final String COMMENT_PATH_PATTERN_STRING\n//\t\t= \"(?:/r/([^/]+)/comments|/comments|/tb)?/([^/]+)(?:/?$|/[^/]+/([a-zA-Z0-9]+)?)?\";\n\tpublic static final String COMMENT_PATH_PATTERN_STRING\n\t\t= \"(?:/r/([^/]+)/comments|/comments|/tb)/([^/]+)(?:/?$|/[^/]+/([a-zA-Z0-9]+)?)?\";\n\tpublic static final String REDDIT_PATH_PATTERN_STRING = \"(?:/r/([^/]+))?/?$\";\n\tpublic static final String USER_PATH_PATTERN_STRING = \"/user/([^/]+)/?$\";\n\t\n\tpublic static final String COMMENT_KIND = \"t1\";\n\tpublic static final String THREAD_KIND = \"t3\";\n\tpublic static final String MESSAGE_KIND = \"t4\";\n\tpublic static final String SUBREDDIT_KIND = \"t5\";\n\tpublic static final String MORE_KIND = \"more\";\n \n\tpublic static final int DEFAULT_THREAD_DOWNLOAD_LIMIT = 25;\n public static final int DEFAULT_COMMENT_DOWNLOAD_LIMIT = 200;\n public static final long DEFAULT_FRESH_DURATION = 1800000; // 30 minutes\n public static final long DEFAULT_FRESH_SUBREDDIT_LIST_DURATION = 86400000; // 24 hours\n\n // startActivityForResult request codes\n public static final int ACTIVITY_PICK_SUBREDDIT = 0;\n public static final int ACTIVITY_SUBMIT_LINK = 1;\n \n // notifications\n public static final int NOTIFICATION_HAVE_MAIL = 0;\n \n // services\n public static final int SERVICE_ENVELOPE = 0;\n \n // --- Intent extras ---\n // Tell PickSubredditActivity to hide the fake subreddits string\n public static final String EXTRA_HIDE_FAKE_SUBREDDITS_STRING = \"hideFakeSubreddits\";\n public static final String EXTRA_ID = \"id\";\n // Tell CommentsListActivity to jump to a comment context (a URL. pattern match)\n public static final String EXTRA_COMMENT_CONTEXT = \"jumpToComment\";\n // Tell CommentsListActivity to show \"more children\"\n public static final String EXTRA_MORE_CHILDREN_ID = \"moreChildrenId\";\n public static final String EXTRA_NUM_COMMENTS = \"num_comments\";\n public static final String EXTRA_SUBREDDIT = \"subreddit\";\n public static final String EXTRA_THREAD_URL = \"thread_url\";\n public static final String EXTRA_TITLE = \"title\";\n \n // User-defined result codes\n public static final int RESULT_LOGIN_REQUIRED = Activity.RESULT_FIRST_USER;\n \n // Menu and dialog actions\n public static final int DIALOG_LOGIN = 2;\n public static final int DIALOG_LOGOUT = 3;\n public static final int DIALOG_THEME = 12;\n public static final int DIALOG_REPLY = 14;\n public static final int DIALOG_HIDE_COMMENT = 17;\n public static final int DIALOG_SHOW_COMMENT = 18;\n public static final int DIALOG_SORT_BY = 20;\n public static final int DIALOG_SORT_BY_NEW = 21;\n public static final int DIALOG_SORT_BY_CONTROVERSIAL = 22;\n public static final int DIALOG_SORT_BY_TOP = 23;\n public static final int DIALOG_COMMENT_CLICK = 24;\n public static final int DIALOG_MESSAGE_CLICK = 25;\n public static final int DIALOG_GOTO_PARENT = 28;\n public static final int DIALOG_EDIT = 29;\n public static final int DIALOG_DELETE = 30;\n public static final int DIALOG_COMPOSE = 31;\n public static final int DIALOG_FIND = 32;\n public static final int DIALOG_REPORT = 33;\n public static final int DIALOG_THREAD_CLICK = 34;\n public static final int DIALOG_VIEW_PROFILE = 35;\n\n // progress dialogs\n public static final int DIALOG_LOGGING_IN = 1000;\n public static final int DIALOG_SUBMITTING = 1004;\n public static final int DIALOG_REPLYING = 1005;\n public static final int DIALOG_LOADING_REDDITS_LIST = 1006;\n public static final int DIALOG_DELETING = 1008;\n public static final int DIALOG_EDITING = 1009;\n public static final int DIALOG_COMPOSING = 1012;\n \n\tpublic static final int SHARE_CONTEXT_ITEM = 1013;\n\tpublic static final int OPEN_IN_BROWSER_CONTEXT_ITEM = 1014;\n\tpublic static final int OPEN_COMMENTS_CONTEXT_ITEM = 1015;\n\tpublic static final int SAVE_CONTEXT_ITEM = 1016;\n\tpublic static final int UNSAVE_CONTEXT_ITEM = 1017;\n\tpublic static final int HIDE_CONTEXT_ITEM = 1018;\n\tpublic static final int UNHIDE_CONTEXT_ITEM = 1019;\n\tpublic static final int VIEW_SUBREDDIT_CONTEXT_ITEM = 1020;\n\n \n // Special CSS for webviews to match themes\n public static final String CSS_DARK = \"<style>body{color:#c0c0c0;background-color:#000000}a:link{color:#ffffff}</style>\";\n\n // Colors for markdown\n public static final int MARKDOWN_LINK_COLOR = 0xff2288cc;\n \n // States for StateListDrawables\n public static final int[] STATE_CHECKED = new int[]{android.R.attr.state_checked};\n public static final int[] STATE_NONE = new int[0];\n \n // Strings\n public static final String NO_STRING = \"no\";\n \n public static final String FRONTPAGE_STRING = \"reddit front page\";\n \n public static final String HAVE_MAIL_TICKER = \"reddit mail\";\n public static final String HAVE_MAIL_TITLE = \"reddit is fun\";\n public static final String HAVE_MAIL_TEXT = \"You have reddit mail.\";\n \n // save instance state Bundle keys\n public static final String AFTER_KEY = \"after\";\n public static final String BEFORE_KEY = \"before\";\n public static final String DELETE_TARGET_KIND_KEY = \"delete_target_kind\";\n public static final String EDIT_TARGET_BODY_KEY = \"edit_target_body\";\n public static final String ID_KEY = \"id\";\n public static final String JUMP_TO_THREAD_ID_KEY = \"jump_to_thread_id\";\n public static final String KARMA_KEY = \"karma\";\n public static final String LAST_AFTER_KEY = \"last_after\";\n public static final String LAST_BEFORE_KEY = \"last_before\";\n public static final String REPORT_TARGET_NAME_KEY = \"report_target_name\";\n public static final String REPLY_TARGET_NAME_KEY = \"reply_target_name\";\n public static final String SUBREDDIT_KEY = \"subreddit\";\n public static final String THREAD_COUNT_KEY = \"thread_count\";\n public static final String THREAD_ID_KEY = \"thread_id\";\n public static final String THREAD_LAST_COUNT_KEY = \"last_thread_count\";\n public static final String THREAD_TITLE_KEY = \"thread_title\";\n public static final String USERNAME_KEY = \"username\";\n public static final String VOTE_TARGET_THING_INFO_KEY = \"vote_target_thing_info\";\n public static final String WHICH_INBOX_KEY = \"which_inbox\";\n \n public static final String SUBMIT_KIND_LINK = \"link\";\n public static final String SUBMIT_KIND_SELF = \"self\";\n public static final String SUBMIT_KIND_POLL = \"poll\";\n \n // Sorting things\n public static final class ThreadsSort {\n\t public static final String SORT_BY_KEY = \"threads_sort_by\";\n\t public static final String SORT_BY_HOT = \"hot\";\n\t public static final String SORT_BY_NEW = \"new\";\n\t public static final String SORT_BY_CONTROVERSIAL = \"controversial\";\n\t public static final String SORT_BY_TOP = \"top\";\n\t public static final String SORT_BY_HOT_URL = \"\";\n\t public static final String SORT_BY_NEW_URL = \"new/\";\n\t public static final String SORT_BY_CONTROVERSIAL_URL = \"controversial/\";\n\t public static final String SORT_BY_TOP_URL = \"top/\";\n\t public static final String[] SORT_BY_CHOICES = {SORT_BY_HOT, SORT_BY_NEW, SORT_BY_CONTROVERSIAL, SORT_BY_TOP};\n\t public static final String[] SORT_BY_URL_CHOICES = {SORT_BY_HOT_URL, SORT_BY_NEW_URL, SORT_BY_CONTROVERSIAL_URL, SORT_BY_TOP_URL};\n\t public static final String SORT_BY_NEW_NEW = \"new\";\n\t public static final String SORT_BY_NEW_RISING = \"rising\";\n\t public static final String SORT_BY_NEW_NEW_URL = \"sort=new\";\n\t public static final String SORT_BY_NEW_RISING_URL = \"sort=rising\";\n\t public static final String[] SORT_BY_NEW_CHOICES = {SORT_BY_NEW_NEW, SORT_BY_NEW_RISING};\n\t public static final String[] SORT_BY_NEW_URL_CHOICES = {SORT_BY_NEW_NEW_URL, SORT_BY_NEW_RISING_URL};\n\t public static final String SORT_BY_CONTROVERSIAL_HOUR = \"this hour\";\n\t public static final String SORT_BY_CONTROVERSIAL_DAY = \"today\";\n\t public static final String SORT_BY_CONTROVERSIAL_WEEK = \"this week\";\n\t public static final String SORT_BY_CONTROVERSIAL_MONTH = \"this month\";\n\t public static final String SORT_BY_CONTROVERSIAL_YEAR = \"this year\";\n\t public static final String SORT_BY_CONTROVERSIAL_ALL = \"all time\";\n\t public static final String SORT_BY_CONTROVERSIAL_HOUR_URL = \"t=hour\";\n\t public static final String SORT_BY_CONTROVERSIAL_DAY_URL = \"t=day\";\n\t public static final String SORT_BY_CONTROVERSIAL_WEEK_URL = \"t=week\";\n\t public static final String SORT_BY_CONTROVERSIAL_MONTH_URL = \"t=month\";\n\t public static final String SORT_BY_CONTROVERSIAL_YEAR_URL = \"t=year\";\n\t public static final String SORT_BY_CONTROVERSIAL_ALL_URL = \"t=all\";\n\t public static final String[] SORT_BY_CONTROVERSIAL_CHOICES = {SORT_BY_CONTROVERSIAL_HOUR, SORT_BY_CONTROVERSIAL_DAY,\n\t \tSORT_BY_CONTROVERSIAL_WEEK, SORT_BY_CONTROVERSIAL_MONTH, SORT_BY_CONTROVERSIAL_YEAR, SORT_BY_CONTROVERSIAL_ALL};\n\t public static final String[] SORT_BY_CONTROVERSIAL_URL_CHOICES = {SORT_BY_CONTROVERSIAL_HOUR_URL, SORT_BY_CONTROVERSIAL_DAY_URL,\n\t \tSORT_BY_CONTROVERSIAL_WEEK_URL, SORT_BY_CONTROVERSIAL_MONTH_URL, SORT_BY_CONTROVERSIAL_YEAR_URL, SORT_BY_CONTROVERSIAL_ALL_URL};\n\t public static final String SORT_BY_TOP_HOUR = \"this hour\";\n\t public static final String SORT_BY_TOP_DAY = \"today\";\n\t public static final String SORT_BY_TOP_WEEK = \"this week\";\n\t public static final String SORT_BY_TOP_MONTH = \"this month\";\n\t public static final String SORT_BY_TOP_YEAR = \"this year\";\n\t public static final String SORT_BY_TOP_ALL = \"all time\";\n\t public static final String SORT_BY_TOP_HOUR_URL = \"t=hour\";\n\t public static final String SORT_BY_TOP_DAY_URL = \"t=day\";\n\t public static final String SORT_BY_TOP_WEEK_URL = \"t=week\";\n\t public static final String SORT_BY_TOP_MONTH_URL = \"t=month\";\n\t public static final String SORT_BY_TOP_YEAR_URL = \"t=year\";\n\t public static final String SORT_BY_TOP_ALL_URL = \"t=all\";\n\t public static final String[] SORT_BY_TOP_CHOICES = {SORT_BY_TOP_HOUR, SORT_BY_TOP_DAY,\n\t \tSORT_BY_TOP_WEEK, SORT_BY_TOP_MONTH, SORT_BY_TOP_YEAR, SORT_BY_TOP_ALL};\n\t public static final String[] SORT_BY_TOP_URL_CHOICES = {SORT_BY_TOP_HOUR_URL, SORT_BY_TOP_DAY_URL,\n\t \tSORT_BY_TOP_WEEK_URL, SORT_BY_TOP_MONTH_URL, SORT_BY_TOP_YEAR_URL, SORT_BY_TOP_ALL_URL};\n }\n public static final class CommentsSort {\n\t public static final String SORT_BY_KEY = \"comments_sort_by\";\n\t public static final String SORT_BY_BEST = \"best\";\n\t public static final String SORT_BY_HOT = \"hot\";\n\t public static final String SORT_BY_NEW = \"new\";\n\t public static final String SORT_BY_CONTROVERSIAL = \"controversial\";\n\t public static final String SORT_BY_TOP = \"top\";\n\t public static final String SORT_BY_OLD = \"old\";\n\t public static final String SORT_BY_BEST_URL = \"sort=confidence\";\n\t public static final String SORT_BY_HOT_URL = \"sort=hot\";\n\t public static final String SORT_BY_NEW_URL = \"sort=new\";\n\t public static final String SORT_BY_CONTROVERSIAL_URL = \"sort=controversial\";\n\t public static final String SORT_BY_TOP_URL = \"sort=top\";\n\t public static final String SORT_BY_OLD_URL = \"sort=old\";\n\t public static final String[] SORT_BY_CHOICES =\n\t \t{SORT_BY_BEST, SORT_BY_HOT, SORT_BY_NEW,\n\t \tSORT_BY_CONTROVERSIAL, SORT_BY_TOP, SORT_BY_OLD};\n\t public static final String[] SORT_BY_URL_CHOICES =\n\t \t{SORT_BY_BEST_URL, SORT_BY_HOT_URL, SORT_BY_NEW_URL,\n\t \tSORT_BY_CONTROVERSIAL_URL, SORT_BY_TOP_URL, SORT_BY_OLD_URL};\n }\n \n \n // JSON values\n public static final String JSON_AFTER = \"after\";\n public static final String JSON_AUTHOR = \"author\";\n public static final String JSON_BEFORE = \"before\";\n public static final String JSON_BODY = \"body\";\n public static final String JSON_CHILDREN = \"children\";\n public static final String JSON_DATA = \"data\";\n public static final String JSON_ERRORS = \"errors\";\n public static final String JSON_JSON = \"json\";\n public static final String JSON_KIND = \"kind\";\n public static final String JSON_LISTING = \"Listing\";\n public static final String JSON_MEDIA = \"media\";\n public static final String JSON_MEDIA_EMBED = \"media_embed\";\n public static final String JSON_MODHASH = \"modhash\";\n public static final String JSON_NEW = \"new\";\n public static final String JSON_NUM_COMMENTS = \"num_comments\";\n public static final String JSON_TITLE = \"title\";\n public static final String JSON_SUBREDDIT = \"subreddit\";\n\tpublic static final String JSON_REPLIES = \"replies\";\n\tpublic static final String JSON_SELFTEXT = \"selftext\";\n\tpublic static final String JSON_SELFTEXT_HTML = \"selftext_html\";\n\tpublic static final String JSON_SUBJECT = \"subject\";\n \n // TabSpec tags\n public static final String TAB_LINK = \"tab_link\";\n public static final String TAB_TEXT = \"tab_text\";\n \n // Preference keys and values\n public static final String PREF_HOMEPAGE = \"homepage\";\n public static final String PREF_USE_EXTERNAL_BROWSER = \"use_external_browser\";\n public static final String PREF_CONFIRM_QUIT = \"confirm_quit\";\n public static final String PREF_SAVE_HISTORY = \"save_history\";\n public static final String PREF_ALWAYS_SHOW_NEXT_PREVIOUS = \"always_show_next_previous\";\n public static final String PREF_COMMENTS_SORT_BY_URL = \"sort_by_url\";\n public static final String PREF_THEME = \"theme\";\n public static final String PREF_THEME_LIGHT = \"THEME_LIGHT\";\n public static final String PREF_THEME_DARK\t = \"THEME_DARK\";\n public static final String PREF_TEXT_SIZE = \"text_size\";\n public static final String PREF_TEXT_SIZE_MEDIUM = \"TEXT_SIZE_MEDIUM\";\n public static final String PREF_TEXT_SIZE_LARGE = \"TEXT_SIZE_LARGE\";\n public static final String PREF_TEXT_SIZE_LARGER = \"TEXT_SIZE_LARGER\";\n public static final String PREF_TEXT_SIZE_HUGE = \"TEXT_SIZE_HUGE\";\n public static final String PREF_SHOW_COMMENT_GUIDE_LINES = \"show_comment_guide_lines\";\n public static final String PREF_ROTATION = \"rotation\";\n public static final String PREF_ROTATION_UNSPECIFIED = \"ROTATION_UNSPECIFIED\";\n public static final String PREF_ROTATION_PORTRAIT = \"ROTATION_PORTRAIT\";\n public static final String PREF_ROTATION_LANDSCAPE = \"ROTATION_LANDSCAPE\";\n public static final String PREF_LOAD_THUMBNAILS = \"load_thumbnails\";\n public static final String PREF_LOAD_THUMBNAILS_ONLY_WIFI = \"load_thumbnails_only_wifi\";\n public static final String PREF_MAIL_NOTIFICATION_STYLE = \"mail_notification_style\";\n public static final String PREF_MAIL_NOTIFICATION_STYLE_DEFAULT = \"MAIL_NOTIFICATION_STYLE_DEFAULT\";\n public static final String PREF_MAIL_NOTIFICATION_STYLE_BIG_ENVELOPE = \"MAIL_NOTIFICATION_STYLE_BIG_ENVELOPE\";\n public static final String PREF_MAIL_NOTIFICATION_STYLE_OFF = \"MAIL_NOTIFICATION_STYLE_OFF\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE = \"mail_notification_service\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE_OFF = \"MAIL_NOTIFICATION_SERVICE_OFF\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE_5MIN = \"MAIL_NOTIFICATION_SERVICE_5MIN\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE_30MIN = \"MAIL_NOTIFICATION_SERVICE_30MIN\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE_1HOUR = \"MAIL_NOTIFICATION_SERVICE_1HOUR\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE_6HOURS = \"MAIL_NOTIFICATION_SERVICE_6HOURS\";\n public static final String PREF_MAIL_NOTIFICATION_SERVICE_1DAY = \"MAIL_NOTIFICATION_SERVICE_1DAY\";\n \n // Reddit's base URL, without trailing slash\n public static final String REDDIT_BASE_URL = \"http://www.reddit.com\";\n public static final String REDDIT_SSL_BASE_URL = \"https://pay.reddit.com\";\n\tpublic static final String REDDIT_LOGIN_URL = \"https://ssl.reddit.com/api/login\";\n\t\n // A short HTML file returned by reddit, so we can get the modhash\n public static final String MODHASH_URL = REDDIT_BASE_URL + \"/r\";\n}", "public class FormValidation {\n\n public static boolean validateComposeMessageInputFields(\n \t\tContext context,\n \t\tfinal EditText composeDestination,\n\t\t\tfinal EditText composeSubject,\n\t\t\tfinal EditText composeText,\n\t\t\tfinal EditText composeCaptcha\n\t) {\n\t\t// reddit.com performs these sanity checks too.\n\t\tif (\"\".equals(composeDestination.getText().toString().trim())) {\n\t\t\tToast.makeText(context, \"please enter a username\", Toast.LENGTH_LONG).show();\n\t\t\treturn false;\n\t\t}\n\t\tif (\"\".equals(composeSubject.getText().toString().trim())) {\n\t\t\tToast.makeText(context, \"please enter a subject\", Toast.LENGTH_LONG).show();\n\t\t\treturn false;\n\t\t}\n\t\tif (\"\".equals(composeText.getText().toString().trim())) {\n\t\t\tToast.makeText(context, \"you need to enter a message\", Toast.LENGTH_LONG).show();\n\t\t\treturn false;\n\t\t}\n\t\tif (composeCaptcha.getVisibility() == View.VISIBLE && \"\".equals(composeCaptcha.getText().toString().trim())) {\n\t\t\tToast.makeText(context, \"\", Toast.LENGTH_LONG).show();\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\n}", "public class RedditIsFunHttpClientFactory {\n\t\n\tprivate static final String TAG = \"RedditIsFunHttpClientFactory\";\n\t\n\tprivate static final DefaultHttpClient mGzipHttpClient = createGzipHttpClient();\n\tprivate static final CookieStore mCookieStore = mGzipHttpClient.getCookieStore();\n\n\t// Default connection and socket timeout of 60 seconds. Tweak to taste.\n\tprivate static final int SOCKET_OPERATION_TIMEOUT = 60 * 1000;\n\n\tstatic DefaultHttpClient createGzipHttpClient() {\n\t\tHttpParams params = new BasicHttpParams();\n\t\tparams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);\n\t\t\n\t\tDefaultHttpClient httpclient = new DefaultHttpClient(params) {\n\t\t @Override\n\t\t protected ClientConnectionManager createClientConnectionManager() {\n\t\t SchemeRegistry registry = new SchemeRegistry();\n\t\t registry.register(\n\t\t new Scheme(\"http\", PlainSocketFactory.getSocketFactory(), 80));\n\t\t registry.register(\n\t\t \t\tnew Scheme(\"https\", getHttpsSocketFactory(), 443));\n\t\t HttpParams params = getParams();\n\t\t\t\tHttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);\n\t\t\t\tHttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);\n\t\t\t\tHttpConnectionParams.setSocketBufferSize(params, 8192);\n\t\t return new ThreadSafeClientConnManager(params, registry);\n\t\t }\n\t\t \n\t\t /** Gets an HTTPS socket factory with SSL Session Caching if such support is available, otherwise falls back to a non-caching factory\n\t\t * @return\n\t\t */\n\t\t protected SocketFactory getHttpsSocketFactory(){\n\t\t\t\ttry {\n\t\t\t\t\tClass<?> sslSessionCacheClass = Class.forName(\"android.net.SSLSessionCache\");\n\t\t\t \tObject sslSessionCache = sslSessionCacheClass.getConstructor(Context.class).newInstance(RedditIsFunApplication.getApplication());\n\t\t\t \tMethod getHttpSocketFactory = Class.forName(\"android.net.SSLCertificateSocketFactory\").getMethod(\"getHttpSocketFactory\", new Class<?>[]{int.class, sslSessionCacheClass});\n\t\t\t \treturn (SocketFactory) getHttpSocketFactory.invoke(null, SOCKET_OPERATION_TIMEOUT, sslSessionCache);\n\t\t\t\t}catch(Exception e){\n\t\t\t\t\treturn SSLSocketFactory.getSocketFactory();\n\t\t\t\t}\n\t\t }\n\t\t};\n\t\t\n\t\t\n httpclient.addRequestInterceptor(new HttpRequestInterceptor() {\n public void process(\n final HttpRequest request,\n final HttpContext context\n ) throws HttpException, IOException {\n \tRedditIsFunApplication app = RedditIsFunApplication.getApplication();\n \tString version;\n\t\t\t\ttry {\n\t\t\t\t\tversion = app.getPackageManager().getPackageInfo(app.getPackageName(), 0).versionName;\n\t\t\t\t} catch (NameNotFoundException e) {\n\t\t\t\t\tLog.e(TAG, \"Package name not found.\", e);\n\t\t\t\t\tversion = \"1\";\n\t\t\t\t}\n \tString userAgent = app.getString(R.string.user_agent, version);\n request.setHeader(\"User-Agent\", userAgent);\n \t\n if (!request.containsHeader(\"Accept-Encoding\"))\n request.addHeader(\"Accept-Encoding\", \"gzip\");\n }\n });\n httpclient.addResponseInterceptor(new HttpResponseInterceptor() {\n public void process(\n final HttpResponse response, \n final HttpContext context) throws HttpException, IOException {\n HttpEntity entity = response.getEntity();\n Header ceheader = entity.getContentEncoding();\n if (ceheader != null) {\n HeaderElement[] codecs = ceheader.getElements();\n for (int i = 0; i < codecs.length; i++) {\n if (codecs[i].getName().equalsIgnoreCase(\"gzip\")) {\n response.setEntity(\n new GzipDecompressingEntity(response.getEntity())); \n return;\n }\n }\n }\n }\n });\n return httpclient;\n\t}\n static class GzipDecompressingEntity extends HttpEntityWrapper {\n public GzipDecompressingEntity(final HttpEntity entity) {\n super(entity);\n }\n @Override\n public InputStream getContent()\n throws IOException, IllegalStateException {\n // the wrapped entity's getContent() decides about repeatability\n InputStream wrappedin = wrappedEntity.getContent();\n return new GZIPInputStream(wrappedin);\n }\n @Override\n public long getContentLength() {\n // length of ungzipped content is not known\n return -1;\n }\n }\n\t/**\n\t * http://hc.apache.org/httpcomponents-client/examples.html\n\t * @return a Gzip-enabled DefaultHttpClient\n\t */\n\tpublic static HttpClient getGzipHttpClient() {\n\t\treturn mGzipHttpClient;\n\t}\n\tpublic static CookieStore getCookieStore() {\n\t\treturn mCookieStore;\n\t}\n\n}", "public class RedditSettings {\n\t\n\tprivate static final String TAG = \"RedditSettings\";\n\t\n\tprivate String username = null;\n\tprivate Cookie redditSessionCookie = null;\n\tprivate String modhash = null;\n\tprivate String homepage = Constants.FRONTPAGE_STRING;\n\tprivate boolean useExternalBrowser = false;\n\tprivate boolean showCommentGuideLines = true;\n\tprivate boolean confirmQuitOrLogout = true;\n\tprivate boolean saveHistory = true;\n\tprivate boolean alwaysShowNextPrevious = true;\n\t\n\tprivate int threadDownloadLimit = Constants.DEFAULT_THREAD_DOWNLOAD_LIMIT;\n\tprivate String commentsSortByUrl = Constants.CommentsSort.SORT_BY_BEST_URL;\n\t\n \n\t// --- Themes ---\n\tprivate int theme = R.style.Reddit_Light_Medium;\n\tprivate int rotation = -1; // -1 means unspecified\n\tprivate boolean loadThumbnails = true;\n\tprivate boolean loadThumbnailsOnlyWifi = false;\n\t\n\tprivate String mailNotificationStyle = Constants.PREF_MAIL_NOTIFICATION_STYLE_DEFAULT;\n\tprivate String mailNotificationService = Constants.PREF_MAIL_NOTIFICATION_SERVICE_OFF;\n\t\n\t\n\t\n\t//\n\t// --- Methods ---\n\t//\n\t\n\t// --- Preferences ---\n\tpublic static class Rotation {\n\t\t/* From http://developer.android.com/reference/android/R.attr.html#screenOrientation\n\t\t * unspecified -1\n\t\t * landscape 0\n\t\t * portrait 1\n\t\t * user 2\n\t\t * behind 3\n\t\t * sensor 4\n\t\t * nosensor 5\n\t\t */\n\t\tpublic static int valueOf(String valueString) {\n\t\t\tif (Constants.PREF_ROTATION_UNSPECIFIED.equals(valueString))\n\t\t\t\treturn -1;\n\t\t\tif (Constants.PREF_ROTATION_PORTRAIT.equals(valueString))\n\t\t\t\treturn 1;\n\t\t\tif (Constants.PREF_ROTATION_LANDSCAPE.equals(valueString))\n\t\t\t\treturn 0;\n\t\t\treturn -1;\n\t\t}\n\t\tpublic static String toString(int value) {\n\t\t\tswitch (value) {\n\t\t\tcase -1:\n\t\t\t\treturn Constants.PREF_ROTATION_UNSPECIFIED;\n\t\t\tcase 1:\n\t\t\t\treturn Constants.PREF_ROTATION_PORTRAIT;\n\t\t\tcase 0:\n\t\t\t\treturn Constants.PREF_ROTATION_LANDSCAPE;\n\t\t\tdefault:\n\t\t\t\treturn Constants.PREF_ROTATION_UNSPECIFIED;\n\t\t\t}\n\t\t}\n\t}\n\t\n public void saveRedditPreferences(Context context) {\n \tSharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);\n \tSharedPreferences.Editor editor = settings.edit();\n \t\n \t// Session\n \tif (this.username != null)\n \t\teditor.putString(\"username\", this.username);\n \telse\n \t\teditor.remove(\"username\");\n \tif (this.redditSessionCookie != null) {\n \t\teditor.putString(\"reddit_sessionValue\", this.redditSessionCookie.getValue());\n \t\teditor.putString(\"reddit_sessionDomain\", this.redditSessionCookie.getDomain());\n \t\teditor.putString(\"reddit_sessionPath\", this.redditSessionCookie.getPath());\n \t\tif (this.redditSessionCookie.getExpiryDate() != null)\n \t\t\teditor.putLong(\"reddit_sessionExpiryDate\", this.redditSessionCookie.getExpiryDate().getTime());\n \t}\n \tif (this.modhash != null)\n \t\teditor.putString(\"modhash\", this.modhash.toString());\n \t\n \t// Default subreddit\n \teditor.putString(Constants.PREF_HOMEPAGE, this.homepage.toString());\n \t\n \t// Use external browser instead of BrowserActivity\n \teditor.putBoolean(Constants.PREF_USE_EXTERNAL_BROWSER, this.useExternalBrowser);\n\n \t// Show confirmation dialog when backing out of root Activity\n \teditor.putBoolean(Constants.PREF_CONFIRM_QUIT, this.confirmQuitOrLogout);\n\n \t// Save reddit history to Browser history\n \teditor.putBoolean(Constants.PREF_SAVE_HISTORY, this.saveHistory);\n \t\n \t// Whether to always show the next/previous buttons, or only at bottom of list\n \teditor.putBoolean(Constants.PREF_ALWAYS_SHOW_NEXT_PREVIOUS, this.alwaysShowNextPrevious);\n \t\n \t// Comments sort order\n \teditor.putString(Constants.PREF_COMMENTS_SORT_BY_URL, this.commentsSortByUrl);\n \t\n \t// Theme and text size\n \tString[] themeTextSize = Util.getPrefsFromThemeResource(this.theme);\n \teditor.putString(Constants.PREF_THEME, themeTextSize[0]);\n \teditor.putString(Constants.PREF_TEXT_SIZE, themeTextSize[1]);\n \t\n \t// Comment guide lines\n \teditor.putBoolean(Constants.PREF_SHOW_COMMENT_GUIDE_LINES, this.showCommentGuideLines);\n \t\n \t// Rotation\n \teditor.putString(Constants.PREF_ROTATION, RedditSettings.Rotation.toString(this.rotation));\n \t\n \t// Thumbnails\n \teditor.putBoolean(Constants.PREF_LOAD_THUMBNAILS, this.loadThumbnails);\n \teditor.putBoolean(Constants.PREF_LOAD_THUMBNAILS_ONLY_WIFI, this.loadThumbnailsOnlyWifi);\n \t\n \t// Notifications\n \teditor.putString(Constants.PREF_MAIL_NOTIFICATION_STYLE, this.mailNotificationStyle);\n \teditor.putString(Constants.PREF_MAIL_NOTIFICATION_SERVICE, this.mailNotificationService);\n\n \teditor.commit();\n }\n \n public void loadRedditPreferences(Context context, HttpClient client) {\n // Session\n \tSharedPreferences sessionPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n \tthis.setUsername(sessionPrefs.getString(\"username\", null));\n \tthis.setModhash(sessionPrefs.getString(\"modhash\", null));\n String cookieValue = sessionPrefs.getString(\"reddit_sessionValue\", null);\n String cookieDomain = sessionPrefs.getString(\"reddit_sessionDomain\", null);\n String cookiePath = sessionPrefs.getString(\"reddit_sessionPath\", null);\n long cookieExpiryDate = sessionPrefs.getLong(\"reddit_sessionExpiryDate\", -1);\n if (cookieValue != null) {\n \tBasicClientCookie redditSessionCookie = new BasicClientCookie(\"reddit_session\", cookieValue);\n \tredditSessionCookie.setDomain(cookieDomain);\n \tredditSessionCookie.setPath(cookiePath);\n \tif (cookieExpiryDate != -1)\n \t\tredditSessionCookie.setExpiryDate(new Date(cookieExpiryDate));\n \telse\n \t\tredditSessionCookie.setExpiryDate(null);\n \tthis.setRedditSessionCookie(redditSessionCookie);\n \t\tRedditIsFunHttpClientFactory.getCookieStore().addCookie(redditSessionCookie);\n \t\ttry {\n \t\t\tCookieSyncManager.getInstance().sync();\n \t\t} catch (IllegalStateException ex) {\n \t\t\tif (Constants.LOGGING) Log.e(TAG, \"CookieSyncManager.getInstance().sync()\", ex);\n \t\t}\n }\n \n // Default subreddit\n String homepage = sessionPrefs.getString(Constants.PREF_HOMEPAGE, Constants.FRONTPAGE_STRING).trim();\n if (StringUtils.isEmpty(homepage))\n \tthis.setHomepage(Constants.FRONTPAGE_STRING);\n else\n \tthis.setHomepage(homepage);\n \n \t// Use external browser instead of BrowserActivity\n this.setUseExternalBrowser(sessionPrefs.getBoolean(Constants.PREF_USE_EXTERNAL_BROWSER, false));\n\n \t// Show confirmation dialog when backing out of root Activity\n this.setConfirmQuitOrLogout(sessionPrefs.getBoolean(Constants.PREF_CONFIRM_QUIT, true));\n\n // Save reddit history to Browser history\n this.setSaveHistory(sessionPrefs.getBoolean(Constants.PREF_SAVE_HISTORY, true));\n \n \t// Whether to always show the next/previous buttons, or only at bottom of list\n this.setAlwaysShowNextPrevious(sessionPrefs.getBoolean(Constants.PREF_ALWAYS_SHOW_NEXT_PREVIOUS, true));\n \n \t// Comments sort order\n this.setCommentsSortByUrl(sessionPrefs.getString(Constants.PREF_COMMENTS_SORT_BY_URL, Constants.CommentsSort.SORT_BY_BEST_URL));\n \n // Theme and text size\n this.setTheme(Util.getThemeResourceFromPrefs(\n \t\tsessionPrefs.getString(Constants.PREF_THEME, Constants.PREF_THEME_LIGHT),\n \t\tsessionPrefs.getString(Constants.PREF_TEXT_SIZE, Constants.PREF_TEXT_SIZE_MEDIUM)));\n \n // Comment guide lines\n this.setShowCommentGuideLines(sessionPrefs.getBoolean(Constants.PREF_SHOW_COMMENT_GUIDE_LINES, true));\n \n // Rotation\n this.setRotation(RedditSettings.Rotation.valueOf(\n \t\tsessionPrefs.getString(Constants.PREF_ROTATION, Constants.PREF_ROTATION_UNSPECIFIED)));\n \n // Thumbnails\n this.setLoadThumbnails(sessionPrefs.getBoolean(Constants.PREF_LOAD_THUMBNAILS, true));\n // Thumbnails on Wifi\n this.setLoadThumbnailsOnlyWifi(sessionPrefs.getBoolean(Constants.PREF_LOAD_THUMBNAILS_ONLY_WIFI, false));\n \n // Notifications\n this.setMailNotificationStyle(sessionPrefs.getString(Constants.PREF_MAIL_NOTIFICATION_STYLE, Constants.PREF_MAIL_NOTIFICATION_STYLE_DEFAULT));\n this.setMailNotificationService(sessionPrefs.getString(Constants.PREF_MAIL_NOTIFICATION_SERVICE, Constants.PREF_MAIL_NOTIFICATION_SERVICE_OFF));\n }\n \n public int getDialogTheme() {\n \tif (Util.isLightTheme(theme))\n \t\treturn R.style.Reddit_Light_Dialog;\n \telse\n \t\treturn R.style.Reddit_Dark_Dialog;\n }\n \n public int getDialogNoTitleTheme() {\n \tif (Util.isLightTheme(theme))\n \t\treturn R.style.Reddit_Light_Dialog_NoTitle;\n \telse\n \t\treturn R.style.Reddit_Dark_Dialog_NoTitle;\n }\n\n\tpublic boolean isLoggedIn() {\n\t\treturn username != null;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic Cookie getRedditSessionCookie() {\n\t\treturn redditSessionCookie;\n\t}\n\n\tpublic void setRedditSessionCookie(Cookie redditSessionCookie) {\n\t\tthis.redditSessionCookie = redditSessionCookie;\n\t}\n\n\tpublic String getModhash() {\n\t\treturn modhash;\n\t}\n\n\tpublic void setModhash(String modhash) {\n\t\tthis.modhash = modhash;\n\t}\n\n\tpublic String getHomepage() {\n\t\treturn homepage;\n\t}\n\n\tpublic void setHomepage(String homepage) {\n\t\tthis.homepage = homepage;\n\t}\n\n\tpublic boolean isUseExternalBrowser() {\n\t\treturn useExternalBrowser;\n\t}\n\n\tpublic void setUseExternalBrowser(boolean useExternalBrowser) {\n\t\tthis.useExternalBrowser = useExternalBrowser;\n\t}\n\n\tpublic boolean isShowCommentGuideLines() {\n\t\treturn showCommentGuideLines;\n\t}\n\n\tpublic void setShowCommentGuideLines(boolean showCommentGuideLines) {\n\t\tthis.showCommentGuideLines = showCommentGuideLines;\n\t}\n\n\tpublic boolean isConfirmQuitOrLogout() {\n\t\treturn confirmQuitOrLogout;\n\t}\n\n\tpublic boolean isSaveHistory() {\n\t\treturn saveHistory;\n\t}\n\n\tpublic void setConfirmQuitOrLogout(boolean confirmQuitOrLogout) {\n\t\tthis.confirmQuitOrLogout = confirmQuitOrLogout;\n\t}\n\n\tpublic void setSaveHistory(boolean saveHistory) {\n\t\tthis.saveHistory = saveHistory;\n\t}\n\n\tpublic boolean isAlwaysShowNextPrevious() {\n\t\treturn alwaysShowNextPrevious;\n\t}\n\n\tpublic void setAlwaysShowNextPrevious(boolean alwaysShowNextPrevious) {\n\t\tthis.alwaysShowNextPrevious = alwaysShowNextPrevious;\n\t}\n\n\tpublic int getThreadDownloadLimit() {\n\t\treturn threadDownloadLimit;\n\t}\n\n\tpublic void setThreadDownloadLimit(int threadDownloadLimit) {\n\t\tthis.threadDownloadLimit = threadDownloadLimit;\n\t}\n\n\tpublic String getCommentsSortByUrl() {\n\t\treturn commentsSortByUrl;\n\t}\n\n\tpublic void setCommentsSortByUrl(String commentsSortByUrl) {\n\t\tthis.commentsSortByUrl = commentsSortByUrl;\n\t}\n\n\tpublic int getTheme() {\n\t\treturn theme;\n\t}\n\n\tpublic void setTheme(int theme) {\n\t\tthis.theme = theme;\n\t}\n\n\tpublic int getRotation() {\n\t\treturn rotation;\n\t}\n\n\tpublic void setRotation(int rotation) {\n\t\tthis.rotation = rotation;\n\t}\n\n\tpublic boolean isLoadThumbnails() {\n\t\treturn loadThumbnails;\n\t}\n\n\tpublic void setLoadThumbnails(boolean loadThumbnails) {\n\t\tthis.loadThumbnails = loadThumbnails;\n\t}\n\n\tpublic boolean isLoadThumbnailsOnlyWifi() {\n\t\treturn loadThumbnailsOnlyWifi;\n\t}\n\n\tpublic void setLoadThumbnailsOnlyWifi(boolean loadThumbnailsOnlyWifi) {\n\t\tthis.loadThumbnailsOnlyWifi = loadThumbnailsOnlyWifi;\n\t}\n\n\tpublic String getMailNotificationStyle() {\n\t\treturn mailNotificationStyle;\n\t}\n\n\tpublic void setMailNotificationStyle(String mailNotificationStyle) {\n\t\tthis.mailNotificationStyle = mailNotificationStyle;\n\t}\n\n\tpublic String getMailNotificationService() {\n\t\treturn mailNotificationService;\n\t}\n\n\tpublic void setMailNotificationService(String mailNotificationService) {\n\t\tthis.mailNotificationService = mailNotificationService;\n\t}\n\n}" ]
import org.apache.http.client.HttpClient; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.TabActivity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.andrewshu.android.reddit.R; import com.andrewshu.android.reddit.captcha.CaptchaCheckRequiredTask; import com.andrewshu.android.reddit.captcha.CaptchaDownloadTask; import com.andrewshu.android.reddit.common.Common; import com.andrewshu.android.reddit.common.Constants; import com.andrewshu.android.reddit.common.FormValidation; import com.andrewshu.android.reddit.common.RedditIsFunHttpClientFactory; import com.andrewshu.android.reddit.settings.RedditSettings; import com.andrewshu.android.reddit.things.ThingInfo;
String whichInbox = whichInboxes[getTabHost().getCurrentTab()]; InboxListActivity inboxListActivity = (InboxListActivity) getLocalActivityManager().getActivity(whichInbox); if (inboxListActivity != null) inboxListActivity.refresh(); break; case android.R.id.home: Common.goHome(this); break; } return true; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; ProgressDialog pdialog; AlertDialog.Builder builder; LayoutInflater inflater; View layout; // used for inflated views for AlertDialog.Builder.setView() switch (id) { case Constants.DIALOG_COMPOSE: inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); builder = new AlertDialog.Builder(new ContextThemeWrapper(this, mSettings.getDialogTheme())); layout = inflater.inflate(R.layout.compose_dialog, null); dialog = builder.setView(layout).create(); final Dialog composeDialog = dialog; Common.setTextColorFromTheme( mSettings.getTheme(), getResources(), (TextView) layout.findViewById(R.id.compose_destination_textview), (TextView) layout.findViewById(R.id.compose_subject_textview), (TextView) layout.findViewById(R.id.compose_message_textview), (TextView) layout.findViewById(R.id.compose_captcha_textview), (TextView) layout.findViewById(R.id.compose_captcha_loading) ); final EditText composeDestination = (EditText) layout.findViewById(R.id.compose_destination_input); final EditText composeSubject = (EditText) layout.findViewById(R.id.compose_subject_input); final EditText composeText = (EditText) layout.findViewById(R.id.compose_text_input); final Button composeSendButton = (Button) layout.findViewById(R.id.compose_send_button); final Button composeCancelButton = (Button) layout.findViewById(R.id.compose_cancel_button); final EditText composeCaptcha = (EditText) layout.findViewById(R.id.compose_captcha_input); composeSendButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { ThingInfo thingInfo = new ThingInfo(); if (!FormValidation.validateComposeMessageInputFields(InboxActivity.this, composeDestination, composeSubject, composeText, composeCaptcha)) return; thingInfo.setDest(composeDestination.getText().toString().trim()); thingInfo.setSubject(composeSubject.getText().toString().trim()); new MyMessageComposeTask( composeDialog, thingInfo, composeCaptcha.getText().toString().trim(), mCaptchaIden, mSettings, mClient, InboxActivity.this ).execute(composeText.getText().toString().trim()); removeDialog(Constants.DIALOG_COMPOSE); } }); composeCancelButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { removeDialog(Constants.DIALOG_COMPOSE); } }); break; case Constants.DIALOG_COMPOSING: pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme())); pdialog.setMessage("Composing message..."); pdialog.setIndeterminate(true); pdialog.setCancelable(true); dialog = pdialog; break; default: throw new IllegalArgumentException("Unexpected dialog id "+id); } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case Constants.DIALOG_COMPOSE: new MyCaptchaCheckRequiredTask(dialog).execute(); break; } } private class MyMessageComposeTask extends MessageComposeTask { public MyMessageComposeTask(Dialog dialog, ThingInfo targetThingInfo, String captcha, String captchaIden, RedditSettings settings, HttpClient client, Context context) { super(dialog, targetThingInfo, captcha, captchaIden, settings, client, context); } @Override public void onPreExecute() { showDialog(Constants.DIALOG_COMPOSING); } @Override public void onPostExecute(Boolean success) { removeDialog(Constants.DIALOG_COMPOSING); if (success) { Toast.makeText(InboxActivity.this, "Message sent.", Toast.LENGTH_SHORT).show(); // TODO: add the reply beneath the original, OR redirect to sent messages page } else { Common.showErrorToast(_mUserError, Toast.LENGTH_LONG, InboxActivity.this); } } }
private class MyCaptchaCheckRequiredTask extends CaptchaCheckRequiredTask {
0
geoparser/geolocator
geo-locator/src/edu/cmu/geoparser/ui/geolocator/GUI/Desktop.java
[ "public class GetReader {\n\n public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException,\n UnsupportedEncodingException {\n File file = new File(filename);\n BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file),\n \"utf-8\"));\n return bin;\n }\n\n public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException {\n IndexWriter iw = GetWriter.getIndexWriter(filename, 1024);\n IndexReader ir = IndexReader.open(iw, false);\n IndexSearcher searcher = new IndexSearcher(ir);\n return searcher;\n }\n\n public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception {\n IndexReader reader;\n Directory d ;\n if (diskOrMem.equals(\"disk\"))\n d = FSDirectory.open(new File(filename));\n else if (diskOrMem.equals(\"mmap\"))\n d= MmapDirectory(new File(filename));\n else\n throw new Exception(\"parameter for directory type not defined.\");\n \n if(OSUtil.isWindows())\n reader = IndexReader.open(FSDirectory.open(new File(filename)));\n else\n reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); \n IndexSearcher searcher = new IndexSearcher(reader);\n return searcher;\n }\n\n private static Directory MmapDirectory(File file) {\n // TODO Auto-generated method stub\n return null;\n }\n\n public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in, \"utf-8\"));\n return br;\n }\n\n}", "public class GetWriter {\n\n public static IndexWriter getIndexWriter(String indexdirectory, double buffersize)\n throws IOException {\n Directory dir;\n if (OSUtil.isWindows())\n dir = FSDirectory.open(new File(indexdirectory));\n else\n dir = NIOFSDirectory.open(new File(indexdirectory));\n\n Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_45);\n IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_45, analyzer);\n\n config.setOpenMode(OpenMode.CREATE_OR_APPEND);\n config.setRAMBufferSizeMB(buffersize);\n LogDocMergePolicy mergePolicy = new LogDocMergePolicy();\n mergePolicy.setMergeFactor(3);\n config.setMergePolicy(mergePolicy);\n\n IndexWriter writer = new IndexWriter(dir, config);\n return writer;\n }\n\n public static BufferedWriter getFileWriter(String filename) throws IOException {\n\n FileOutputStream fos = new FileOutputStream(filename, false);// rewrite the file of the same\n // name\n OutputStreamWriter ofw = new OutputStreamWriter(fos, \"utf-8\");\n BufferedWriter bw = new BufferedWriter(ofw);\n\n return bw;\n }\n\n}", "public class Tweet {\n String id;\n\n Status status;\n\n Sentence sentence;\n\n List<LocEntity> geoLocations;\n\n public Tweet(){\n }\n public Tweet(String tweetStr){\n this.sentence = new Sentence(tweetStr);\n }\n public String getId() {\n return id;\n }\n\n public Tweet setId(String id) {\n this.id = id;\n return this;\n }\n\n public Status getStatus() {\n return status;\n }\n\n public Tweet setStatus(Status status) {\n this.status = status;\n return this;\n }\n\n public Sentence getSentence() {\n return sentence;\n }\n\n public Tweet setSentence(Sentence sentence) {\n this.sentence = sentence;\n return this;\n }\n\n public Tweet setSentence(String sent){\n if (sentence==null)\n sentence = new Sentence(sent);\n sentence.setSentenceString(sent);\n return this;\n }\n public List<LocEntity> getGeoLocations() {\n return geoLocations;\n }\n\n public Tweet setGeoLocations(List<LocEntity> geoLocations) {\n this.geoLocations = geoLocations;\n return this;\n }\n\n @Override\n public String toString() {\n\n return \"tweet id: \" + id + \", text : \" + sentence;\n }\n\n @Override\n public int hashCode() {\n return id.hashCode();\n }\n\n}", "public class FeatureGenerator {\n\n HashSet<String> preposition, countries;\n\n Dictionary prepdict, countrydict;\n\n EuroLangTwokenizer tokenizer;\n\n Lemmatizer lemmatizer;\n\n POSTagger postagger;\n\n Index index;\n\n public Index getIndex() {\n return index;\n }\n\n @SuppressWarnings(\"unchecked\")\n public FeatureGenerator(String language, Index index, String resourcepath) {\n // initialize dictionary to lookup.\n // \"geoNames.com/allCountries.txt\"\n this.index = index;\n\n if (language.equals(\"en\") || language.equals(\"es\"))\n tokenizer = new EuroLangTwokenizer();\n else\n System.err.println(\"No proper tokenizer found for this language.\");\n\n if (language.equals(\"en\"))\n // lemmatizer = new AnnaLemmatizer(resourcepath + language+\n // \"/CoNLL2009-ST-English-ALL.anna-3.3.lemmatizer.model\");\n lemmatizer = NLPFactory.getEnUWStemmer();\n else if (language.equals(\"es\"))\n lemmatizer = new AnnaLemmatizer(resourcepath + language\n + \"/CoNLL2009-ST-Spanish-ALL.anna-3.3.lemmatizer.model\");\n if (language.equals(\"en\"))\n postagger = NLPFactory.getEnPosTagger();\n else if (language.equals(\"es\"))\n postagger = new ESAnnaPOSTagger(resourcepath + language\n + \"/CoNLL2009-ST-Spanish-ALL.anna-3.3.postagger.model\");\n try {\n prepdict = Dictionary.getSetFromListFile(resourcepath + language + \"/prepositions.txt\", true,\n true);\n preposition = (HashSet<String>) prepdict.getDic(DicType.SET);\n } catch (IOException e) {\n\n e.printStackTrace();\n }\n }\n\n static int statstreet = 0;\n\n static int statbuilding = 0;\n\n static int stattoponym = 0;\n\n static int statabbr = 0, statadj = 0;\n\n String tweet;\n\n public static void main(String argv[]) throws IOException, InterruptedException {\n // argv[0] = \"es\";\n // argv[1] = \"GeoNames/allCountries.txt\";\n argv[2] = \"res/\";\n\n String featuretype = \"-3tok*.3pres.2cap.3caps.1pos.2pos.1gaz.1gazs.1cty.1ctys.-3-1prep\";\n // =\"ct-only\";\n // =\"allbutpos\";\n FeatureGenerator fgen = new FeatureGenerator(argv[0], ResourceFactory.getClbIndex(),\n argv[2]);\n String traintest[] = new String[] { \"train\", \"test\" };\n for (int tt = 0; tt < 2; tt++) {\n CsvReader entries = new CsvReader(\"trainingdata/\" + argv[0] + \"NER/\" + traintest[tt]\n + \"/raw.csv\", ',', Charset.forName(\"utf-8\"));\n\n BufferedWriter fwriter = GetWriter.getFileWriter(\"trainingdata/\" + argv[0] + \"NER/\"\n + traintest[tt] + \"/\" + featuretype + \"-features.txt\");\n\n entries.readHeaders();\n\n int i = 1;\n int counttweets = 0;\n while (entries.readRecord()) {\n i++;\n if (i % 200 == 0)\n System.out.println(i + \" \");\n\n String tag = entries.get(entries.getHeaders()[0]);\n\n if (tag.equals(\"\") == false)\n continue;// filter language\n else\n counttweets++; // count spanish tweets\n\n String tweet = entries.get(entries.getHeaders()[1]);// System.out.println(tweet);\n tweet = tweet.replace(\"-\", \" - \");\n String street = entries.get(entries.getHeaders()[2]);\n street = street.replace(\"-\", \" - \");\n String building = entries.get(entries.getHeaders()[3]);\n building = building.replace(\"-\", \" - \");\n String toponym = entries.get(entries.getHeaders()[4]);\n toponym = toponym.replace(\"-\", \" - \");\n String abbr = entries.get(entries.getHeaders()[5]);\n abbr = abbr.replace(\"-\", \" - \");\n // String locadj = entries.get(entries.getHeaders()[6]);\n // locadj = locadj.replace(\"-\", \" - \");\n\n String[] t_tweet = (EuroLangTwokenizer.tokenize(tweet)).toArray(new String[] {});\n String[] t_street = street.trim().split(\",\");// without\n // trimming\n String[] t_building = building.trim().split(\",\");// without\n // trimming\n String[] t_toponym = toponym.trim().split(\",\");// without\n // trimming\n String[] t_abbr = abbr.trim().split(\",\");// without\n // trimming\n // String[] t_locadj = locadj.trim().split(\",\");\n\n if (!EmptyArray(t_street))\n statstreet += t_street.length;\n if (!EmptyArray(t_building))\n statbuilding += t_building.length;\n if (!EmptyArray(t_toponym))\n stattoponym += t_toponym.length;\n if (!EmptyArray(t_abbr))\n statabbr += t_abbr.length;\n // if (!EmptyArray(t_locadj))\n // statadj += t_locadj.length;\n if (t_tweet.length == 0)\n continue;\n\n // labeling\n HashMap<Integer, String> f_loc = safeTag(t_tweet, t_street, t_building, t_toponym, t_abbr);\n\n Sentence sent = new Sentence(tweet);\n List<Feature[]> tweetfeatures = fgen.extractFeature(sent);\n\n for (int j = 0; j < tweetfeatures.size(); j++) {\n initialFeatureWriter();\n for (Feature f : tweetfeatures.get(j)) {\n append(f.toString());\n // System.out.println(f.toString());\n }\n\n // location class.\n String loctag = \"O\";\n if (f_loc.containsKey(j))\n loctag = f_loc.get(j);\n // loctag = \"LOC\";\n append(loctag);\n fwriter.write(emit());\n }\n\n fwriter.write(\"\\n\");\n }\n System.out.println(statstreet);\n System.out.println(statbuilding);\n System.out.println(stattoponym);\n System.out.println(statabbr);\n // System.out.println(statadj);\n System.out.println();\n System.out.println(counttweets);\n\n fwriter.close();\n entries.close();\n }\n }\n\n /**\n * MAIN FUNCTION FOR EXTRACTIN FEATURES\n * \n * @param t_tweet\n * @param trie\n * @param postags\n * @return FEATURE LISTS\n */\n public List<Feature[]> extractFeature(Sentence tweetSentence) {\n // String[] t_tweet; //original input.\n int len = tweetSentence.tokenLength();\n List<List<Feature>> instances = new ArrayList<List<Feature>>(len);\n List<Feature> f = new ArrayList<Feature>();\n\n // normalize tweet norm_tweet\n for (int i = 0; i < len; i++)\n tweetSentence.getTokens()[i].setNorm(StringUtil\n .getDeAccentLoweredString(tokentype(tweetSentence.getTokens()[i].getToken())));\n // lemmatize norm field. store in lemma field.// originally lemmat_tweet;\n // stored in lemma field\n lemmatizer.lemmatize(tweetSentence);\n\n // pos tagging, originally postags. input is t_tweet\n // stored in pos field\n postagger.tag(tweetSentence);\n\n // String[] f_pos = postags.toArray(new String[] {});\n\n // f_gaz originally. filled in inGaz Field in token. check norm_tweet field.\n // boolean[] f_gaz =\n gazTag(tweetSentence, this.index);\n\n // use norm_tweet field to tag countries. don't remove f_country, because it's not a type in\n // token.\n boolean[] f_country = countryTag(tweetSentence);\n\n for (int i = 0; i < len; i++) {\n // clear feature list for this loop\n f = new ArrayList<Feature>();\n // /////////////////////////////// MORPH FEATURES\n // use lemma_tweet to get token features.\n genTokenFeatures(f, tweetSentence, i);\n // ////////////////////////////// SEMANTIC FEATURES\n genPosFeatures(f, tweetSentence, i);\n // ////////////////////////////////// GAZ AND DICT LOOK UP\n genGazFeatures(f, tweetSentence, i);\n // f7: STREET SUFFIX\n // f8 PREPOSITION\n\n genCountryFeatures(f, f_country, i);// f10: DIRECTION\n // f10 directions\n\n // FEATURES are not stored in tweetsentence in advance. Those are generated in those features.\n // use t_tweet to get cap.\n genCapFeatures(f, tweetSentence, i);\n\n // use t_tweet to generate preposition tags.\n genPrepFeatures(f, tweetSentence, i, preposition);\n\n // f9: COUNTRY\n // f11: DISTANCE\n // f12: STOPWORDS\n // f13: BUILDING\n instances.add(f);\n }\n\n // convert array to output format.\n ArrayList<Feature[]> newinstances = new ArrayList<Feature[]>();\n for (int i1 = 0; i1 < instances.size(); i1++) {\n newinstances.add(instances.get(i1).toArray(new Feature[] {}));\n }\n return newinstances;\n }\n\n // //////////////////////////////////////////////////////////////////////////////////\n // FEATURE EXTRACTORS\n // //////////////////////////////////////////////\n /**\n * PREPOSITION OR NOT.\n * \n * INPUT RAW TOKENS OUTPUT BINARY VALUE YES OR NO.\n * \n * @param f\n * @param t_tweet\n * @param i\n */\n // prep-2.prep-1\n private static void genPrepFeatures(List<Feature> f, Sentence sent, int i,\n HashSet<String> preposition) {\n // String[] t_tweet;\n\n if (i - 3 >= 0)\n addFeature(f,\n \"-3_cont_prep_\" + preposition.contains(TOKLW(sent.getTokens()[i - 3].getToken())));\n if (i - 2 >= 0)\n addFeature(f,\n \"-2_cont_prep_\" + preposition.contains(TOKLW(sent.getTokens()[i - 2].getToken())));\n if (i - 1 >= 0)\n addFeature(f,\n \"-1_cont_prep_\" + preposition.contains(TOKLW(sent.getTokens()[i - 1].getToken())));\n }\n\n /**\n * COUNTRY GAZ EXISTENCE\n * \n * @param f\n * @param f_country\n * @param i\n */\n // country.-1.+1.seq-1+1\n private static void genCountryFeatures(List<Feature> f, boolean[] f_country, int i) {\n addFeature(f, \"0_cont_country_\" + f_country[i]);\n String countryseq = \"\";\n if (i - 1 >= 0) {\n addFeature(f, \"-1_cont_country_\" + f_country[i - 1]);\n countryseq += f_country[i - 1] + \"::\";\n }\n if (i + 1 <= f_country.length - 1) {\n addFeature(f, \"+1_cont_country_\" + f_country[i + 1]);\n countryseq += f_country[i + 1];\n }\n addFeature(f, \"-+_cont_country_seq_\" + countryseq);\n\n }\n\n /**\n * GAZ EXISTENCE\n * \n * @param f\n * @param f_gaz\n * @param i\n */\n // gaz.-1.+1.seq-1+1\n private static void genGazFeatures(List<Feature> f, Sentence sent, int i) {\n // boolean[] f_gaz;\n // CURRENT WORD\n addFeature(f, \"0_cont_gaz_\" + sent.getTokens()[i].isInLocationGazetteer());\n\n String gazseq = \"\";\n if (i - 1 >= 0) {\n addFeature(f, \"-1_cont_gaz_\" + sent.getTokens()[i - 1].isInLocationGazetteer());\n gazseq += sent.getTokens()[i - 1].isInLocationGazetteer() + \"::\";\n }\n if (i + 1 <= sent.tokenLength() - 1) {\n addFeature(f, \"+1_cont_gaz_\" + sent.getTokens()[i + 1].isInLocationGazetteer());\n gazseq += sent.getTokens()[i + 1].isInLocationGazetteer();\n }\n addFeature(f, \"-+_cont_gaz_seq_\" + gazseq);\n }\n\n /**\n * POINT POS FOR EACH SURROUNDING WORD POS SEQUENCE\n * \n * @param f\n * @param f_pos\n * @param i\n */\n // pos.seq-3-1.seq+1+3\n private static void genPosFeatures(List<Feature> f, Sentence twSent, int i) {\n // String[] f_pos;\n int t_length = twSent.tokenLength();\n // f5 PART OF SPEECH\n\n // CURRENT WORD\n addFeature(f, \"0_pos_\" + twSent.getTokens()[i].getPOS());\n\n String posleft = \"\", posright = \"\";\n if (i - 4 >= 0) {\n // addFeature(f, \"-4.pos.\" + f_pos[i - 4]);\n // posleft += f_pos[i - 4];\n }\n if (i - 3 >= 0) {\n // addFeature(f, \"-3.pos.\" + f_pos[i - 3]);\n // posleft += f_pos[i - 3];\n }\n if (i - 2 >= 0) {\n // addFeature(f, \"-2_pos_\" + f_pos[i - 2]);\n posleft += twSent.getTokens()[i - 2].getPOS();\n }\n if (i - 1 >= 0) {\n addFeature(f, \"-1_pos_\" + twSent.getTokens()[i - 1].getPOS());\n posleft += twSent.getTokens()[i - 1].getPOS();\n }\n if (i + 1 <= t_length - 1) {\n addFeature(f, \"+1_pos_\" + twSent.getTokens()[i + 1].getPOS());\n posright += twSent.getTokens()[i + 1].getPOS();\n }\n if (i + 2 <= t_length - 1) {\n // addFeature(f, \"+2_pos_\" + f_pos[i + 2]);\n posright += twSent.getTokens()[i + 2].getPOS();\n }\n if (i + 3 <= t_length - 1) {\n // addFeature(f, \"+3.pos.\" + f_pos[i + 3]);\n // posright += f_pos[i + 3];\n }\n if (i + 4 <= t_length - 1) {\n // addFeature(f, \"+4.pos.\" + f_pos[i + 4]);\n // posright += f_pos[i + 4];\n }\n addFeature(f, \"-pos_seq_\" + posleft);\n addFeature(f, \"+pos_seq_\" + posright);\n\n }\n\n /**\n * CAPITALIZATION SEQUENCE POINT CAPs OF SURROUNDING WORDS CAP SEQUENCEs\n * \n * @param f\n * @param t_tweet\n * @param i\n */\n // cap.seq-3-1.seq+1+3\n private static void genCapFeatures(List<Feature> f, Sentence sent, int i) {\n // String[] t_tweet;\n int t_length = sent.tokenLength();\n\n // CURRENT WORD\n addFeature(f, \"0_mph_cap_\" + MPHCAP(sent.getTokens()[i].getToken()));\n\n String left = \"\", right = \"\";\n if (i - 4 >= 0) {\n // addFeature(f, \"-4_mph_cap_\" + MPHCAP(t_tweet[i - 4]));\n // left += MPHCAP(t_tweet[i - 4]);\n }\n if (i - 3 >= 0) {\n addFeature(f, \"-3_mph_cap_\" + MPHCAP(sent.getTokens()[i - 3].getToken()));\n // left += MPHCAP(t_tweet[i - 3]);\n }\n if (i - 2 >= 0) {\n addFeature(f, \"-2_mph_cap_\" + MPHCAP(sent.getTokens()[i - 2].getToken()));\n left += MPHCAP(sent.getTokens()[i - 2].getToken());\n }\n if (i - 1 >= 0) {\n addFeature(f, \"-1_mph_cap_\" + MPHCAP(sent.getTokens()[i - 1].getToken()));\n left += MPHCAP(sent.getTokens()[i - 1].getToken()) + \"::\";\n }\n if (i + 1 <= t_length - 1) {\n addFeature(f, \"+1_mph_cap_\" + MPHCAP(sent.getTokens()[i + 1].getToken()));\n right += MPHCAP(sent.getTokens()[i + 1].getToken());\n }\n if (i + 2 <= t_length - 1) {\n addFeature(f, \"+2_mph_cap_\" + MPHCAP(sent.getTokens()[i + 2].getToken()));\n right += MPHCAP(sent.getTokens()[i + 2].getToken());\n }\n if (i + 3 <= t_length - 1) {\n addFeature(f, \"+3_mph_cap_\" + MPHCAP(sent.getTokens()[i + 3].getToken()));\n // right += MPHCAP(t_tweet[i + 3]);\n }\n if (i + 4 <= t_length - 1) {\n // addFeature(f, \"+4_mph_cap_\" + MPHCAP(t_tweet[i + 4]));\n // right += MPHCAP(t_tweet[i + 4]);\n }\n addFeature(f, \"-_mph_cap_seq_\" + left);\n addFeature(f, \"+_mph_cap_seq_\" + right);\n addFeature(f, \"-+_mph_cap_seq_\" + left + right);\n\n }\n\n /**\n * CONTEXT WORD (LEMMA) EXISTENCE The bag of words feature, and position appearance feature\n * together. 1. Each lemma is added in bag of context words 2. Each position has an presence\n * feature for determining the existence of the window position.\n * \n * @param f\n * : Feature list\n * @param lemmat_tweet\n * : lemmas of the tweet,\n * @param i\n * : position of the current word\n */\n // tok.-1.+1.pres-4+4.\n private static void genTokenFeatures(List<Feature> f, Sentence sent, int i) {\n // String[] lemmat_tweet;\n // CURRENT TOKEN\n addFeature(f, \"0_tok_lw_\" + TOKLW(sent.getTokens()[i].getLemma()));\n if (i - 4 >= 0) {\n // addFeature(f, \"-_tok_lw_\" + TOKLW(lemmat_tweet[i - 4]));\n addFeature(f, \"-4_tok_present_1\");\n } else {\n addFeature(f, \"-4_tok_present_0\");\n }\n if (i - 3 >= 0) {\n addFeature(f, \"-_tok_lw_\" + TOKLW(sent.getTokens()[i - 3].getLemma()));\n addFeature(f, \"-3_tok_present_1\");\n } else {\n addFeature(f, \"-3_tok_present_0\");\n }\n // this feature has changed into bag of window words feature,\n // which is less specific than just the position.\n if (i - 2 >= 0) {\n addFeature(f, \"-2_tok_lw_\" + TOKLW(sent.getTokens()[i - 2].getLemma()));\n addFeature(f, \"-2_tok_present_1\");\n } else {\n addFeature(f, \"-2_tok_present_0\");\n }\n if (i - 1 >= 0) {\n addFeature(f, \"-1_tok_lw_\" + TOKLW(sent.getTokens()[i - 1].getLemma()));\n addFeature(f, \"-1_tok_present_1\");\n } else {\n addFeature(f, \"-1_tok_present_0\");\n }\n if (i + 1 <= sent.tokenLength() - 1) {\n addFeature(f, \"+1_tok_lw_\" + TOKLW(sent.getTokens()[i + 1].getLemma()));\n addFeature(f, \"+1_tok_present_1\");\n } else {\n addFeature(f, \"+1_tok_present_0\");\n }\n if (i + 2 <= sent.tokenLength() - 1) {\n addFeature(f, \"+2_tok_lw_\" + TOKLW(sent.getTokens()[i + 2].getLemma()));\n addFeature(f, \"+2_tok_present_1\");\n } else {\n addFeature(f, \"+2_tok_present_0\");\n }\n if (i + 3 <= sent.tokenLength() - 1) {\n addFeature(f, \"+_tok_lw_\" + TOKLW(sent.getTokens()[i + 3].getLemma()));\n addFeature(f, \"+3_tok_present_1\");\n } else {\n addFeature(f, \"+3_tok_present_0\");\n }\n if (i + 4 <= sent.tokenLength() - 1) {\n // addFeature(f, \"+_tok_lw_\" + TOKLW(sent.getTokens()[i+4].getLemma()));\n addFeature(f, \"+4_tok_present_1\");\n } else {\n addFeature(f, \"+4_tok_present_0\");\n }\n }\n\n /**\n * CAPITALIZATION\n * \n * @param string\n * @return boolean\n */\n private static String MPHCAP(String string) {\n\n boolean a = Character.isUpperCase(string.charAt(0));\n return Boolean.toString(a);\n }\n\n /**\n * CONVERT TO LOWER TYPE Input the lemma, 1. Run tokentype() to convert to token 2. lowercase and\n * deaccent the lemma.\n * \n * @param lemmastring\n * @return\n */\n private static String TOKLW(String lemmastring) {\n\n lemmastring = StringUtil.getDeAccentLoweredString(tokentype(lemmastring));\n return lemmastring;\n }\n\n /**\n * CONVERT TO TYPE Naively decide the tweet token type, url, or hashtag, or metion, or number. Or\n * it's not any of them, just return it's original string.\n * \n * @param token\n * @return\n */\n public static String tokentype(String token) {\n // lower cased word.\n String ltoken = StringUtil.getDeAccentLoweredString(token.trim());\n\n if (ltoken.startsWith(\"http:\") || ltoken.startsWith(\"www:\")) {\n ltoken = \"[http]\";\n } else if (ltoken.startsWith(\"@\") || ltoken.startsWith(\"#\")) {\n if (ltoken.length() > 1) {\n ltoken = ltoken.substring(1);\n }\n }\n try {\n Double.parseDouble(ltoken);\n ltoken = \"[num]\";\n } catch (NumberFormatException e) {\n }\n\n return ltoken;\n }\n\n // ////////////////////////////////////////////////////////////////////////////////////\n // GAZ FEATURE HELPER\n // //////////////////////////////////////////////////////////\n /**\n * GAZ TAGGING BASED ON GREEDY SEARCH. FIND THE LONGEST MATCH STARTING FROM THE CURRENT WORD\n * \n * @param t_tweet\n * @param trie\n * @return\n */\n private static Sentence gazTag(Sentence twSent, Index index) {\n int len = twSent.tokenLength();\n boolean[] gaztag = new boolean[twSent.tokenLength()];\n int i = 0;\n while (i < len) {\n String history = \"\";\n for (int j = i; j < len; j++) {\n history += twSent.getTokens()[j].getNorm();\n if (index.inIndex(history)) {\n for (int k = i; k < j + 1; k++)\n gaztag[k] = true;\n // gaztag[j]=true;\n }\n }\n i++;\n }\n\n for (i = 0; i < gaztag.length; i++) {\n twSent.getTokens()[i].setInLocationGazetteer(gaztag[i]);\n }\n return twSent;\n }\n\n /**\n * COUNTRY TAGGING BASED ON GREEDY SEARCH FIND THE LONGEST MATCH STARTING FROM THE CURRENT WORD\n * \n * @param t_tweet\n * @return\n */\n private static boolean[] countryTag(Sentence sent) {\n // String[] t_tweet;\n boolean[] countrytag = new boolean[sent.tokenLength()];\n int i = 0;\n while (i < sent.tokenLength()) {\n String history = \"\";\n for (int j = i; j < sent.tokenLength(); j++) {\n history += \" \" + StringUtil.getDeAccentLoweredString(sent.getTokens()[j].getNorm());\n // System.out.println(history);\n // System.out.println(ParserUtils.isCountry(history.trim()));\n if (ParserUtils.isCountry(history.trim())) {\n for (int k = i; k < j + 1; k++)\n countrytag[k] = true;\n }\n }\n i++;\n }\n return countrytag;\n }\n\n /**\n * HELPER FOR SAFELY TAGGING THE STRINGS\n * \n * @param t_tweet\n * @param t_street\n * @param t_building\n * @param t_toponym\n * @param t_abbr\n * @param tk\n * @return\n */\n private static HashMap<Integer, String> safeTag(String[] t_tweet, String[] t_street,\n String[] t_building, String[] t_toponym, String[] t_abbr) {\n HashMap<Integer, String> tagresults = new HashMap<Integer, String>();\n if (!EmptyArray(t_toponym)) {\n fillinTag(t_tweet, t_toponym, tagresults, \"TP\");\n }\n if (!EmptyArray(t_street)) {\n fillinTag(t_tweet, t_street, tagresults, \"ST\");\n }\n if (!EmptyArray(t_building)) {\n fillinTag(t_tweet, t_building, tagresults, \"BD\");\n }\n if (!EmptyArray(t_abbr)) {\n fillinTag(t_tweet, t_abbr, tagresults, \"AB\");\n }\n return tagresults;\n }\n\n /**\n * AUXILARY FUNCTION FOR SAFETAG. FILL THE TAG IN t_location INTO THE tagresults hashmap.\n * \n * @param t_tweet\n * @param t_street\n * @param tagresults\n * @param tk\n */\n private static void fillinTag(String[] t_tweet, String[] t_location,\n HashMap<Integer, String> tagresults, String TAG) {\n\n for (String location : t_location) {\n\n List<String> loctokens = EuroLangTwokenizer.tokenize(location);\n // if (TAG.equals(\"AB\")) {\n // System.out.println(\"the original tweet tokenized is : \" +\n // Arrays.asList(t_tweet).toString());\n // System.out.println(\"the location tokenized is :\" +\n // loctokens.toString());\n // }\n for (String token : loctokens) {\n boolean have = false;\n String ntoken = StringUtil.getDeAccentLoweredString(token);\n for (int i = 0; i < t_tweet.length; i++) {\n if (StringUtil.getDeAccentLoweredString(\n (t_tweet[i].startsWith(\"#\") && t_tweet[i].length() > 1) ? t_tweet[i].substring(1)\n : t_tweet[i]).equals(ntoken)) {\n tagresults.put(i, TAG);\n have = true;\n }\n }\n if (have == false)\n System.out.println(\"Don't have the tag: \" + token);\n }\n }\n // if(TAG.equals(\"AB\"))\n // System.out.println(tagresults);\n }\n\n // ///////////////////////////////////////////////////////////////////////////////////////////////////////\n // TOOLS\n // //////////////////////////////////\n /**\n * JUDGE EMPTY OF AN ARRAY.\n * \n * @param array\n * @return\n */\n static boolean EmptyArray(String[] array) {\n if (array.length < 2)\n if (array[0].equals(\"\"))\n return true;\n return false;\n }\n\n // ////////////////////////////////////////////////////////////////////////////////\n // HELPER FOR FEATURE VECTOR\n // /////////////////////////////////////////\n static StringBuilder sb = new StringBuilder();\n\n /**\n * helper for building feature vector. sb stores the features on a line, and this func is used to\n * initialize the sb, aka, clear the builder.\n */\n private static void initialFeatureWriter() {\n sb = new StringBuilder();\n }\n\n private static void append(String featurestring) {\n\n if (sb.length() > 0)\n sb.append(\"\\t\");\n sb.append(featurestring);\n }\n\n static String emit() {\n return sb.append(\"\\n\").toString();\n }\n\n private static void addFeature(List<Feature> features, String string) {\n\n features.add(new Feature(string));\n }\n\n // ////////////////////////////////////////////////////////////////////////////////////\n // GETTER AND SETTERS /////\n\n public HashSet<String> getPreposition() {\n return preposition;\n }\n\n public void setPreposition(HashSet<String> preposition) {\n this.preposition = preposition;\n }\n\n public HashSet<String> getCountries() {\n return countries;\n }\n\n public void setCountries(HashSet<String> countries) {\n this.countries = countries;\n }\n\n public EuroLangTwokenizer getTokenizer() {\n return tokenizer;\n }\n\n public void setTokenizer(EuroLangTwokenizer tokenizer) {\n this.tokenizer = tokenizer;\n }\n\n public Lemmatizer getLemmatizer() {\n return lemmatizer;\n }\n\n public void setLemmatizer(Lemmatizer lemmatizer) {\n this.lemmatizer = lemmatizer;\n }\n\n public POSTagger getPostagger() {\n return postagger;\n }\n\n public void setPostagger(POSTagger postagger) {\n this.postagger = postagger;\n }\n\n}", "public class EnglishParser {\n\n private NERTagger ner;\n private STBDParser stbd;\n private TPParser tp;\n\t\n\tHashSet<LocEntity> match;\n\tpublic EnglishParser(String root, Index index, boolean misspell){\n\t\tner = ParserFactory.getEnNERParser();\n\t\tstbd = ParserFactory.getEnSTBDParser();\n\t\ttp = ParserFactory.getEnToponymParser();\n\t}\n\tpublic List<LocEntity> parse(Tweet t){\n\t\tmatch = new HashSet<LocEntity>();\n\t\tList<LocEntity> nerresult = ner.parse(t);\n\t\tList<LocEntity> stbdresult = stbd.parse(t);\n\t\tList<LocEntity> toporesult = tp.parse(t);\n\t\tmatch.addAll(nerresult);\n\t\tmatch.addAll(stbdresult);\n\t\tmatch.addAll(toporesult);\n\t\treturn new ArrayList<LocEntity>(match);\t\n\t\t\n\t}\n}", "public interface Index {\n \n /**\n * search in the resource for existance.\n * @param phrase\n * @return boolean value\n */\n public boolean inIndex(String phrase);\n// public boolean inIndexStrict(String phrase);\n \n /**\n * search index, return the documents fetched.\n * @param phrase to search\n * @return list of docuements containing detail info.\n */\n public ArrayList<Document> getDocumentsByPhrase(String phrase);\n// public ArrayList<Document> getDocumentsByPhraseStrict(String phrase);\n \n /**\n * search index by id.\n */\n public Document getDocumentsById(String id);\n \n /**\n * open index\n */\n public Index open();\n /**\n * close index\n */\n public void close();\n}", "public class CollaborativeIndex implements Index {\n\n private IndexSearcher stringSearcher, infoSearcher;\n\n private HashSet<String> ids;\n\n private BooleanQuery q;\n\n private ArrayList<Document> returnDocs;\n\n private String stringIndexName, infoIndexName, stringLoad, infoLoad;\n\n private static CollaborativeIndex ci;\n\n public static CollaborativeIndex getInstance() {\n if (ci == null)\n ci = new CollaborativeIndex().config(\"GazIndex/StringIndex\", \"GazIndex/InfoIndex\", \"mmap\",\n \"mmap\").open();\n return ci;\n\n }\n\n public CollaborativeIndex config(String stringIndexName, String infoIndexName, String stringLoad,\n String infoLoad) {\n this.stringIndexName = stringIndexName;\n this.infoIndexName = infoIndexName;\n this.stringLoad = stringLoad;\n this.infoLoad = infoLoad;\n return this;\n }\n/*\n public boolean inIndexStrict(String phrase) {\n if (phrase == null || phrase.length() == 0)\n throw new NullPointerException();\n TermQuery query = new TermQuery(new Term(\"LOWERED_ORIGIN\", phrase.toLowerCase()));\n //If it's an abbreviation, then return true; ignore case.\n \n if (ResourceFactory.getCountryCode2CountryMap().isCountryAbbreviation(phrase))\n return true;\n TopDocs res = null;\n try {\n res = stringSearcher.search(query, 1);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n if (res == null)\n return false;\n else\n return res.totalHits > 0 ? true : false;\n }\n*/\n /**\n * Check if the original string is in index. If not, check the non-space version. However, we have\n * to add some heuristics.\n */\n @Override\n public boolean inIndex(String phrase) {\n if (phrase == null || phrase.length() == 0)\n throw new NullPointerException();\n if (phrase.startsWith(\"#\"))\n phrase = phrase.substring(1);\n if (ResourceFactory.getCountryCode2CountryMap().isInMap(phrase.trim().toLowerCase()))\n return true;\n phrase = phrase.toLowerCase().replace(\" \", \"\");\n TermQuery query = new TermQuery(new Term(\"LOWERED-NO-WS\", phrase));\n TopDocs res = null;\n try {\n res = stringSearcher.search(query, 1);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n if (res == null)\n return false;\n return res.totalHits > 0 ? true : false;\n }\n\n @Override\n public ArrayList<Document> getDocumentsByPhrase(String phrase) {\n if (phrase == null || phrase.length() == 0)\n throw new NullPointerException();\n if (phrase.startsWith(\"#\"))\n phrase = phrase.substring(1);\n TermQuery query = new TermQuery(\n new Term(\"LOWERED-NO-WS\", phrase.toLowerCase().replace(\" \", \"\")));\n TopDocs res = null;\n try {\n res = stringSearcher.search(query, 2500);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n String abIds =null;\n if (ResourceFactory.getCountryCode2CountryMap().isInMap(phrase.toLowerCase()))\n abIds = ResourceFactory.getCountryCode2CountryMap().getValue(phrase.toLowerCase()).getId();\n\n// System.out.println(res.totalHits);\n if (res == null && abIds==null)\n return null;\n if (res.totalHits == 0 && abIds==null)\n return null;\n ids = new HashSet<String>();\n if (res!=null)\n try {\n for (ScoreDoc doc : res.scoreDocs) {\n ids.add(stringSearcher.doc(doc.doc).get(\"ID\"));\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n if (abIds !=null)\n ids.add(abIds);\n// System.out.println(ids);\n // System.out.println(\"total number of String ids are:\" + ids.size());\n q = new BooleanQuery();\n\n for (String id : ids) {\n q.add(new TermQuery(new Term(\"ID\", id)), Occur.SHOULD);\n }\n // use a term filter instead of a query filter.\n try {\n TopDocs docs = infoSearcher.search(q, 2500);\n // System.out.println(\"total hits in info is:\" + docs.totalHits);\n returnDocs = new ArrayList<Document>(docs.totalHits);\n for (ScoreDoc d : docs.scoreDocs) {\n returnDocs.add(infoSearcher.doc(d.doc));\n }\n return returnDocs;\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n }\n/*\n public ArrayList<Document> getDocumentsByPhraseStrict(String phrase) {\n if (phrase == null || phrase.length() == 0)\n throw new NullPointerException();\n TermQuery query = new TermQuery(new Term(\"LOWERED_ORIGIN\", phrase.toLowerCase()));\n TopDocs res = null;\n try {\n res = stringSearcher.search(query, 200);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n System.out.println(res.totalHits);\n\n if (res == null)\n return null;\n if (res.totalHits == 0)\n return null;\n ids = new HashSet<String>(res.totalHits);\n try {\n for (ScoreDoc doc : res.scoreDocs) {\n ids.add(stringSearcher.doc(doc.doc).get(\"ID\"));\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n if (ResourceFactory.getCountryCode2CountryMap().isCountryAbbreviation(phrase))\n ids.add(ResourceFactory.getCountryCode2CountryMap().getValue(phrase).getId());\n // System.out.println(\"total number of String ids are:\" + ids.size());\n q = new BooleanQuery();\n\n for (String id : ids) {\n q.add(new TermQuery(new Term(\"ID\", id)), Occur.SHOULD);\n }\n // use a term filter instead of a query filter.\n try {\n TopDocs docs = infoSearcher.search(q, 200);\n // System.out.println(\"total hits in info is:\" + docs.totalHits);\n returnDocs = new ArrayList<Document>(docs.totalHits);\n for (ScoreDoc d : docs.scoreDocs) {\n returnDocs.add(infoSearcher.doc(d.doc));\n }\n return returnDocs;\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n }\n*/\n public CollaborativeIndex open() {\n try {\n stringSearcher = GetReader.getIndexSearcher(stringIndexName, stringLoad);\n // for setting the max clause count for search query.\n BooleanQuery.setMaxClauseCount(2500);\n\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n try {\n infoSearcher = GetReader.getIndexSearcher(infoIndexName, infoLoad);\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return this;\n }\n\n @Override\n public void close() {\n // TODO Auto-generated method stub\n\n }\n\n public String[] getAlternateNames(String id) {\n HashSet<String> names = null;\n Query query = new TermQuery(new Term(\"ID\", id));\n try {\n TopDocs topDocs = infoSearcher.search(query, 2500);\n names = new HashSet<String>(topDocs.totalHits);\n for (ScoreDoc doc : topDocs.scoreDocs) {\n names.add(stringSearcher.doc(doc.doc).get(\"LOWERED_ORIGIN\"));\n }\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return names.toArray(new String[names.size()]);\n }\n\n @Override\n public Document getDocumentsById(String id) {\n if (id == null || id.length() == 0)\n throw new NullPointerException();\n TermQuery query = new TermQuery(new Term(\"ID\", id));\n TopDocs res = null;\n try {\n res = infoSearcher.search(query, 1);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n if (res == null)\n return null;\n if (res.totalHits == 0)\n return null;\n try {\n return infoSearcher.doc(res.scoreDocs[0].doc);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n\n }\n\n public static void main(String argv[]) throws IOException {\n CollaborativeIndex ci = ResourceFactory.getClbIndex();\n\n boolean mode = true; // string\n// mode = false; // id\n /**\n * search string //id\n */\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n String s = null;\n while ((s = br.readLine()) != null) {\n if (mode) {\n if( ResourceFactory.getClbIndex().inIndex(s))\n for ( Document d: ResourceFactory.getClbIndex().getDocumentsByPhrase(s) )\n System.out.println(d);\n else\n System.out.println(\"null.\");\n } else {\n Document doc = ci.getDocumentsById(s);\n System.out.println(doc);\n CandidateAndFeature gc = new CandidateAndFeature(s , doc, new LocEntity(0, 0, s, null));\n System.out.println(gc.getId() + \" \"+gc.getAsciiName() +\" \" +gc.getCountryCode());\n }\n }\n }\n}" ]
import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.border.Border; import edu.cmu.geoparser.Disambiguation.ContextDisamb; import edu.cmu.geoparser.io.GetReader; import edu.cmu.geoparser.io.GetWriter; import edu.cmu.geoparser.model.Tweet; import edu.cmu.geoparser.nlp.languagedetector.LangDetector; import edu.cmu.geoparser.nlp.ner.FeatureExtractor.FeatureGenerator; import edu.cmu.geoparser.parser.english.EnglishParser; import edu.cmu.geoparser.resource.gazindexing.Index; import edu.cmu.geoparser.resource.gazindexing.CollaborativeIndex.CollaborativeIndex; import edu.cmu.geoparser.resource.trie.IndexSupportedTrie;
JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); JMenuItem mntmNew = new JMenuItem("New"); mnFile.add(mntmNew); JMenuItem mntmOpen = new JMenuItem("Open"); mnFile.add(mntmOpen); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); mnFile.add(mntmExit); JMenu mnHelp = new JMenu("Help"); menuBar.add(mnHelp); JMenuItem mntmAbout = new JMenuItem("About"); mnHelp.add(mntmAbout); mntmAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { About window = new About(); window.frame.setVisible(true); } }); frame.getContentPane().setLayout(null); /** * Message Box text area. */ final JTextArea txtrMessageBox = new JTextArea(); txtrMessageBox .setText("Welcome to Geo-parser! It's developed by the Language Technology Institute in CMU."); txtrMessageBox.setEditable(false); txtrMessageBox.setLineWrap(true); txtrMessageBox.setBounds(10, 11, 288, 178); frame.getContentPane().add(txtrMessageBox); /** * Output box text area */ final JTextArea txtrOutputBox = new JTextArea(); txtrOutputBox.setText("Run the algorithm, and part of the results will be shown here."); txtrOutputBox.setBounds(10, 217, 288, 178); txtrOutputBox.setBorder(blackline); txtrOutputBox.setLineWrap(true); JScrollPane oscrollPane = new JScrollPane(txtrOutputBox); oscrollPane.setVisible(true); frame.getContentPane().add(txtrOutputBox); /** * input path, read in inbox content as file name */ txtCusers = new JTextField(); txtCusers.setText("Input file"); txtCusers.setToolTipText("Input path"); txtCusers.setBounds(338, 11, 180, 20); frame.getContentPane().add(txtCusers); txtCusers.setColumns(10); /** * output path, read in output box content as file name */ txtCusersoutput = new JTextField(); txtCusersoutput.setText("output file"); txtCusersoutput.setToolTipText("Output path"); txtCusersoutput.setBounds(338, 59, 180, 20); frame.getContentPane().add(txtCusersoutput); txtCusersoutput.setColumns(10); /** * Input file button clicked */ JButton btnNewButton = new JButton("Input File"); btnNewButton.setToolTipText("Select file of toponyms to tag."); btnNewButton.setBounds(528, 10, 33, 23); frame.getContentPane().add(btnNewButton); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // to do: fill out the input text area with selected file path. } }); /** * output file button clicked, output file is ready */ JButton btnNewButton_1 = new JButton("Ouput File"); btnNewButton_1.setToolTipText("Select file to store results."); btnNewButton_1.setBounds(528, 58, 33, 23); frame.getContentPane().add(btnNewButton_1); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // to do: fill out the output text area with selected file path. } }); JButton btnRun = new JButton("Run"); btnRun.setToolTipText("Run geolocator algorithm on above chosen files."); btnRun.setBounds(338, 218, 89, 23); frame.getContentPane().add(btnRun); btnRun.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { br = GetReader.getUTF8FileReader(txtCusers.getText().trim()); bw = GetWriter.getFileWriter(txtCusersoutput.getText().trim()); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } sb = new StringBuilder();
Tweet t;
2
ISibboI/JBitmessage
src/main/java/sibbo/bitmessage/network/NetworkManager.java
[ "public class Options extends Properties {\n\tprivate static final Logger LOG = Logger.getLogger(Options.class.getName());\n\n\tprivate static final Options defaults = new Options(null);\n\n\tstatic {\n\t\tdefaults.setProperty(\"global.version\", \"0.0.0\");\n\t\tdefaults.setProperty(\"global.name\", \"JBitmessage\");\n\n\t\tdefaults.setProperty(\"protocol.maxMessageLength\", 10 * 1024 * 1024);\n\t\tdefaults.setProperty(\"protocol.maxInvLength\", 50_000);\n\t\tdefaults.setProperty(\"protocol.maxAddrLength\", 1_000);\n\t\tdefaults.setProperty(\"protocol.services\", 1);\n\t\tdefaults.setProperty(\"protocol.remoteServices\", 1);\n\t\tdefaults.setProperty(\"protocol.version\", 1); // TODO Change to 2 after\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// implementation.\n\t\tdefaults.setProperty(\"pow.averageNonceTrialsPerByte\", 320);\n\t\tdefaults.setProperty(\"pow.payloadLengthExtraBytes\", 14_000);\n\t\tdefaults.setProperty(\"pow.systemLoad\", 0.5f);\n\t\tdefaults.setProperty(\"pow.iterationfactor\", 100);\n\t\tdefaults.setProperty(\"network.connectTimeout\", 5_000);\n\t\tdefaults.setProperty(\"network.timeout\", 10_000);\n\t\tdefaults.setProperty(\"network.listenPort\", 8443);\n\t\tdefaults.setProperty(\"network.passiveMode.maxConnections\", 8);\n\t\tdefaults.setProperty(\"network.activeMode.maxConnections\", 16);\n\t\tdefaults.setProperty(\"network.activeMode.stopListenConnectionCount\", 32);\n\t\tdefaults.setProperty(\"network.userAgent\",\n\t\t\t\t\"/\" + defaults.getString(\"global.name\") + \":\" + defaults.getString(\"global.version\") + \"/\");\n\t\tdefaults.setProperty(\"data.maxNodeStorageTime\", 3600 * 3); // Seconds\n\t}\n\n\tprivate static final Options instance = new Options(defaults);\n\n\tpublic static Options getInstance() {\n\t\treturn instance;\n\t}\n\n\tprivate Options(Properties defaults) {\n\t\tsuper(defaults);\n\t}\n\n\tpublic float getFloat(String key) {\n\t\ttry {\n\t\t\treturn Float.valueOf(getProperty(key));\n\t\t} catch (NumberFormatException e) {\n\t\t\tLOG.log(Level.SEVERE, \"Not a float: \" + getProperty(key), e);\n\t\t\tSystem.exit(1);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tpublic int getInt(String key) {\n\t\ttry {\n\t\t\treturn Integer.valueOf(getProperty(key));\n\t\t} catch (NumberFormatException e) {\n\t\t\tLOG.log(Level.SEVERE, \"Not an integer: \" + getProperty(key), e);\n\t\t\tSystem.exit(1);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tpublic long getLong(String key) {\n\t\ttry {\n\t\t\treturn Long.valueOf(getProperty(key));\n\t\t} catch (NumberFormatException e) {\n\t\t\tLOG.log(Level.SEVERE, \"Not a long: \" + getProperty(key), e);\n\t\t\tSystem.exit(1);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getProperty(String key) {\n\t\tString result = super.getProperty(key);\n\n\t\tif (result == null) {\n\t\t\tthrow new NullPointerException(\"Property not found: \" + key);\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tpublic String getString(String key) {\n\t\treturn getProperty(key);\n\t}\n\n\tpublic Object setProperty(String key, float value) {\n\t\treturn setProperty(key, String.valueOf(value));\n\t}\n\n\tpublic Object setProperty(String key, int value) {\n\t\treturn setProperty(key, String.valueOf(value));\n\t}\n\n\tpublic Object setProperty(String key, long value) {\n\t\treturn setProperty(key, String.valueOf(value));\n\t}\n}", "public class Datastore {\n\tprivate static final Logger LOG = Logger.getLogger(Datastore.class.getName());\n\t/** The database. */\n\tprivate final Database database;\n\n\t/** Stores the hashes of all objects that we have. */\n\tprivate final Set<InventoryVectorMessage> localObjects = Collections\n\t\t\t.synchronizedSet(new HashSet<InventoryVectorMessage>());\n\n\t/** Caches objects to reduce disc activity. */\n\tprivate final Map<InventoryVectorMessage, POWMessage> objectCache = new Hashtable<>();\n\n\t/** Stores all nodes that we know. */\n\tprivate final Map<Long, Map<NetworkAddressMessage, NetworkAddressMessage>> knownNodes = new Hashtable<>();\n\n\t/** Stores all addresses we own. */\n\tprivate final Set<BMAddress> ownedAddresses = Collections.synchronizedSet(new HashSet<BMAddress>());\n\n\t/** If true, the datastore stops as fast as possible. */\n\tprivate volatile boolean stop;\n\n\t/**\n\t * Creates a new datastore with the given name.\n\t * \n\t * @param datastorePath\n\t * The path to the file containing the datastore.\n\t */\n\tpublic Datastore(String datastoreName) {\n\t\tdatabase = new Database(datastoreName);\n\t}\n\n\t/**\n\t * Returns a list containing all nodes from the given list that are not\n\t * present in the datastore.\n\t * \n\t * @param list\n\t * The list of nodes to filter.\n\t * @return A list containing only nodes that are not present in the\n\t * datastore.\n\t */\n\tpublic List<NetworkAddressMessage> filterNodesThatWeAlreadyHave(List<NetworkAddressMessage> list) {\n\t\tList<NetworkAddressMessage> l = new ArrayList<>(list);\n\n\t\tfor (Map<NetworkAddressMessage, NetworkAddressMessage> m : knownNodes.values()) {\n\t\t\tl.removeAll(m.values());\n\t\t}\n\n\t\treturn l;\n\t}\n\n\t/**\n\t * Returns a list containing all inventory vectors from the given list that\n\t * represent objects we don't have.\n\t * \n\t * @param inventoryVectors\n\t * The inventory vectors to check.\n\t * @return The given inventory vectors without those that represent objects\n\t * that we already have.\n\t */\n\tpublic List<InventoryVectorMessage> filterObjectsThatWeAlreadyHave(List<InventoryVectorMessage> inventoryVectors) {\n\t\tList<InventoryVectorMessage> l = new ArrayList<>(inventoryVectors);\n\n\t\tl.removeAll(localObjects);\n\n\t\treturn l;\n\t}\n\n\t/**\n\t * Returns all addresses that we own.\n\t * \n\t * @return All addresses that we own.\n\t */\n\tpublic Collection<BMAddress> getAddresses() {\n\t\treturn new ArrayList<>(ownedAddresses);\n\t}\n\n\t/**\n\t * Returns a list with all nodes that belong to one of the given streams.\n\t * \n\t * @param streams\n\t * The streams.\n\t * @return A list with all nodes that belong to one of the given streams.\n\t */\n\tpublic List<NetworkAddressMessage> getNodes(long[] streams) {\n\t\tList<Map<NetworkAddressMessage, NetworkAddressMessage>> nodeLists = new ArrayList<>();\n\t\tint size = 0;\n\n\t\tfor (long stream : streams) {\n\t\t\tMap<NetworkAddressMessage, NetworkAddressMessage> s = knownNodes.get(stream);\n\n\t\t\tif (s != null) {\n\t\t\t\tnodeLists.add(s);\n\t\t\t\tsize += s.size();\n\t\t\t}\n\t\t}\n\n\t\tList<NetworkAddressMessage> l = new ArrayList<>(size);\n\n\t\tfor (Map<NetworkAddressMessage, NetworkAddressMessage> s : nodeLists) {\n\t\t\tl.addAll(s.values());\n\t\t}\n\n\t\treturn l;\n\t}\n\n\t/**\n\t * Returns the POWMessages that belong to the given InventoryVectors\n\t * (hashes).\n\t * \n\t * @param inventoryVectors\n\t * The hashes.\n\t * @return The objects that belong to the given hashes.\n\t */\n\tpublic List<POWMessage> getObjects(List<InventoryVectorMessage> inventoryVectors) {\n\t\tList<POWMessage> objects = new ArrayList<>(inventoryVectors.size());\n\n\t\tfor (InventoryVectorMessage m : inventoryVectors) {\n\t\t\tPOWMessage p = objectCache.get(m);\n\n\t\t\tif (p != null) {\n\t\t\t\tobjects.add(p);\n\t\t\t} else {\n\t\t\t\tp = database.getObject(m);\n\n\t\t\t\tif (p != null) {\n\t\t\t\t\tobjects.add(p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn objects;\n\t}\n\n\t/**\n\t * Returns a random node from the datastore.\n\t * \n\t * @return A random node from the datastore.\n\t */\n\tpublic NetworkAddressMessage getRandomNode(long stream) {\n\t\tList<NetworkAddressMessage> nodes = new ArrayList<>(knownNodes.get(stream).keySet());\n\n\t\treturn nodes.get((int) (Math.random() * nodes.size()));\n\t}\n\n\t/**\n\t * Adds the given object to the datastore.\n\t * \n\t * @param m\n\t * The object to add.\n\t * @return True if the object was added, false if it already exists.\n\t */\n\tpublic boolean put(POWMessage m) {\n\t\tInventoryVectorMessage i = m.getInventoryVector();\n\n\t\tif (localObjects.contains(i)) {\n\t\t\tobjectCache.put(i, m);\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Adds all given nodes to the datastore, if they don't exist.\n\t * \n\t * @param list\n\t * The nodes to add.\n\t * @return A list containing all nodes that were added.\n\t */\n\tpublic Collection<NetworkAddressMessage> putAll(List<NetworkAddressMessage> list) {\n\t\tList<NetworkAddressMessage> added = new ArrayList<>(list.size());\n\n\t\tfor (NetworkAddressMessage m : list) {\n\t\t\tNetworkAddressMessage before = knownNodes.get(m.getStream()).put(m, m);\n\n\t\t\tif (before == null) {\n\t\t\t\tadded.add(m);\n\t\t\t}\n\t\t}\n\n\t\treturn added;\n\t}\n\n\t/**\n\t * Removes the node with the given ip and port if its older than the\n\t * threshold (Can be set via Options).\n\t * \n\t * @param address\n\t * The address of the node.\n\t * @param port\n\t * The port of the node.\n\t */\n\tpublic void removeNodeIfOld(InetAddress address, int port) {\n\t\tfor (Map<NetworkAddressMessage, NetworkAddressMessage> s : knownNodes.values()) {\n\t\t\t// NetworkAddressMessage m = s.get(new NetworkAddressMessage(1, 1,\n\t\t\t// new NodeServicesMessage(NodeServicesMessage.NODE_NETWORK),\n\t\t\t// address, port));\n\n\t\t\t// if (m.getTime() < (System.currentTimeMillis() / 1000)\n\t\t\t// - Options.getInstance().getInt(\"data.maxNodeStorageTime\")) {\n\t\t\t// s.remove(m);\n\t\t\t// }\n\n\t\t\tthrow new RuntimeException(\"Not implemented!\");\n\t\t}\n\t}\n\n\t/**\n\t * Stops the datastore as fast as possible.\n\t */\n\tpublic void stop() {\n\t\tstop = true;\n\t}\n}", "public class InventoryVectorMessage extends Message {\n\tprivate static final Logger LOG = Logger.getLogger(InventoryVectorMessage.class.getName());\n\n\t/** The hash */\n\tprivate byte[] hash; // 32\n\n\t/**\n\t * Creates a new inventory vector message.\n\t * \n\t * @param o\n\t * The hash.\n\t */\n\tpublic InventoryVectorMessage(byte[] hash, MessageFactory factory) {\n\t\tsuper(factory);\n\n\t\tObjects.requireNonNull(hash, \"o must not be null!\");\n\n\t\tif (hash.length != 32) {\n\t\t\tthrow new IllegalArgumentException(\"hash must have a length of 32\");\n\t\t}\n\n\t\tthis.hash = hash;\n\t}\n\n\t/**\n\t * {@link Message#Message(InputBuffer, MessageFactory)}\n\t */\n\tpublic InventoryVectorMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException {\n\t\tsuper(b, factory);\n\t}\n\n\tpublic byte[] getHash() {\n\t\treturn hash;\n\t}\n\n\t@Override\n\tprotected void read(InputBuffer b) throws IOException, ParsingException {\n\t\thash = b.get(0, 32);\n\t}\n\n\t@Override\n\tpublic byte[] getBytes() {\n\t\treturn hash;\n\t}\n\n\tpublic int length() {\n\t\treturn 32;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o instanceof InventoryVectorMessage) {\n\t\t\tInventoryVectorMessage ivm = (InventoryVectorMessage) o;\n\n\t\t\treturn Arrays.equals(ivm.hash, hash);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Util.getInt(hash);\n\t}\n}", "public class MsgMessage extends POWMessage {\n\tprivate static final Logger LOG = Logger.getLogger(MsgMessage.class.getName());\n\n\t/** The command string for this message type. */\n\tpublic static final String COMMAND = \"msg\";\n\n\t/** The stream of the destination. */\n\tprivate long stream;\n\n\t/** The encrypted message. */\n\tprivate EncryptedMessage encrypted;\n\n\t/**\n\t * Creates a new msg message.\n\t * \n\t * @param stream\n\t * @param encrypted\n\t */\n\tpublic MsgMessage(long stream, EncryptedMessage encrypted, MessageFactory factory) {\n\t\tsuper(factory);\n\n\t\tObjects.requireNonNull(encrypted);\n\n\t\tif (stream == 0) {\n\t\t\tthrow new IllegalArgumentException(\"stream must not be 0.\");\n\t\t}\n\n\t\tthis.stream = stream;\n\t\tthis.encrypted = encrypted;\n\t}\n\n\t/**\n\t * {@link Message#Message(InputBuffer, MessageFactory)}\n\t */\n\tpublic MsgMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException {\n\t\tsuper(b, factory);\n\t}\n\n\tpublic long getStream() {\n\t\treturn stream;\n\t}\n\n\tpublic EncryptedMessage getEncrypted() {\n\t\treturn encrypted;\n\t}\n\n\t@Override\n\tprotected void readPayload(InputBuffer b) throws IOException, ParsingException {\n\t\tVariableLengthIntegerMessage v = getMessageFactory().parseVariableLengthIntegerMessage(b);\n\t\tb = b.getSubBuffer(v.length());\n\t\tstream = v.getLong();\n\n\t\tencrypted = getMessageFactory().parseEncryptedMessage(b);\n\t}\n\n\t@Override\n\tprotected byte[] getPayloadBytes() {\n\t\tByteArrayOutputStream b = new ByteArrayOutputStream();\n\n\t\ttry {\n\t\t\tb.write(getMessageFactory().createVariableLengthIntegerMessage(stream).getBytes());\n\t\t\tb.write(encrypted.getBytes());\n\t\t} catch (IOException e) {\n\t\t\tLOG.log(Level.SEVERE, \"Could not write bytes!\", e);\n\t\t\tSystem.exit(1);\n\t\t}\n\n\t\treturn b.toByteArray();\n\t}\n\n\t@Override\n\tpublic String getCommand() {\n\t\treturn COMMAND;\n\t}\n}", "public class NetworkAddressMessage extends Message {\n\tprivate static final Logger LOG = Logger.getLogger(NetworkAddressMessage.class.getName());\n\n\t/** Timestamp describing when the node with this address was last seen. */\n\tprivate int time;\n\n\t/** The stream number of the node described by this network address. */\n\tprivate int stream;\n\n\t/** Bitfield of features that are enabled by this node. */\n\tprivate NodeServicesMessage services;\n\n\t/** IPv6 address or IPv6 mapped IPv4 address. */\n\tprivate InetAddress ip;\n\n\t/** The port of the node. */\n\tprivate int port;\n\n\t/**\n\t * Creates a new network address message describing a node.\n\t * \n\t * @param time\n\t * The time the node was last seen.\n\t * @param stream\n\t * The stream the node belongs to.\n\t * @param services\n\t * The services the node has enabled.\n\t * @param ip\n\t * The ip of the node.\n\t * @param port\n\t * The port of the node.\n\t */\n\tpublic NetworkAddressMessage(int time, int stream, NodeServicesMessage services, InetAddress ip, int port,\n\t\t\tMessageFactory factory) {\n\t\tsuper(factory);\n\n\t\tObjects.requireNonNull(ip, \"ip must not be null!\");\n\n\t\tif (stream == 0) {\n\t\t\tthrow new IllegalArgumentException(\"stream must not be 0.\");\n\t\t}\n\n\t\tif (port < 1 || port > 65535) {\n\t\t\tthrow new IllegalArgumentException(\"port must not be in range 1 - 65535\");\n\t\t}\n\n\t\tif (!services.isSet(NodeServicesMessage.NODE_NETWORK)) {\n\t\t\tthrow new IllegalArgumentException(\"A node must have the NODE_NETWORK service enabled!\");\n\t\t}\n\n\t\tthis.time = time;\n\t\tthis.stream = stream;\n\t\tthis.services = services;\n\t\tthis.ip = ip;\n\t\tthis.port = port;\n\t}\n\n\t/**\n\t * {@link Message#Message(InputBuffer, MessageFactory)}\n\t */\n\tpublic NetworkAddressMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException {\n\t\tsuper(b, factory);\n\t}\n\n\t@Override\n\tprotected void read(InputBuffer b) throws IOException, ParsingException {\n\t\ttime = Util.getInt(b.get(0, 4));\n\t\tstream = Util.getInt(b.get(4, 4));\n\t\tb = b.getSubBuffer(8);\n\n\t\tservices = getMessageFactory().parseNodeServicesMessage(b);\n\t\tb = b.getSubBuffer(services.length());\n\n\t\tbyte[] ipBytes = b.get(0, 16);\n\n\t\ttry {\n\t\t\tif (isIpv4(ipBytes)) {\n\t\t\t\tip = InetAddress.getByAddress(Arrays.copyOfRange(ipBytes, 12, 16));\n\t\t\t} else {\n\t\t\t\tip = InetAddress.getByAddress(ipBytes);\n\t\t\t}\n\t\t} catch (UnknownHostException e) {\n\t\t\tthrow new ParsingException(\"Not an IP: \" + Arrays.toString(ipBytes));\n\t\t}\n\n\t\tbyte[] portBytes = b.get(16, 2);\n\t\tport = Util.getInt(new byte[] { 0, 0, portBytes[0], portBytes[1] });\n\n\t\tif (ip.isAnyLocalAddress() || ip.isMulticastAddress()) {\n\t\t\tthrow new ParsingException(\"IP is local or multicast!\");\n\t\t}\n\n\t\tboolean isNull = true;\n\n\t\tfor (byte a : ip.getAddress()) {\n\t\t\tif (a != 0) {\n\t\t\t\tisNull = false;\n\t\t\t}\n\t\t}\n\n\t\tif (isNull) {\n\t\t\tthrow new ParsingException(\"IP is 0\");\n\t\t}\n\t}\n\n\t@Override\n\tpublic byte[] getBytes() {\n\t\tByteArrayOutputStream b = new ByteArrayOutputStream(34);\n\n\t\ttry {\n\t\t\tb.write(Util.getBytes(time));\n\t\t\tb.write(Util.getBytes(stream));\n\t\t\tb.write(services.getBytes());\n\n\t\t\tbyte[] ip = this.ip.getAddress();\n\t\t\tif (ip.length == 4) {\n\t\t\t\tbyte[] tmpip = new byte[16];\n\n\t\t\t\ttmpip[10] = tmpip[11] = -1;\n\t\t\t\ttmpip[12] = ip[0];\n\t\t\t\ttmpip[13] = ip[1];\n\t\t\t\ttmpip[14] = ip[2];\n\t\t\t\ttmpip[15] = ip[3];\n\n\t\t\t\tip = tmpip;\n\t\t\t}\n\n\t\t\tb.write(ip);\n\n\t\t\tbyte[] port = Util.getBytes(this.port);\n\t\t\tb.write(new byte[] { port[2], port[3] });\n\t\t} catch (IOException e) {\n\t\t\tLOG.log(Level.SEVERE, \"Could not write bytes!\", e);\n\t\t\tSystem.exit(1);\n\t\t}\n\n\t\treturn b.toByteArray();\n\t}\n\n\tpublic int getTime() {\n\t\treturn time;\n\t}\n\n\tpublic int getStream() {\n\t\treturn stream;\n\t}\n\n\tpublic NodeServicesMessage getServices() {\n\t\treturn services;\n\t}\n\n\tpublic InetAddress getIp() {\n\t\treturn ip;\n\t}\n\n\t/**\n\t * Returns true if the given 16 byte ip-address is an IPv4 address, false if\n\t * it is an IPv6 address.\n\t * \n\t * @param ip\n\t * An IPv6 address or v6 mapped v4 address.\n\t * @return True if the given 16 byte ip-address is an IPv4 address, false if\n\t * it is an IPv6 address.\n\t */\n\tpublic boolean isIpv4(byte[] ip) {\n\t\tif (ip.length != 16) {\n\t\t\tthrow new IllegalArgumentException(\"ip must have a length of 16.\");\n\t\t}\n\n\t\tbyte[] prefix = new byte[12];\n\t\tprefix[10] = prefix[11] = -1;\n\n\t\treturn Arrays.equals(Arrays.copyOf(ip, 12), prefix);\n\t}\n\n\tpublic int getPort() {\n\t\treturn port;\n\t}\n\n\tpublic int length() {\n\t\treturn 34;\n\t}\n\n\t/**\n\t * Returns the hash for this object, calculated only from the ip and port.\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\tif (ip.getAddress().length == 4) {\n\t\t\treturn Util.getInt(ip.getAddress()) + port;\n\t\t} else {\n\t\t\treturn Util.getInt(Arrays.copyOfRange(ip.getAddress(), 12, 16)) + port;\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if the given object is a NetworkAddressMessage and\n\t * represents the same ip and port as this message.\n\t */\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o instanceof NetworkAddressMessage) {\n\t\t\tNetworkAddressMessage m = (NetworkAddressMessage) o;\n\n\t\t\treturn m.ip.equals(ip) && port == m.port;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n}", "public abstract class POWMessage extends P2PMessage {\n\tprivate static final Logger LOG = Logger.getLogger(POWMessage.class.getName());\n\n\t/** The proof of work nonce. Null if the pow has not been done. */\n\tprivate byte[] nonce;\n\n\t/** The time this message was sent. */\n\tprivate int time;\n\n\t/** Caches the byte representation of the payload. */\n\tprivate byte[] payloadBytes;\n\n\t/**\n\t * {@link Message#Message(MessageFactory)}\n\t */\n\tpublic POWMessage(MessageFactory factory) {\n\t\tsuper(factory);\n\t}\n\n\t/**\n\t * {@link Message#Message(InputBuffer, MessageFactory)}\n\t */\n\tpublic POWMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException {\n\t\tsuper(b, factory);\n\t}\n\n\t@Override\n\tprotected final void read(InputBuffer b) throws IOException, ParsingException {\n\t\tnonce = b.get(0, 8);\n\t\ttime = Util.getInt(b.get(8, 4));\n\n\t\tif (!CryptManager.getInstance().checkPOW(b.get(8, b.length() - 8), nonce)) {\n\t\t\tthrow new ParsingException(\"POW insufficient!\");\n\t\t}\n\n\t\treadPayload(b.getSubBuffer(12));\n\t}\n\n\t/**\n\t * Initializes the message reading the data from the input buffer.\n\t * \n\t * @param b\n\t * The input buffer to read from, must not contain POW.\n\t * @throws IOException\n\t * If reading from the given input buffer fails.\n\t * @throws ParsingException\n\t * If parsing the data fails.\n\t */\n\tprotected abstract void readPayload(InputBuffer b) throws IOException, ParsingException;\n\n\t@Override\n\tpublic final byte[] getBytes() {\n\t\tif (nonce == null) {\n\t\t\tthrow new IllegalStateException(\"POW has not been done!\");\n\t\t}\n\n\t\tcachePayload();\n\t\tByteArrayOutputStream b = new ByteArrayOutputStream();\n\n\t\ttry {\n\t\t\tb.write(nonce);\n\t\t\tb.write(Util.getBytes(time));\n\t\t\tb.write(payloadBytes);\n\t\t} catch (IOException e) {\n\t\t\tLOG.log(Level.SEVERE, \"Could not write bytes!\", e);\n\t\t\tSystem.exit(1);\n\t\t}\n\n\t\treturn b.toByteArray();\n\t}\n\n\tprivate void cachePayload() {\n\t\tif (payloadBytes == null) {\n\t\t\tpayloadBytes = getPayloadBytes();\n\t\t}\n\t}\n\n\t/**\n\t * Does the POW for this message.<br />\n\t * <b>WARNING: Takes a long time!!!</b>\n\t */\n\tpublic void doPOW() {\n\t\tcachePayload();\n\n\t\tbyte[] b = new byte[payloadBytes.length + 4];\n\t\tbyte[] time = Util.getBytes(this.time);\n\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tb[i] = time[i];\n\t\t}\n\n\t\tfor (int i = 0; i < payloadBytes.length; i++) {\n\t\t\tb[i + 4] = payloadBytes[i];\n\t\t}\n\n\t\tnonce = CryptManager.getInstance().doPOW(b);\n\t}\n\n\t/**\n\t * Creates a byte array of containing this message without POW.\n\t * \n\t * @return A byte array of containing this message without POW.\n\t */\n\tprotected abstract byte[] getPayloadBytes();\n\n\tpublic int getTime() {\n\t\treturn time;\n\t}\n\n\t/**\n\t * Calculates the hash of this object. This method uses two rounds of sha512\n\t * and returns the first 32 bytes of the sum.\n\t * \n\t * @return The first 32 bytes of a 2-rounds sha512 hash of the object.\n\t */\n\tpublic byte[] getHash() {\n\t\treturn Digest.sha512(Digest.sha512(getBytes()), 32);\n\t}\n\n\t/**\n\t * Returns the inventory vector describing this message.\n\t * \n\t * @return The inventory vector describing this message.\n\t */\n\tpublic InventoryVectorMessage getInventoryVector() {\n\t\treturn getMessageFactory().createInventoryVectorMessage(getHash());\n\t}\n}", "public final class Util {\n\tprivate static final Logger LOG = Logger.getLogger(Util.class.getName());\n\n\tpublic static byte[] getBytes(ECPublicKey publicKey) {\n\t\tbyte[] x = getUnsignedBytes(publicKey.getQ().getX().toBigInteger(), 32);\n\t\tbyte[] y = getUnsignedBytes(publicKey.getQ().getY().toBigInteger(), 32);\n\t\tbyte[] result = new byte[64];\n\n\t\tSystem.arraycopy(x, 0, result, 0, 32);\n\t\tSystem.arraycopy(y, 0, result, 32, 32);\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns a byte array containing the bytes of the given integer in big\n\t * endian order.\n\t * \n\t * @param i\n\t * The integer to convert.\n\t * @return A byte array containing the 4 bytes of the given integer in big\n\t * endian order.\n\t */\n\tpublic static byte[] getBytes(int i) {\n\t\treturn new byte[] { (byte) (i >> 24), (byte) (i >> 16 & 0xFF), (byte) (i >> 8 & 0xFF), (byte) (i & 0xFF) };\n\t}\n\n\t/**\n\t * Returns a byte array containing the bytes of the given long in big endian\n\t * order.\n\t * \n\t * @param l\n\t * The long to convert.\n\t * @return A byte array containing the 4 bytes of the given long in big\n\t * endian order.\n\t */\n\tpublic static byte[] getBytes(long l) {\n\t\treturn new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40), (byte) (l >> 32), (byte) (l >> 24),\n\t\t\t\t(byte) (l >> 16 & 0xFF), (byte) (l >> 8 & 0xFF), (byte) (l & 0xFF) };\n\t}\n\n\t/**\n\t * Returns a byte array containing the bytes of the given short in big\n\t * endian order.\n\t * \n\t * @param i\n\t * The short to convert.\n\t * @return A byte array containing the 2 bytes of the given short in big\n\t * endian order.\n\t */\n\tpublic static byte[] getBytes(short i) {\n\t\treturn new byte[] { (byte) (i >> 8), (byte) (i & 0xFF) };\n\t}\n\n\t/**\n\t * Creates an integer created from the given bytes.\n\t * \n\t * @param b\n\t * The byte data in big endian order.\n\t * @return An integer created from the given bytes.\n\t */\n\tpublic static int getInt(byte[] b) {\n\t\tint i = 0;\n\n\t\ti |= (b[0] & 0xFF) << 24;\n\t\ti |= (b[1] & 0xFF) << 16;\n\t\ti |= (b[2] & 0xFF) << 8;\n\t\ti |= (b[3] & 0xFF);\n\n\t\treturn i;\n\t}\n\n\t/**\n\t * Returns a long created from the given bytes.\n\t * \n\t * @param b\n\t * The byte data in big endian order.\n\t * @return A long created from the given bytes.\n\t */\n\tpublic static long getLong(byte[] b) {\n\t\tlong l = 0;\n\n\t\tl |= (b[0] & 0xFFL) << 56;\n\t\tl |= (b[1] & 0xFFL) << 48;\n\t\tl |= (b[2] & 0xFFL) << 40;\n\t\tl |= (b[3] & 0xFFL) << 32;\n\t\tl |= (b[4] & 0xFFL) << 24;\n\t\tl |= (b[5] & 0xFFL) << 16;\n\t\tl |= (b[6] & 0xFFL) << 8;\n\t\tl |= (b[7] & 0xFFL);\n\n\t\treturn l;\n\t}\n\n\tpublic static ECPublicKey getPublicKey(byte[] b) {\n\t\tif (b.length != 64) {\n\t\t\tthrow new IllegalArgumentException(\"Need exactly 64 bytes, but have \" + b.length + \".\");\n\t\t}\n\n\t\tBigInteger x = getUnsignedBigInteger(b, 0, 32);\n\t\tBigInteger y = getUnsignedBigInteger(b, 32, 32);\n\n\t\treturn CryptManager.getInstance().createPublicEncryptionKey(x, y);\n\t}\n\n\t/**\n\t * Returns a short created from the given bytes.\n\t * \n\t * @param b\n\t * The byte data in big endian order.\n\t * @return A short created from the given bytes.\n\t */\n\tpublic static short getShort(byte[] b) {\n\t\treturn getShort(b, 0);\n\t}\n\n\t/**\n\t * Returns a short created from the given bytes.\n\t * \n\t * @param b\n\t * The byte data in big endian order.\n\t * @param offset\n\t * The first byte of the number.\n\t * @return A short created from the given bytes.\n\t */\n\tpublic static short getShort(byte[] b, int offset) {\n\t\tshort s = 0;\n\n\t\ts |= (b[offset] & 0xFF) << 8;\n\t\ts |= (b[offset + 1] & 0xFF);\n\n\t\treturn s;\n\t}\n\n\t/**\n\t * Returns a positive BigInteger from the given bytes. (Big endian)\n\t * \n\t * @param data\n\t * The bytes.\n\t * @param offset\n\t * The first byte.\n\t * @param length\n\t * The amount of bytes to process.\n\t * @return A BigInteger from the given bytes.\n\t */\n\tpublic static BigInteger getUnsignedBigInteger(byte[] data, int offset, int length) {\n\t\tif (length == 0) {\n\t\t\treturn BigInteger.ZERO;\n\t\t}\n\n\t\tbyte[] value = new byte[length + 1];\n\t\tSystem.arraycopy(data, offset, value, 1, length);\n\n\t\treturn new BigInteger(value);\n\t}\n\n\t/**\n\t * Returns an unsigned byte[] representation of the given big integer.\n\t * \n\t * @param number\n\t * The BigInteger. Must be >= 0.\n\t * @param length\n\t * The maximum length.\n\t * @return The last <code>length</code> bytes of the given big integer,\n\t * filled with zeros if necessary.\n\t */\n\tpublic static byte[] getUnsignedBytes(BigInteger number, int length) {\n\t\tbyte[] value = number.toByteArray();\n\n\t\tif (value.length > length + 1) {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"The given BigInteger does not fit into a byte array with the given length: \" + value.length\n\t\t\t\t\t\t\t+ \" > \" + length);\n\t\t}\n\n\t\tbyte[] result = new byte[length];\n\n\t\tint i = value.length == length + 1 ? 1 : 0;\n\t\tfor (; i < value.length; i++) {\n\t\t\tresult[i + length - value.length] = value[i];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Utility class */\n\tprivate Util() {\n\t}\n}" ]
import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Vector; import java.util.logging.Logger; import sibbo.bitmessage.Options; import sibbo.bitmessage.data.Datastore; import sibbo.bitmessage.network.protocol.InventoryVectorMessage; import sibbo.bitmessage.network.protocol.MsgMessage; import sibbo.bitmessage.network.protocol.NetworkAddressMessage; import sibbo.bitmessage.network.protocol.POWMessage; import sibbo.bitmessage.network.protocol.Util;
package sibbo.bitmessage.network; /** * Manages the operation of this bitmessage node. It is responsible for all * communication with other nodes. * * @author Sebastian Schmidt * @version 1.0 */ public class NetworkManager implements ConnectionListener, Runnable { private static final Logger LOG = Logger.getLogger(NetworkManager.class.getName()); /** * Contains all connections managed by this object.<br /> * Thread-safe */ private final List<Connection> connections = new Vector<>(); /** * The objects that listen for network status changes.<br /> * Thread-safe */ private final List<NetworkListener> listeners = new Vector<>(); /** The datastore that makes all data persistent. */ private final Datastore datastore; /** Contains all objects that are currently requested from a node. */ // Note that this is a bad method to ensure that we get all objects but // don't get anything twice. If someone sends an inv but never responds to a // getdata and keeps connected, the respective objects will be blocked and // can only be received if the network manager is restarted. private final Map<InventoryVectorMessage, Connection> alreadyRequested = new Hashtable<>(); /** * The parser to parse new objects. This is used to prevent timing attacks * on the network manager thread. */ private final ObjectParser objectParser; /** If this is true, the network manager stops as fast as possible. */ private volatile boolean stop; /** * True if someone connected to us. That means that we are reachable from * outside. */ private boolean activeMode; /** A random nonce to detect connections to self. */ private final long nonce; /** * Creates a new network manager operating on the datastore at the given * path. * * @param datastore * The name of the datastore. */ public NetworkManager(String datastoreName) { this.datastore = new Datastore(datastoreName); objectParser = new ObjectParser(datastore.getAddresses()); Random r = new Random(); byte[] nonce = new byte[8]; r.nextBytes(nonce);
this.nonce = Util.getLong(nonce);
6
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/ModlogEvents.java
[ "public class RedisController {\n\n private static JedisPool jedisPool;\n\n public static BlockingQueue<RedisSetData> setQueue = new LinkedBlockingQueue<>();\n\n private RedisController() {\n }\n\n public RedisController(JSONConfig config) {\n jedisPool = new JedisPool(\n new JedisPoolConfig(),\n config.getString(\"redis.host\").get(),\n Integer.parseInt(config.getString(\"redis.port\").get()),\n 3000,\n config.getString(\"redis.password\").get().isEmpty() ? null : config.getString(\"redis.password\").get());\n try (Jedis jedis = jedisPool.getResource()) {\n String response = jedis.ping();\n if (!(\"PONG\".equals(response))) throw new IOException(\"Ping to server failed!\");\n FlareBot.LOGGER.info(\"Redis started with a DB Size of {}\", jedis.dbSize());\n } catch (Exception e) {\n FlareBot.LOGGER.error(\"Could not connect to redis!\", e);\n return;\n }\n new Thread(() -> {\n try (Jedis jedis = RedisController.getJedisPool().getResource()) {\n jedis.monitor(new JedisMonitor() {\n public void onCommand(String command) {\n String finalCommand = command;\n if (command.contains(\"AUTH\")) finalCommand = \"AUTH\";\n FlareBot.LOGGER.debug(\"Executing redis command: {}\", command.substring(finalCommand.lastIndexOf(\"]\") + 1).trim());\n }\n });\n }\n }, \"Redis-Monitor\").start();\n Thread setThread = new Thread(() -> {\n while (!FlareBot.EXITING.get()) {\n try {\n RedisSetData data = RedisController.setQueue.poll(2, TimeUnit.SECONDS);\n if (data != null) {\n try (Jedis jedis = RedisController.getJedisPool().getResource()) {\n data.set(jedis);\n FlareBot.LOGGER.debug(\"Saving redis value with key: \" + data.getKey());\n }\n }\n\n } catch (Exception e) {\n FlareBot.LOGGER.error(\"Error in set thread!\", e);\n }\n }\n }, \"Redis-SetThread\");\n setThread.start();\n }\n\n public static JedisPool getJedisPool() {\n return jedisPool;\n }\n\n /**\n * Expires a key after a certain amount of time\n *\n * @param key The key to set the expiry on\n * @param seconds The amount of seconds to expire after\n * @return {@code 0} if the key does not exist. <br>\n * {@code 1} if the expiry was successfully set.\n */\n public static Long expire(String key, int seconds) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.expire(key, seconds);\n }\n }\n\n /**\n * Expires a key after a certain amount of milliseconds\n *\n * @param key The key to set the expiry on\n * @param millis The number of milliseconds to expire after\n * @return {@code 0} if the key does not exist. <br>\n * {@code 1} if the expiry was successfully set.\n */\n public static Long pExpire(String key, long millis) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.pexpire(key, millis);\n }\n }\n\n /**\n * Expires a key after at a certain unix time in seconds.\n * <i>If the unix time is in the past the key is deleted</i>\n *\n * @param key The key to set the expiry on\n * @param unixTime The unix time in seconds to expire the key at\n * @return {@code 0} if the key does not exist. <br>\n * {@code 1} if the expiry was successfully set.\n */\n public static Long expireAt(String key, long unixTime) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.expireAt(key, unixTime);\n }\n }\n\n /**\n * Expires a key after at a certain unix time in milliseconds.\n * <i>If the unix time is in the past the key is deleted</i>\n *\n * @param key The key to set the expiry on\n * @param unixTime The unix time in milliseconds to expire the key at\n * @return {@code 0} if the key does not exist. <br>\n * {@code 1} if the expiry was successfully set.\n */\n public static Long pExpireAt(String key, long unixTime) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.pexpireAt(key, unixTime);\n }\n }\n\n /**\n * Gets the TTL in seconds for the specified key\n *\n * @param key The key to check for TTL\n * @return The TTL of the specified key in seconds. <br>\n * {@code -2} if the key does not exist. <br>\n * {@code -1} if the key exists but has no associated expire.\n */\n public static Long ttl(String key) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.ttl(key);\n }\n }\n\n /**\n * Gets the TTL in milliseconds for the specified key\n *\n * @param key The key to check for TTL\n * @return The TTL of the specified key in milliseconds. <br>\n * {@code -2} if the key does not exist. <br>\n * {@code -1} if the key exists but has no associated expire.\n */\n public static Long pttl(String key) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.pttl(key);\n }\n }\n\n /**\n * Sets a value with a specific key in the datebase\n *\n * @param key The key to set\n * @param value The value to set at the key\n */\n public static void set(String key, String value) {\n setQueue.add(new RedisSetData(key, value));\n }\n\n /**\n * Sets a value with a specific key in the datebase\n *\n * @param key The key to set\n * @param value The value to set at the key\n * @param nxxx {@code NX} to set the key only if doesn't exist <br>\n * {@code XX} to set the key only if it exists <br>\n * Otherwise use {@link RedisController#set(String, String)}\n */\n public static void set(String key, String value, String nxxx) {\n setQueue.add(new RedisSetData(key, value, nxxx));\n }\n\n /**\n * Sets a value with a specific key in the datebase\n *\n * @param key The key to set\n * @param value The value to set at the key\n * @param nxxx {@code NX} to set the key only if doesn't exist <br>\n * {@code XX} to set the key only if it exists <br>\n * Otherwise use empty value\n * @param pxex {@code PX} to set the expiry in milliseconds <br>\n * {@code EX} to set the expiry in seconds <br>\n * Otherwise use {@link RedisController#set(String, String, String)}\n * @param time The expiry time to set\n */\n public static void set(String key, String value, String nxxx, String pxex, long time) {\n setQueue.add(new RedisSetData(key, value, nxxx, pxex, time));\n }\n\n /**\n * Gets a value from the database\n *\n * @param key The key to get from redis\n * @return The value of the key or {@code null} if the key doesn't exist\n */\n public static String get(String key) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.get(key);\n }\n }\n\n /**\n * Deletes one or more keys from Eedis\n *\n * @param keys The keys to remove\n * @return The amount of keys that were removed\n */\n public static Long del(String... keys) {\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.del(keys);\n }\n }\n\n /**\n * Check whether a key exists\n *\n * @param key The key to check\n * @return Whether the specified key exists or not\n */\n public static boolean exists(String key) {\n if (key == null) return false;\n try (Jedis jedis = jedisPool.getResource()) {\n return jedis.exists(key);\n }\n }\n\n\n}", "public class RedisMessage {\n\n private final String messageID;\n private final String authorID;\n private final String channelID;\n private final String guildID;\n private final String content;\n private final long timestamp;\n\n public RedisMessage(String messageID, String authorID, String channelID, String guildID, String content, long timestamp) {\n this.messageID = messageID;\n this.authorID = authorID;\n this.channelID = channelID;\n this.guildID = guildID;\n this.content = content;\n this.timestamp = timestamp;\n }\n\n public String getMessageID() {\n return messageID;\n }\n\n public String getAuthorID() {\n return authorID;\n }\n\n public String getChannelID() {\n return channelID;\n }\n\n public String getGuildID() {\n return guildID;\n }\n\n public String getContent() {\n return content;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n}", "public enum ModlogEvent {\n\n MEMBER_JOIN(\"Member Joined\", \"Triggers when user joins the server.\", ColorUtils.GREEN, true),\n MEMBER_LEAVE(\"Member Left\", \"Triggers when user leaves the server.\", ColorUtils.ORANGE, true),\n\n MEMBER_NICK_CHANGE(\"Nickname Change\", \"Triggers when a user changes their nick.\", ColorUtils.FLAREBOT_BLUE, true),\n\n MEMBER_ROLE_GIVE(\"Role Give\", \"Triggers when a role is added to a user.\", ColorUtils.GREEN, true),\n MEMBER_ROLE_REMOVE(\"Role Remove\", \"Triggers when a role is taken away a user.\", ColorUtils.ORANGE, true),\n\n MEMBER_VOICE_JOIN(\"Voice Join\", \"Triggers when a user joins a voice channel.\", ColorUtils.FLAREBOT_BLUE, false),\n MEMBER_VOICE_LEAVE(\"Voice Leave\", \"Triggers when a user leaves a voice channel.\", ColorUtils.FLAREBOT_BLUE, false),\n MEMBER_VOICE_MOVE(\"Voice Move\", \"Triggers when a user moves to a different voice channel. \" +\n \"Either because they moved or because they where force moved.\", ColorUtils.FLAREBOT_BLUE, false),\n\n // These are events triggered mostly by our mod actions\n USER_BANNED(\"User Banned\", \"Triggers when a user is banned, either through Discord or a bot\", ColorUtils.RED, true, true),\n USER_SOFTBANNED(\"User Soft Banned\", \"Triggers when a user is softbanned using FlareBot\", ColorUtils.RED, true, true),\n USER_TEMP_BANNED(\"User Temp Banned\", \"Triggers when a user is temporarily banned using FlareBot\", ColorUtils.RED, true, true),\n USER_UNBANNED(\"User Unbanned\", \"Triggers when a user is unbanned, either through Discord or a bot\", ColorUtils.FLAREBOT_BLUE, true, true),\n\n USER_KICKED(\"User Kicked\", \"Triggers when a user is kicked.\", ColorUtils.ORANGE, true, true),\n\n USER_MUTED(\"User Muted\", \"Triggers when a user is muted using FlareBot\", ColorUtils.ORANGE, true, true),\n USER_TEMP_MUTED(\"User Temp Muted\", \"Triggers when a user is temporary muted using FlareBot\", ColorUtils.ORANGE, true, true),\n USER_UNMUTED(\"User Unmuted\", \"Triggers when a user is unmuted\", ColorUtils.FLAREBOT_BLUE, true, true),\n\n USER_WARNED(\"User Warned\", \"Triggers when a user is warned using FlareBot\", ColorUtils.ORANGE, true, true),\n\n REPORT_SUBMITTED(\"User Reported\", \"Triggers when a user is reported using FlareBot\", ColorUtils.ORANGE, true, true),\n REPORT_EDITED(\"Report Edited\", \"Triggers when a report is edited\", ColorUtils.FLAREBOT_BLUE, true, true),\n /////////////////\n\n ROLE_CREATE(\"Role Create\", \"Triggers when a role is created.\", ColorUtils.GREEN, true),\n ROLE_DELETE(\"Role Delete\", \"Triggers when a role is deleted.\", ColorUtils.RED, true),\n ROLE_EDIT(\"Role Edit\", \"Triggers when a role is edited.\", ColorUtils.FLAREBOT_BLUE, false),\n\n CHANNEL_CREATE(\"Channel Create\", \"Triggers when a channel is created.\", ColorUtils.GREEN, true),\n CHANNEL_DELETE(\"Channel Delete\", \"Triggers when a channel is deleted.\", ColorUtils.RED, true),\n\n MESSAGE_EDIT(\"Message Edit\", \"Triggers when a message is edited.\", ColorUtils.FLAREBOT_BLUE, true),\n MESSAGE_DELETE(\"Message Delete\", \"Triggers when a message is deleted.\", ColorUtils.RED, true),\n\n GUILD_EXPLICIT_FILTER_CHANGE(\"Explicit Filter Change\", \"Triggers when the server's explicit filter level is changed.\",\n ColorUtils.ORANGE, false),\n GUILD_UPDATE(\"Settings Update\", \"Triggers when any of the server setting are changed.\", ColorUtils.FLAREBOT_BLUE, false),\n\n FLAREBOT_AUTOASSIGN_ROLE(\"Autoassign Role\", \"Triggers when a role is automatically given to a user\",\n ColorUtils.GREEN, true),\n FLAREBOT_COMMAND(\"Command\", \"Triggers when a user runs a **FlareBot** command.\", ColorUtils.FLAREBOT_BLUE,\n false),\n FLAREBOT_PURGE(\"Purge\", \"Triggers when a user does a purge with FlareBot.\", ColorUtils.FLAREBOT_BLUE, false),\n \n NINO(\"NINO Caught Link\", \"Triggers when NINO catches a spoopy link!\", ColorUtils.ORANGE, false, false, true);\n\n public static final ModlogEvent[] values = values();\n public static final List<ModlogEvent> events = Arrays.asList(values);\n\n private String title;\n private String description;\n private Color color;\n private boolean defaultEvent;\n private boolean showReason;\n private boolean hidden = false;\n\n // GSONs needs\n ModlogEvent() {\n }\n\n ModlogEvent(String title, String description, Color color, boolean defaultEvent) {\n this.title = title;\n this.description = description;\n this.color = color;\n this.defaultEvent = defaultEvent;\n this.showReason = false;\n }\n\n ModlogEvent(String title, String description, Color color, boolean defaultEvent, boolean showReason) {\n this.title = title;\n this.description = description;\n this.color = color;\n this.defaultEvent = defaultEvent;\n this.showReason = showReason;\n }\n \n ModlogEvent(String title, String description, Color color, boolean defaultEvent, boolean showReason, boolean hidden) {\n this.title = title;\n this.description = description;\n this.color = color;\n this.defaultEvent = defaultEvent;\n this.showReason = showReason;\n this.hidden = hidden;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Color getColor() {\n return color;\n }\n\n public EmbedBuilder getEventEmbed(User user, User responsible) {\n return getEventEmbed(user, responsible, null);\n }\n\n public EmbedBuilder getEventEmbed(User user, User responsible, String reason) {\n if (user == null && responsible == null) {\n throw new IllegalArgumentException(\"User or the responsible user has to be not-null! Event: \" + this.getName());\n }\n EmbedBuilder eb = new EmbedBuilder()\n .setAuthor(WordUtils.capitalize(getTitle()), null, user == null ? responsible.getEffectiveAvatarUrl()\n : user.getEffectiveAvatarUrl());\n if (user != null)\n eb.addField(\"User\", user.getAsMention() + \" | \" + MessageUtils.getTag(user), true);\n eb.setFooter(\"User ID: \" + (user == null ? responsible.getId() : user.getId()), null)\n .setTimestamp(OffsetDateTime.now(ZoneOffset.UTC));\n if (responsible != null) {\n eb.addField(\"Responsible\", MessageUtils.getTag(responsible), true);\n }\n if (showReason) {\n eb.addField(\"Reason\", (reason == null || reason.isEmpty() ? \"No Reason Given!\" : reason), true);\n }\n eb.setColor(color);\n\n // Custom event changes.\n if (this == ModlogEvent.FLAREBOT_PURGE)\n eb.setAuthor(user != null ? \"User Purge\" : \"Chat Purge\", null, user == null ? responsible.getEffectiveAvatarUrl()\n : user.getEffectiveAvatarUrl());\n return eb;\n }\n\n public String getEventText(User user, User responsible, String reason) {\n if (user == null && responsible == null) {\n throw new IllegalArgumentException(\"User or the responsible user has to be not-null! Event: \" + this.getName());\n }\n String title = WordUtils.capitalize(getTitle());\n // Custom event changes.\n if (this == ModlogEvent.FLAREBOT_PURGE)\n title = user != null ? \"User Purge\" : \"Chat Purge\";\n\n StringBuilder sb = new StringBuilder()\n .append(title)\n .append(\" (\").append(FormatUtils.formatTime(OffsetDateTime.now(ZoneOffset.UTC).toLocalDateTime()))\n .append(\")\\n\");\n\n if (user != null)\n sb.append(\"**User**: `\").append(MessageUtils.getTag(user)).append(\"` (\").append(user.getId()).append(\") \");\n if (responsible != null) {\n sb.append(\"**Responsible**: `\").append(MessageUtils.getTag(responsible)).append(\"` (\")\n .append(responsible.getId()).append(\") \");\n }\n if (showReason) {\n sb.append(\"**Reason**: \").append(reason == null || reason.isEmpty() ? \"No Reason Given!\" : reason);\n }\n return sb.toString().trim();\n }\n\n public String getTitle() {\n return title;\n }\n\n public boolean isDefaultEvent() {\n return defaultEvent;\n }\n\n public String getName() {\n return WordUtils.capitalize(name().toLowerCase().replaceAll(\"_\", \" \"));\n }\n\n public ModlogAction getAction(long channelId) {\n return new ModlogAction(channelId, this, false);\n }\n\n public static ModlogEvent getEvent(String arg) {\n for (ModlogEvent event : values()) {\n if (event.getName().equalsIgnoreCase(arg) || event.getTitle().equalsIgnoreCase(arg)) {\n return event;\n }\n }\n return null;\n }\n\n\n}", "public class ModlogHandler {\n\n private static ModlogHandler instance;\n\n public static ModlogHandler getInstance() {\n if (instance == null) instance = new ModlogHandler();\n return instance;\n }\n\n /**\n * This will get the TextChannel of a certain event, this could also return null in two cases.<br>\n * <ol>\n * <li>They don't have a channel set for the event</li>\n * <li>The channel set is in another guild.</li>\n * </ol>\n *\n * @param wrapper GuildWrapper of the desired guild to check.\n * @param event The event to check.\n * @return The TextChannel of the desired event in the desired guild or null in the two cases listed above.\n */\n public TextChannel getModlogChannel(GuildWrapper wrapper, ModlogEvent event) {\n for (ModlogAction modlogAction : wrapper.getModConfig().getEnabledActions())\n if (modlogAction.getEvent() == event)\n return wrapper.getGuild().getTextChannelById(modlogAction.getModlogChannelId());\n return null;\n }\n\n public void postToModlog(GuildWrapper wrapper, ModlogEvent event, User user) {\n postToModlog(wrapper, event, user, null, null, new MessageEmbed.Field[0]);\n }\n\n public void postToModlog(GuildWrapper wrapper, ModlogEvent event, User user, MessageEmbed.Field... fields) {\n postToModlog(wrapper, event, user, null, null, fields);\n }\n\n public void postToModlog(GuildWrapper wrapper, ModlogEvent event, User user, EmbedBuilder builder) {\n postToModlog(wrapper, event, user, null, null, builder.getFields().toArray(new\n MessageEmbed.Field[builder.getFields().size()]));\n }\n\n public void postToModlog(GuildWrapper wrapper, ModlogEvent event, User target, User responsible, String reason) {\n postToModlog(wrapper, event, target, responsible, reason, new MessageEmbed.Field[0]);\n }\n\n public void postToModlog(GuildWrapper wrapper, ModlogEvent event, User target, User responsible, String reason,\n MessageEmbed.Field... extraFields) {\n if (!wrapper.getModeration().isEventEnabled(wrapper, event)) return;\n TextChannel tc = getModlogChannel(wrapper, event);\n // They either don't have a channel or set it to another guild.\n if (tc != null) {\n if (!tc.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_EMBED_LINKS)) {\n tc.getGuild().getOwner().getUser().openPrivateChannel().queue(pc -> {\n pc.sendMessage(\"Please give me permission to read message, write messages and embed links in the modlog channel: \"\n + tc.getAsMention()\n + \" or set the modlog channel to one I have access to!\").queue();\n });\n return;\n }\n if (!wrapper.getModeration().isEventCompacted(event)) {\n EmbedBuilder eb = event.getEventEmbed(target, responsible, reason);\n if (extraFields != null && extraFields.length > 0) {\n for (MessageEmbed.Field field : extraFields)\n eb.addField(field);\n }\n\n tc.sendMessage(eb.build()).queue();\n } else {\n StringBuilder sb = new StringBuilder(event.getEventText(target, responsible, reason));\n if (extraFields != null && extraFields.length > 0) {\n sb.append(\"\\n\");\n for (MessageEmbed.Field field : extraFields) {\n if (field == null) continue;\n sb.append(\"**\").append(field.getName()).append(\"**: \").append(field.getValue()).append(\"\\t\");\n }\n }\n sb.append(\"\\n** **\");\n tc.sendMessage(sb.toString().trim()).queue();\n }\n }\n }\n\n /**\n * Handle a ModAction, this will do a bunch of checks and if they pass it will handle said action. For example if\n * you want to ban someone it will do checks like if you can ban that user, ig they're the owner, if you're trying\n * to ban yourself etc. After those pass it will then do the actual banning, post to the modlog and handle any tmp\n * stuff if needed. <br />\n * This will run the {@link #handleAction(GuildWrapper, TextChannel, User, User, ModAction, String, long)} method\n * with a -1 duration.\n *\n * @param wrapper The GuildWrapper of the guild this is being done in.\n * @param channel The channel this was executed, this is used for failire messages in the checks.\n * @param sender The person who sent that said action, the user responsible.\n * @param target The target user to have the action taken against.\n * @param modAction The ModAction to be performed.\n * @param reason The reason this was done, if this is null it will default to \"No Reason Given\".\n */\n public void handleAction(GuildWrapper wrapper, TextChannel channel, User sender, User target, ModAction modAction,\n String reason) {\n handleAction(wrapper, channel, sender, target, modAction, reason, -1);\n }\n\n /**\n * Handle a ModAction, this will do a bunch of checks and if they pass it will handle said action. For example if\n * you want to ban someone it will do checks like if you can ban that user, ig they're the owner, if you're trying\n * to ban yourself etc. After those pass it will then do the actual banning, post to the modlog and handle any tmp\n * stuff if needed.<br />\n * See also {@link #handleAction(GuildWrapper, TextChannel, User, User, ModAction, String)}\n *\n * @param wrapper The GuildWrapper of the guild this is being done in.\n * @param channel The channel this was executed, this is used for failire messages in the checks.\n * @param sender The person who sent that said action, the user responsible.\n * @param target The target user to have the action taken against.\n * @param modAction The ModAction to be performed.\n * @param reason The reason this was done, if this is null it will default to \"No Reason Given\".\n * @param duration The duration of said action, this only applies to temp actions, -1 should be passed otherwise.\n */\n public void handleAction(GuildWrapper wrapper, TextChannel channel, User sender, User target, ModAction modAction,\n String reason, long duration) {\n String rsn = (reason == null ? \"No reason given!\" : reason.replaceAll(\"`\", \"'\"));\n Member member = null;\n if (target != null) {\n member = wrapper.getGuild().getMember(target);\n }\n if (channel == null) return;\n if (member == null && modAction != ModAction.FORCE_BAN && modAction != ModAction.UNBAN) {\n MessageUtils.sendErrorMessage(\"That user isn't in this server!\"\n + (modAction == ModAction.KICK ? \" You can forceban with `{%}forceban <id>` to keep them from coming back.\" : \"\"), channel);\n return;\n }\n\n // Make sure the target user isn't the guild owner\n if (member != null && member.isOwner()) {\n MessageUtils.sendErrorMessage(String.format(\"Cannot %s **%s** because they're the guild owner!\",\n modAction.getLowercaseName(), MessageUtils.getTag(target)), channel);\n return;\n }\n\n // Make sure the target user isn't themselves\n if (target != null && sender != null && target.getIdLong() == sender.getIdLong()) {\n MessageUtils.sendErrorMessage(String.format(\"You cannot %s yourself you daft person!\",\n modAction.getLowercaseName()), channel);\n return;\n }\n\n if (target != null && target.getIdLong() == FlareBot.instance().getClient().getSelfUser().getIdLong()) {\n if (modAction == ModAction.UNBAN || modAction == ModAction.UNMUTE)\n MessageUtils.sendWarningMessage(\"W-why would you want to do that in the first place. Meanie :(\", channel);\n else\n MessageUtils.sendWarningMessage(String.format(\"T-that's meannnnnnn :( I can't %s myself and I hope you don't want to either :(\",\n modAction.getLowercaseName()), channel);\n return;\n }\n\n // Check if the person is below the target in role hierarchy\n if (member != null && sender != null && !canInteract(wrapper.getGuild().getMember(sender), member, wrapper)) {\n MessageUtils.sendErrorMessage(String.format(\"You cannot %s a user who is higher than you in the role hierarchy!\",\n modAction.getLowercaseName()), channel);\n return;\n }\n\n // Check if there role is higher therefore we can't take action, this should be something applied to everything\n // not just kick, ban etc.\n if (member != null && !wrapper.getGuild().getSelfMember().canInteract(member)) {\n MessageUtils.sendErrorMessage(String.format(\"Cannot \" + modAction.getLowercaseName() + \" %s! \" +\n \"Their highest role is higher than my highest role or they're the guild owner.\",\n MessageUtils.getTag(target)), channel);\n return;\n }\n\n try {\n // BAN\n switch (modAction) {\n case BAN:\n channel.getGuild().getController().ban(target, 7, reason).queue(aVoid ->\n channel.sendMessage(new EmbedBuilder().setColor(Color.GREEN)\n .setDescription(\"The ban hammer has been struck on \" + target.getName()\n + \" <:banhammer:368861419602575364>\\nReason: \" + rsn)\n .setImage(channel.getGuild().getIdLong() == Constants.OFFICIAL_GUILD ?\n \"https://flarebot.stream/img/banhammer.png\" : null)\n .build()).queue());\n break;\n case SOFTBAN:\n channel.getGuild().getController().ban(target, 7, reason).queue(aVoid -> {\n channel.sendMessage(new EmbedBuilder().setColor(Color.GREEN)\n .setDescription(target.getName() + \" was softly hit with the ban hammer... \" +\n \"this time\\nReason: \" + rsn)\n .build()).queue();\n channel.getGuild().getController().unban(target).queue();\n });\n break;\n case FORCE_BAN:\n channel.getGuild().getController().ban(target.getId(), 7, reason).queue(aVoid ->\n channel.sendMessage(new EmbedBuilder().setColor(Color.GREEN)\n .setDescription(\"The ban hammer has been forcefully struck on \" + target.getName()\n + \" <:banhammer:368861419602575364>\\nReason: \" + rsn)\n .setImage(channel.getGuild().getIdLong() == Constants.OFFICIAL_GUILD ?\n \"https://flarebot.stream/img/banhammer.png\" : null)\n .build()).queue());\n break;\n case TEMP_BAN: {\n Period period = new Period(duration);\n channel.getGuild().getController().ban(channel.getGuild().getMember(target), 7, reason).queue(aVoid -> {\n channel.sendMessage(new EmbedBuilder()\n .setDescription(\"The ban hammer has been struck on \" + target.getName() + \" for \"\n + FormatUtils.formatJodaTime(period) + \"\\nReason: \" + rsn)\n .setImage(channel.getGuild().getIdLong() == Constants.OFFICIAL_GUILD\n ? \"https://flarebot.stream/img/banhammer.png\" : null)\n .setColor(Color.WHITE).build()).queue();\n Scheduler.queueFutureAction(channel.getGuild().getIdLong(), channel.getIdLong(), sender.getIdLong(),\n target.getIdLong(), reason, period, FutureAction.Action.TEMP_BAN);\n });\n break;\n }\n case UNBAN:\n if (target == null) return;\n wrapper.getGuild().getController().unban(target).queue();\n\n MessageUtils.sendSuccessMessage(\"Unbanned \" + target.getAsMention() + \"!\", channel, sender);\n // MUTE\n break;\n case MUTE:\n try {\n wrapper.getModeration().muteUser(wrapper, wrapper.getGuild().getMember(target));\n } catch (HierarchyException e) {\n MessageUtils.sendErrorMessage(\"Cannot apply the mute role, make sure it is below FlareBot in the \" +\n \"role hierarchy.\",\n channel);\n return;\n }\n\n MessageUtils.sendSuccessMessage(\"Muted \" + target.getAsMention() + \"\\nReason: \" + rsn, channel, sender);\n break;\n case TEMP_MUTE: {\n try {\n wrapper.getModeration().muteUser(wrapper, wrapper.getGuild().getMember(target));\n } catch (HierarchyException e) {\n MessageUtils.sendErrorMessage(\"Cannot apply the mute role, make sure it is below FlareBot in the \" +\n \"role hierarchy.\",\n channel);\n return;\n }\n\n Period period = new Period(duration);\n Scheduler.queueFutureAction(channel.getGuild().getIdLong(), channel.getIdLong(), sender.getIdLong(),\n target.getIdLong(), reason, period, FutureAction.Action.TEMP_MUTE);\n\n MessageUtils.sendSuccessMessage(\"Temporarily Muted \" + target.getAsMention() + \" for \"\n + FormatUtils.formatJodaTime(period) + \"\\nReason: \" + rsn, channel, sender);\n break;\n }\n case UNMUTE:\n if (wrapper.getMutedRole() != null && wrapper.getGuild().getMember(target).getRoles()\n .contains(wrapper.getMutedRole())) {\n wrapper.getModeration().unmuteUser(wrapper, member);\n MessageUtils.sendSuccessMessage(\"Unmuted \" + target.getAsMention(), channel, sender);\n } else {\n MessageUtils.sendErrorMessage(\"That user isn't muted!!\", channel);\n }\n\n // KICK and WARN\n break;\n case KICK:\n channel.getGuild().getController().kick(member, reason).queue(aVoid ->\n MessageUtils.sendSuccessMessage(target.getName() + \" has been kicked from the server!\\nReason: \" + rsn,\n channel, sender));\n break;\n case WARN:\n wrapper.addWarning(target, (reason != null ? reason : \"No reason provided - action done by \"\n + sender.getName()));\n EmbedBuilder eb = new EmbedBuilder();\n eb.appendDescription(\"\\u26A0 Warned \" + MessageUtils.getTag(target)\n + \"\\nReason: \" + rsn)\n .setColor(Color.WHITE);\n channel.sendMessage(eb.build()).queue();\n break;\n default:\n throw new IllegalArgumentException(\"An illegal ModAction was attempted to be handled - \"\n + modAction.toString());\n }\n } catch (PermissionException e) {\n MessageUtils.sendErrorMessage(String.format(\"Cannot \" + modAction.getLowercaseName() + \" %s! \" +\n \"I do not have the `\" + e.getPermission().getName() + \"` permission!\",\n MessageUtils.getTag(target)), channel);\n return;\n }\n // TODO: Infraction\n postToModlog(wrapper, modAction.getEvent(), target, sender, rsn);\n }\n\n private boolean canInteract(Member sender, Member target, GuildWrapper wrapper) {\n if (target.isOwner() || target.hasPermission(Permission.ADMINISTRATOR))\n return true;\n\n if (target.getRoles().isEmpty() || sender.getRoles().isEmpty()) {\n return true;\n }\n\n Role muteRole = wrapper.getMutedRole();\n Role topMemberRole = sender.getRoles().get(0);\n Role topTargetRole = target.getRoles().get(0);\n if (muteRole != null) {\n if (topMemberRole.getIdLong() == muteRole.getIdLong() && sender.getRoles().size() > 1)\n topMemberRole = sender.getRoles().get(1);\n if (topTargetRole.getIdLong() == muteRole.getIdLong() && target.getRoles().size() > 1)\n topTargetRole = target.getRoles().get(1);\n }\n return topMemberRole.getPosition() > topTargetRole.getPosition();\n }\n}", "public class GuildWrapper {\n\n public static transient final long DATA_VERSION = 1;\n public final long dataVersion = DATA_VERSION;\n\n private String guildId;\n private char prefix = Constants.COMMAND_CHAR;\n private Welcome welcome = new Welcome();\n private PerGuildPermissions permissions = new PerGuildPermissions();\n private Set<String> autoAssignRoles = new HashSet<>();\n private Set<String> selfAssignRoles = new HashSet<>();\n private boolean songnick = false;\n // Should be moved to their own manager.\n private boolean blocked = false;\n private long unBlockTime = -1;\n private String blockReason = null;\n // TODO: Move to Moderation fully - This will be a breaking change so we will basically just refer to the new location\n private String mutedRoleID = null;\n private ReportManager reportManager = new ReportManager();\n private Map<String, List<String>> warnings = new ConcurrentHashMap<>();\n private Map<String, String> tags = new ConcurrentHashMap<>();\n private String musicAnnounceChannelId = null;\n private Moderation moderation;\n private NINO nino = null;\n private GuildSettings settings = null;\n\n // oooo special!\n private boolean betaAccess = false;\n\n /**\n * <b>Do not use</b>\n *\n * @param guildId Guild Id of the desired new GuildWrapper\n */\n public GuildWrapper(String guildId) {\n this.guildId = guildId;\n }\n\n public Guild getGuild() {\n return Getters.getGuildById(guildId);\n }\n\n public String getGuildId() {\n return this.guildId;\n }\n\n public long getGuildIdLong() {\n return Long.parseLong(this.guildId);\n }\n\n public Welcome getWelcome() {\n if (welcome == null) {\n welcome = new Welcome();\n welcome.setDmEnabled(false);\n welcome.setGuildEnabled(false);\n }\n return this.welcome;\n }\n\n public PerGuildPermissions getPermissions() {\n if (permissions == null) {\n permissions = new PerGuildPermissions();\n }\n return permissions;\n }\n\n public void setPermissions(PerGuildPermissions permissions) {\n this.permissions = permissions;\n }\n\n public Set<String> getAutoAssignRoles() {\n return this.autoAssignRoles;\n }\n\n public Set<String> getSelfAssignRoles() {\n return this.selfAssignRoles;\n }\n\n public boolean isBlocked() {\n return this.blocked;\n }\n\n public void addBlocked(String reason) {\n blocked = true;\n blockReason = reason;\n unBlockTime = -1; //-1 represents both infinite and unblocked\n }\n\n public void addBlocked(String reason, long unBlockTime) {\n blocked = true;\n blockReason = reason;\n this.unBlockTime = unBlockTime;\n }\n\n public void revokeBlock() {\n blocked = false;\n blockReason = \"\";\n unBlockTime = -1; //-1 represents both infinite and unblocked\n }\n\n public String getBlockReason() {\n return blockReason;\n }\n\n public long getUnBlockTime() {\n return unBlockTime;\n }\n\n public boolean isSongnickEnabled() {\n return songnick;\n }\n\n public void setSongnick(boolean songnick) {\n this.songnick = songnick;\n }\n\n @Nullable\n public Role getMutedRole() {\n if (mutedRoleID == null) {\n Role mutedRole =\n GuildUtils.getRole(\"Muted\", getGuild()).isEmpty() ? null : GuildUtils.getRole(\"Muted\", getGuild()).get(0);\n if (mutedRole == null) {\n if (!getGuild().getSelfMember().hasPermission(Permission.MANAGE_ROLES, Permission.MANAGE_PERMISSIONS))\n return null;\n try {\n mutedRole = getGuild().getController().createRole().setName(\"Muted\").submit().get();\n if (!getGuild().getSelfMember().getRoles().isEmpty())\n getGuild().getController().modifyRolePositions().selectPosition(mutedRole)\n .moveTo(getGuild().getSelfMember().getRoles().get(0).getPosition() - 1).queue();\n mutedRoleID = mutedRole.getId();\n handleMuteChannels(mutedRole);\n return mutedRole;\n } catch (InterruptedException | ExecutionException e) {\n FlareBot.LOGGER.error(\"Error creating role!\", e);\n return null;\n }\n } else {\n mutedRoleID = mutedRole.getId();\n handleMuteChannels(mutedRole);\n return mutedRole;\n }\n } else {\n Role mutedRole = getGuild().getRoleById(mutedRoleID);\n if (mutedRole == null) {\n mutedRoleID = null;\n return getMutedRole();\n } else {\n handleMuteChannels(mutedRole);\n return mutedRole;\n }\n }\n }\n\n /**\n * This will go through all the channels in a guild, if there is no permission override or it doesn't block message write then deny it.\n *\n * @param muteRole This is the muted role of the server, the role which will have MESSAGE_WRITE denied.\n */\n private void handleMuteChannels(Role muteRole) {\n getGuild().getTextChannels().forEach(channel -> {\n if (!getGuild().getSelfMember().hasPermission(channel, Permission.MANAGE_PERMISSIONS)) return;\n if (channel.getPermissionOverride(muteRole) != null &&\n !channel.getPermissionOverride(muteRole).getDenied().contains(Permission.MESSAGE_WRITE))\n channel.getPermissionOverride(muteRole).getManager().deny(Permission.MESSAGE_WRITE).queue();\n else if (channel.getPermissionOverride(muteRole) == null)\n channel.createPermissionOverride(muteRole).setDeny(Permission.MESSAGE_WRITE).queue();\n });\n }\n\n public ReportManager getReportManager() {\n if (reportManager == null) reportManager = new ReportManager();\n return reportManager;\n }\n\n public List<String> getUserWarnings(User user) {\n if (warnings == null) warnings = new ConcurrentHashMap<>();\n return warnings.getOrDefault(user.getId(), new ArrayList<>());\n }\n\n public void addWarning(User user, String reason) {\n List<String> warningsList = getUserWarnings(user);\n warningsList.add(reason);\n warnings.put(user.getId(), warningsList);\n }\n\n public Map<String, List<String>> getWarningsMap() {\n return warnings;\n }\n\n public boolean hasBetaAccess() {\n return betaAccess;\n }\n\n public void setBetaAccess(boolean betaAccess) {\n this.betaAccess = betaAccess;\n }\n\n public boolean getBetaAccess() {\n return betaAccess;\n }\n\n public Map<String, String> getTags() {\n if (tags == null) tags = new ConcurrentHashMap<>();\n return tags;\n }\n\n public Moderation getModeration() {\n if (this.moderation == null) this.moderation = new Moderation();\n return this.moderation;\n }\n\n public Moderation getModConfig() {\n return getModeration();\n }\n\n public char getPrefix() {\n return prefix == Character.MIN_VALUE ? (prefix = Constants.COMMAND_CHAR) : prefix;\n }\n\n public void setPrefix(char prefix) {\n this.prefix = prefix;\n }\n\n public String getMusicAnnounceChannelId() {\n return musicAnnounceChannelId;\n }\n\n public void setMusicAnnounceChannelId(String musicAnnounceChannelId) {\n this.musicAnnounceChannelId = musicAnnounceChannelId;\n }\n\n public NINO getNINO() {\n if (nino == null)\n nino = new NINO();\n return nino;\n }\n\n public GuildSettings getSettings() {\n if (settings == null)\n settings = new GuildSettings();\n return settings;\n }\n}", "public class GeneralUtils {\n\n //Constants\n private static final DecimalFormat percentageFormat = new DecimalFormat(\"#.##\");\n private static final Pattern timeRegex = Pattern.compile(\"^([0-9]*):?([0-9]*)?:?([0-9]*)?$\");\n\n private static final PeriodFormatter periodParser = new PeriodFormatterBuilder()\n .appendWeeks().appendSuffix(\"w\")\n .appendDays().appendSuffix(\"d\")\n .appendHours().appendSuffix(\"h\")\n .appendMinutes().appendSuffix(\"m\")\n .appendSeconds().appendSuffix(\"s\")\n .toFormatter();\n\n\n /**\n * Gets a user count for a guild not including bots\n *\n * @param guild The guild to get the user count for\n * @return The amount of non-bot users in a guild\n */\n public static int getGuildUserCount(Guild guild) {\n int i = 0;\n for (Member member : guild.getMembers()) {\n if (!member.getUser().isBot()) {\n i++;\n }\n }\n return i;\n }\n\n /**\n * Gets the {@link Report} embed with all of the info on the report.\n *\n * @param sender The {@link User} who requested the embed\n * @param report The {@link Report} to get the embed of.\n * @return an {@link EmbedBuilder} that contains all the report data\n */\n public static EmbedBuilder getReportEmbed(User sender, Report report) {\n EmbedBuilder eb = MessageUtils.getEmbed(sender);\n User reporter = Getters.getUserById(report.getReporterId());\n User reported = Getters.getUserById(report.getReportedId());\n\n eb.addField(\"Report ID\", String.valueOf(report.getId()), true);\n eb.addField(\"Reporter\", reporter != null ? MessageUtils.getTag(reporter) : \"Unknown\", true);\n eb.addField(\"Reported\", reported != null ? MessageUtils.getTag(reported) : \"Unknown\", true);\n\n //eb.addField(\"Time\", report.getTime().toLocalDateTime().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \" GMT/BST\", true);\n eb.setTimestamp(report.getTime().toLocalDateTime());\n eb.addField(\"Status\", report.getStatus().getMessage(), true);\n\n eb.addField(\"Message\", \"```\" + report.getMessage() + \"```\", false);\n StringBuilder builder = new StringBuilder(\"The last 5 messages by the reported user: ```\\n\");\n for (ReportMessage m : report.getMessages()) {\n builder.append(\"[\").append(m.getTime().toLocalDateTime().format(DateTimeFormatter.ofPattern(\"HH:mm:ss\"))).append(\" GMT/BST] \")\n .append(FormatUtils.truncate(100, m.getMessage()))\n .append(\"\\n\");\n }\n builder.append(\"```\");\n eb.addField(\"Messages from reported user\", builder.toString(), false);\n return eb;\n }\n\n /**\n * Gets the string representing the current page out of total.\n * Example: 6/10.\n *\n * @param page The current page.\n * @param items The items that are being paged.\n * @param pageLength The page length.\n * @return A string representing the current page out of the total pages which was calculated from the items and page length.\n */\n public static String getPageOutOfTotal(int page, List<?> items, int pageLength) {\n return page + \"/\" + String.valueOf(items.size() < pageLength ? 1 : (items.size() / pageLength) + (items.size() % pageLength != 0 ? 1 : 0));\n }\n\n /**\n * Gets the progress bar for the current {@link Track} including the percent played.\n *\n * @param track The {@link Track} to get a progress bar for.\n * @return A string the represents a progress bar that represents the time played.\n */\n public static String getProgressBar(Track track) {\n float percentage = (100f / track.getTrack().getDuration() * track.getTrack().getPosition());\n return \"[\" + StringUtils.repeat(\"▬\", (int) Math.round((double) percentage / 10)) +\n \"](https://github.com/FlareBot)\" +\n StringUtils.repeat(\"▬\", 10 - (int) Math.round((double) percentage / 10)) +\n \" \" + GeneralUtils.percentageFormat.format(percentage) + \"%\";\n }\n\n /**\n * Gets a String stacktrace from a {@link Throwable}.\n * This return the String you'd typical see with printStackTrace()\n *\n * @param e the {@link Throwable}.\n * @return A string representing the stacktrace.\n */\n public static String getStackTrace(Throwable e) {\n StringWriter writer = new StringWriter();\n PrintWriter printWriter = new PrintWriter(writer);\n e.printStackTrace(printWriter);\n printWriter.close();\n return writer.toString();\n }\n\n /**\n * Gets an int from a String.\n * The default value you pass is what it return if their was an error parsing the string.\n * This happens when the string you enter isn't an int. For example if you enter in 'no'.\n *\n * @param s The string to parse an int from.\n * @param defaultValue The default int value to get in case parsing fails.\n * @return The int parsed from the string or the default value.\n */\n public static int getInt(String s, int defaultValue) {\n try {\n return Integer.parseInt(s);\n } catch (NumberFormatException e) {\n return defaultValue;\n }\n }\n\n /**\n * Gets an int from a String.\n * The default value you pass is what it return if their was an error parsing the string.\n * This happens when the string you enter isn't an int. For example if you enter in 'no'.\n *\n * @param s The string to parse an byte from.\n * @param defaultValue The default int value to get in case parsing fails.\n * @return The int parsed from the string or the default value.\n */\n public static byte getByte(String s, byte defaultValue) {\n try {\n return Byte.parseByte(s);\n } catch (NumberFormatException e) {\n return defaultValue;\n }\n }\n\n /**\n * Gets an int from a String.\n * The default value you pass is what it return if their was an error parsing the string.\n * This happens when the string you enter isn't an int. For example if you enter in 'no'.\n *\n * @param s The string to parse an int from.\n * @param defaultValue The default int value to get in case parsing fails.\n * @return The int parsed from the string or the default value.\n */\n public static int getPositiveInt(String s, int defaultValue) {\n try {\n int i = Integer.parseInt(s);\n return (i >= 0 ? i : defaultValue);\n } catch (NumberFormatException e) {\n return defaultValue;\n }\n }\n\n /**\n * Gets a long from a String.\n * The default value you pass is what it return if their was an error parsing the string.\n * This happens when the string you enter isn't an int. For example if you enter in 'no'.\n *\n * @param s The string to parse a long from.\n * @param defaultValue The default long value to get in case parsing fails.\n * @return The long parsed from the string or the default value.\n */\n public static long getLong(String s, long defaultValue) {\n try {\n return Long.parseLong(s);\n } catch (NumberFormatException e) {\n return defaultValue;\n }\n }\n\n /**\n * Get a Joda {@link Period} from the input string.\n * This will convert something like `1d20s` to 1 day and 20 seconds.\n * If the format isn't correct we throw an error message to the channel.\n *\n * @param input The input string to parse.\n * @return The joda Period or null if the format is not correct.\n */\n public static Period getTimeFromInput(String input, TextChannel channel) {\n try {\n return periodParser.parsePeriod(input);\n } catch (IllegalArgumentException e) {\n MessageUtils.sendErrorMessage(\"The duration is not in the correct format! Try something like `1d`\",\n channel);\n return null;\n }\n }\n\n /**\n * Gets the changes between two lists.\n * Represented by a map where the true value is the things added and the false\n * is the things removed with the unchanged being left out.\n *\n * @param oldList The old list\n * @param newList The new List\n * @return A map where the added objects are true, and the removed objects are false. the values the same are not included.\n */\n public static <T> Map<Boolean, List<T>> getChanged(List<T> oldList, List<T> newList) {\n Map<Boolean, List<T>> changes = new HashMap<>();\n List<T> removed = new ArrayList<>();\n List<T> added = new ArrayList<>();\n for (T oldItem : oldList) {\n if (!newList.contains(oldItem)) {\n removed.add(oldItem);\n }\n }\n for (T newItem : newList) {\n if (!oldList.contains(newItem)) {\n added.add(newItem);\n }\n }\n changes.put(true, added);\n changes.put(false, removed);\n return changes;\n }\n\n /**\n * Gets the suffix for the a day in a month\n * Example: 1st\n *\n * @param n The day in the month to get a suffix.\n * @return The suffix for the day.\n */\n public static String getDayOfMonthSuffix(final int n) {\n if (n < 1 || n > 31) throw new IllegalArgumentException(\"illegal day of month: \" + n);\n if (n >= 11 && n <= 13) {\n return \"th\";\n }\n switch (n % 10) {\n case 1:\n return \"st\";\n case 2:\n return \"nd\";\n case 3:\n return \"rd\";\n default:\n return \"th\";\n }\n }\n\n /**\n * Message fields:\n * - Message ID\n * - Author ID\n * - Channel ID\n * - Guild ID\n * - Raw Content\n * - Timestamp (Epoch seconds)\n *\n * @param message The message to serialise\n * @return The serialised message\n */\n public static String getRedisMessageJson(Message message) {\n return FlareBot.GSON.toJson(new RedisMessage(\n message.getId(),\n message.getAuthor().getId(),\n message.getChannel().getId(),\n message.getGuild().getId(),\n message.getContentRaw(),\n message.getCreationTime().toInstant().toEpochMilli()\n ));\n }\n\n /**\n * Coverts the json from redis to a RedisMessage.\n * Message fields:\n * - Message ID\n * - Author ID\n * - Channel ID\n * - Guild ID\n * - Raw Content\n * - Timestamp (Epoch seconds)\n *\n * @param json The json to convert\n * @return {@link RedisMessage}\n * @throws IllegalArgumentException This throws if the json doesn't match what {@link RedisMessage} is expecting.\n */\n public static RedisMessage toRedisMessage(String json) throws IllegalArgumentException {\n Pair<List<String>, List<String>> paths = jsonContains(json,\n \"messageID\",\n \"authorID\",\n \"channelID\",\n \"guildID\",\n \"content\",\n \"timestamp\"\n );\n if (paths.getKey().size() != 6) {\n throw new IllegalArgumentException(\"Malformed JSON! Missing paths: \" +\n Arrays.toString(paths.getValue().toArray(new String[paths.getValue().size()])));\n }\n return FlareBot.GSON.fromJson(json, RedisMessage.class);\n }\n\n /**\n * Gets the String representing the verification level.\n * For {@link Guild.VerificationLevel#HIGH} and {@link Guild.VerificationLevel#VERY_HIGH}\n * we return the unicode characters and not the string it's self.\n *\n * @param level The verification level to get the string version.\n * @return A string representing the verification level.\n */\n public static String getVerificationString(Guild.VerificationLevel level) {\n switch (level) {\n case HIGH:\n return \"(\\u256F\\u00B0\\u25A1\\u00B0\\uFF09\\u256F\\uFE35 \\u253B\\u2501\\u253B\"; //(╯°□°)╯︵ ┻━┻\n case VERY_HIGH:\n return \"\\u253B\\u2501\\u253B\\u5F61 \\u30FD(\\u0CA0\\u76CA\\u0CA0)\\u30CE\\u5F61\\u253B\\u2501\\u253B\"; //┻━┻彡 ヽ(ಠ益ಠ)ノ彡┻━┻\n default:\n return level.toString().charAt(0) + level.toString().substring(1).toLowerCase();\n }\n }\n\n /**\n * Parses time from string.\n * The input can be in these formats\n * s\n * m:s\n * h:m:s\n * XhXmXs\n * Examples:\n * 5 - Would be 5 seconds\n * 5s - Would also be 5 seconds\n * 1:10 - Would be 1 minute and 10 seconds\n * 1m10s - Would also be 1 minute and 10 seconds\n * 1:00:00 - Would be an hour\n * 1h - Would also be an hour\n *\n * @param time The time string to parse.\n * @return The long representing the time entered in millis from when this method was ran.\n */\n public static Long parseTime(String time) {\n Matcher digitMatcher = timeRegex.matcher(time);\n if (digitMatcher.matches()) {\n try {\n return new PeriodFormatterBuilder()\n .appendHours().appendSuffix(\":\")\n .appendMinutes().appendSuffix(\":\")\n .appendSeconds()\n .toFormatter()\n .parsePeriod(time)\n .toStandardDuration().getMillis();\n } catch (IllegalArgumentException e) {\n return null;\n }\n }\n PeriodFormatter formatter = new PeriodFormatterBuilder()\n .appendHours().appendSuffix(\"h\")\n .appendMinutes().appendSuffix(\"m\")\n .appendSeconds().appendSuffix(\"s\")\n .toFormatter();\n Period period;\n try {\n period = formatter.parsePeriod(time);\n } catch (IllegalArgumentException e) {\n return null;\n }\n return period.toStandardDuration().getMillis();\n }\n\n /**\n * Converts an {@link MessageEmbed} into a String.\n * This will first start with the title in bold. then adds the description.\n * Then puts in all the fields with the title fallowed by the value. The finally the footer italicized.\n *\n * @param embed The {@link MessageEmbed} to convert\n * @return The String containing embed data\n */\n public static String embedToText(MessageEmbed embed) {\n StringBuilder sb = new StringBuilder();\n\n if (embed.getTitle() != null)\n sb.append(\"**\").append(embed.getTitle()).append(\"**: \");\n if (embed.getDescription() != null)\n sb.append(embed.getDescription()).append(\" \");\n for (MessageEmbed.Field field : embed.getFields()) {\n sb.append(\"**\").append(field.getName()).append(\"**: \").append(field.getValue()).append(\" \");\n }\n if (embed.getFooter() != null)\n sb.append(\"*\").append(embed.getFooter().getText()).append(\"*\");\n return sb.toString();\n }\n\n /**\n * Resolves an {@link AudioItem} from a string.\n * This can be a url or search terms\n *\n * @param player The music player\n * @param input The string to get the AudioItem from.\n * @return {@link AudioItem} from the string.\n * @throws IllegalArgumentException If the Item couldn't be found due to it not existing on Youtube.\n * @throws IllegalStateException If the Video is unavailable for Flare, for example if it was published by VEVO.\n */\n public static AudioItem resolveItem(Player player, String input) throws IllegalArgumentException, IllegalStateException {\n Optional<AudioItem> item = Optional.empty();\n boolean failed = false;\n int backoff = 2;\n Throwable cause = null;\n for (int i = 0; i <= 2; i++) {\n try {\n item = Optional.ofNullable(player.resolve(input));\n failed = false;\n break;\n } catch (FriendlyException | InterruptedException | ExecutionException e) {\n failed = true;\n cause = e;\n if (e.getMessage().contains(\"Vevo\")) {\n throw new IllegalStateException(Jsoup.clean(cause.getMessage(), Whitelist.none()), cause);\n }\n FlareBot.LOGGER.error(Markers.NO_ANNOUNCE, \"Cannot get video '\" + input + \"'\");\n try {\n Thread.sleep(backoff);\n } catch (InterruptedException ignored) {\n }\n backoff ^= 2;\n }\n }\n if (failed) {\n throw new IllegalStateException(Jsoup.clean(cause.getMessage(), Whitelist.none()), cause);\n } else if (!item.isPresent()) {\n throw new IllegalArgumentException();\n }\n return item.get();\n }\n\n public static String truncate(int length, String string) {\n return truncate(length, string, true);\n }\n\n public static String truncate(int length, String string, boolean ellipse) {\n return string.substring(0, Math.min(string.length(), length - (ellipse ? 3 : 0))) + (string.length() >\n length - (ellipse ? 3 : 0) && ellipse ? \"...\" : \"\");\n }\n\n @Deprecated\n @Nullable\n public static TextChannel getChannel(String arg) {\n return getChannel(arg, null);\n }\n\n @Deprecated\n @Nullable\n public static TextChannel getChannel(String channelArg, GuildWrapper wrapper) {\n return GuildUtils.getChannel(channelArg, wrapper);\n }\n\n /**\n * Orders a Collection alphabetic by whatever {@link String#valueOf(Object)} returns.\n *\n * @param strings The Collection to order.\n * @return The ordered List.\n */\n public static <T extends Comparable> List<T> orderList(Collection<? extends T> strings) {\n List<T> list = new ArrayList<>(strings);\n list.sort(Comparable::compareTo);\n return list;\n }\n\n /**\n * This will download and cache the image if not found already!\n *\n * @param fileUrl Url to download the image from.\n * @param fileName Name of the image file.\n * @param user User to send the image to.\n */\n public static void sendImage(String fileUrl, String fileName, User user) {\n try {\n File dir = new File(\"imgs\");\n if (!dir.exists() && !dir.mkdir())\n throw new IllegalStateException(\"Cannot create 'imgs' folder!\");\n File image = new File(\"imgs\" + File.separator + fileName);\n if (!image.exists() && image.createNewFile()) {\n URL url = new URL(fileUrl);\n HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();\n conn.setRequestProperty(\"User-Agent\", \"Mozilla/5.0 FlareBot\");\n InputStream is = conn.getInputStream();\n OutputStream os = new FileOutputStream(image);\n byte[] b = new byte[2048];\n int length;\n while ((length = is.read(b)) != -1) {\n os.write(b, 0, length);\n }\n is.close();\n os.close();\n }\n user.openPrivateChannel().complete().sendFile(image, fileName, null)\n .queue();\n } catch (IOException | ErrorResponseException e) {\n FlareBot.LOGGER.error(\"Unable to send image '\" + fileName + \"'\", e);\n }\n }\n\n /**\n * Runs code and catches any errors. It prints success, error and start messages as appropriate to the specified logger.\n *\n * @param logger The logger to log to.\n * @param startMessage The start message. Gets sent to the logger when the runnable starts.\n * @param successMessage The success message. Gets sent to the logger if the runnable finished successfully.\n * @param errorMessage The error message. Gets sent to the logger if an error is thrown in the runnable.\n * @param runnable The {@link Runnable} to run.\n */\n public static void methodErrorHandler(Logger logger, String startMessage,\n String successMessage, String errorMessage,\n Runnable runnable) {\n Objects.requireNonNull(successMessage);\n Objects.requireNonNull(errorMessage);\n if (startMessage != null) logger.info(startMessage);\n try {\n runnable.run();\n logger.info(successMessage);\n } catch (Exception e) {\n logger.error(errorMessage, e);\n }\n }\n\n /**\n * This is to handle \"multi-selection commands\" for example the info and stats commands which take one or more\n * arguments and get select data from an enum\n */\n public static void handleMultiSelectionCommand(User sender, TextChannel channel, String[] args,\n MultiSelectionContent<String, String, Boolean>[] providedContent) {\n String search = MessageUtils.getMessage(args);\n String[] fields = search.split(\",\");\n EmbedBuilder builder = MessageUtils.getEmbed(sender).setColor(Color.CYAN);\n boolean valid = false;\n for (String string : fields) {\n String s = string.trim();\n for (MultiSelectionContent<String, String, Boolean> content : providedContent) {\n if (s.equalsIgnoreCase(content.getName()) || s.replaceAll(\"_\", \" \")\n .equalsIgnoreCase(content.getName())) {\n builder.addField(content.getName(), content.getReturn(), content.isAlign());\n valid = true;\n }\n }\n }\n if (valid) channel.sendMessage(builder.build()).queue();\n\n else MessageUtils.sendErrorMessage(\"That piece of information could not be found!\", channel);\n }\n\n /**\n * Checks if paths exist in the given json\n * <p>\n * Key of the {@link Pair} is a list of the paths that exist in the JSON\n * Value of the {@link Pair} is a list of the paths that don't exist in the JSON\n *\n * @param json The JSON to check <b>Mustn't be null</b>\n * @param paths The paths to check <b>Mustn't be null or empty</b>\n * @return\n */\n public static Pair<List<String>, List<String>> jsonContains(String json, String... paths) {\n Objects.requireNonNull(json);\n Objects.requireNonNull(paths);\n if (paths.length == 0)\n throw new IllegalArgumentException(\"Paths cannot be empty!\");\n JsonElement jelem = FlareBot.GSON.fromJson(json, JsonElement.class);\n JSONConfig config = new JSONConfig(jelem.getAsJsonObject());\n List<String> contains = new ArrayList<>();\n List<String> notContains = new ArrayList<>();\n for (String path : paths) {\n if (path == null) continue;\n if (config.getElement(path).isPresent())\n contains.add(path);\n else\n notContains.add(path);\n }\n return new Pair<>(Collections.unmodifiableList(contains), Collections.unmodifiableList(notContains));\n }\n\n /**\n * Returns a lookup map for an enum, using the passed transform function.\n *\n * @param clazz The clazz of the enum\n * @param mapper The mapper. Must be bijective as it otherwise overwrites keys/values.\n * @param <T> the enum type\n * @param <R> the type of map key\n * @return a map with the given key and the enum value associated with it\n * @apiNote Thanks to I Al Istannen#1564 for this\n */\n public static <T extends Enum, R> Map<R, T> getReverseMapping(Class<T> clazz, Function<T, R> mapper) {\n Map<R, T> result = new HashMap<>();\n\n for (T t : clazz.getEnumConstants()) {\n result.put(mapper.apply(t), t);\n }\n\n return result;\n }\n\n public static boolean canRunInternalCommand(@Nonnull Command command, User user) {\n return canRunInternalCommand(command.getType(), user);\n }\n\n /**\n * If the user can run the command, this will check if the command is null and if it is internal.\n * If internal it will check the official guild to see if the user has the right role.\n * <b>This does not check permissions</b>\n *\n * @return If the command is not internal or if the role has the right role to run an internal command.\n */\n public static boolean canRunInternalCommand(@Nonnull CommandType type, User user) {\n if (type.isInternal()) {\n if (FlareBot.instance().isTestBot() && PerGuildPermissions.isContributor(user))\n return true;\n Guild g = Getters.getOfficialGuild();\n\n if (g != null && g.getMember(user) != null) {\n for (long roleId : type.getRoleIds())\n if (g.getMember(user).getRoles().contains(g.getRoleById(roleId)))\n return true;\n } else\n return false;\n }\n return false;\n }\n}", "public class GuildUtils {\n\n private static final Pattern userDiscrim = Pattern.compile(\".+#[0-9]{4}\");\n private static final int LEVENSHTEIN_DISTANCE = 8;\n\n /**\n * Gets the prefix for the specified {@link Guild}\n *\n * @param guild The {@link Guild} to get a prefix from\n * @return A char that is the guilds prefix\n */\n public static char getPrefix(Guild guild) {\n return guild == null ? Constants.COMMAND_CHAR : FlareBotManager.instance().getGuild(guild.getId()).getPrefix();\n }\n\n /**\n * Gets the prefix from the {@link GuildWrapper}\n *\n * @param guild The {@link GuildWrapper} that represents the guild that you want to get the prefix from\n * @return A char that is the guilds prefix\n */\n public static char getPrefix(GuildWrapper guild) {\n return guild == null ? Constants.COMMAND_CHAR : guild.getPrefix();\n }\n\n /**\n * Gets the number of users that the {@link Guild} has. Not including bots.\n *\n * @param guild The {@link Guild} to get the user count from\n * @return An int of the number of users\n */\n public static int getGuildUserCount(Guild guild) {\n int i = 0;\n for (Member member : guild.getMembers()) {\n if (!member.getUser().isBot()) {\n i++;\n }\n }\n return i;\n }\n\n /**\n * Gets a list of {@link Role} that match a string. Case doesn't matter.\n *\n * @param string The String to get a list of {@link Role} from.\n * @param guild The {@link Guild} to get the roles from.\n * @return an empty if no role matches, otherwise a list of roles matching the string.\n */\n public static List<Role> getRole(String string, Guild guild) {\n return guild.getRolesByName(string, true);\n }\n\n /**\n * Gets a {@link Role} from a string. Case Doesn't matter.\n *\n * @param s The String to get a role from\n * @param guildId The id of the {@link Guild} to get the role from\n * @return null if the role doesn't, otherwise a list of roles matching the string\n */\n public static Role getRole(String s, String guildId) {\n return getRole(s, guildId, null);\n }\n\n /**\n * Gets a {@link Role} that matches a string. Case doesn't matter.\n *\n * @param s The String to get a role from\n * @param guildId The id of the {@link Guild} to get the role from\n * @param channel The channel to send an error message to if anything goes wrong.\n * @return null if the role doesn't, otherwise a list of roles matching the string\n */\n public static Role getRole(String s, String guildId, TextChannel channel) {\n Guild guild = Getters.getGuildById(guildId);\n Role role = guild.getRoles().stream()\n .filter(r -> r.getName().equalsIgnoreCase(s))\n .findFirst().orElse(null);\n if (role != null) return role;\n try {\n role = guild.getRoleById(Long.parseLong(s.replaceAll(\"[^0-9]\", \"\")));\n if (role != null) return role;\n } catch (NumberFormatException | NullPointerException ignored) {\n }\n if (channel != null) {\n if (guild.getRolesByName(s, true).isEmpty()) {\n String closest = null;\n int distance = LEVENSHTEIN_DISTANCE;\n for (Role role1 : guild.getRoles().stream().filter(role1 -> FlareBotManager.instance().getGuild(guildId).getSelfAssignRoles()\n .contains(role1.getId())).collect(Collectors.toList())) {\n int currentDistance = StringUtils.getLevenshteinDistance(role1.getName(), s);\n if (currentDistance < distance) {\n distance = currentDistance;\n closest = role1.getName();\n }\n }\n MessageUtils.sendErrorMessage(\"That role does not exist! \"\n + (closest != null ? \"Maybe you mean `\" + closest + \"`\" : \"\"), channel);\n return null;\n } else {\n return guild.getRolesByName(s, true).get(0);\n }\n }\n return null;\n }\n\n /**\n * Gets a {@link User} from a string. Not case sensitive.\n * The string can eater be their name, their id, or them being mentioned.\n *\n * @param s the string to get the user from\n * @return null if the user wasn't found otherwise a {@link User}\n */\n public static User getUser(String s) {\n return getUser(s, null);\n }\n\n /**\n * Gets a {@link User} from a string. Not case sensitive.\n * The string can eater be their name, their id, or them being mentioned.\n *\n * @param s The string to get the user from.\n * @param guildId The string id of the {@link Guild} to get the user from.\n * @return null if the user wasn't found otherwise a {@link User}.\n */\n public static User getUser(String s, String guildId) {\n return getUser(s, guildId, false);\n }\n\n /**\n * Gets a {@link User} from a string. Not case sensitive.\n * The string can eater be their name, their id, or them being mentioned.\n *\n * @param s The string to get the user from\n * @param forceGet If you want to get the user from Discord instead of from a guild\n * @return null if the user wasn't found otherwise a {@link User}\n * @throws\n */\n public static User getUser(String s, boolean forceGet) {\n return getUser(s, null, forceGet);\n }\n\n /**\n * Gets a {@link User} from a string. Not case sensitive.\n * The string can eater be their name, their id, or them being mentioned.\n *\n * @param s The string to get the user from.\n * @param guildId The id of the {@link Guild} to get the user from.\n * @param forceGet If you want to get the user from discord instead of from a guild.\n * @return null if the user wasn't found otherwise a {@link User}.\n */\n public static User getUser(String s, String guildId, boolean forceGet) {\n Guild guild = guildId == null || guildId.isEmpty() ? null : Getters.getGuildById(guildId);\n if (userDiscrim.matcher(s).find()) {\n if (guild == null) {\n return Getters.getUserCache().stream()\n .filter(user -> (user.getName() + \"#\" + user.getDiscriminator()).equalsIgnoreCase(s))\n .findFirst().orElse(null);\n } else {\n try {\n return guild.getMembers().stream()\n .map(Member::getUser)\n .filter(user -> (user.getName() + \"#\" + user.getDiscriminator()).equalsIgnoreCase(s))\n .findFirst().orElse(null);\n } catch (NullPointerException ignored) {\n }\n }\n } else {\n User tmp;\n if (guild == null) {\n tmp = Getters.getUserCache().stream().filter(user -> user.getName().equalsIgnoreCase(s))\n .findFirst().orElse(null);\n } else {\n tmp = guild.getMembers().stream()\n .map(Member::getUser)\n .filter(user -> user.getName().equalsIgnoreCase(s))\n .findFirst().orElse(null);\n }\n if (tmp != null) return tmp;\n try {\n long l = Long.parseLong(s.replaceAll(\"[^0-9]\", \"\"));\n if (guild == null) {\n tmp = Getters.getUserById(l);\n } else {\n Member temMember = guild.getMemberById(l);\n if (temMember != null) {\n tmp = temMember.getUser();\n }\n }\n if (tmp != null) {\n return tmp;\n } else if (forceGet) {\n return Getters.retrieveUserById(l);\n }\n } catch (NumberFormatException | NullPointerException ignored) {\n }\n }\n return null;\n }\n\n /**\n * Gets a {@link TextChannel} from a string. Not case sensitive.\n * The string can eater be the channel name, it's id, or it being mentioned.\n *\n * @param arg The string to get the channel from.\n * @return null if the channel couldn't be found otherwise a {@link TextChannel}.\n */\n public static TextChannel getChannel(String arg) {\n return getChannel(arg, null);\n }\n\n /**\n * Gets a {@link TextChannel} from a string. Not case sensitive.\n * The string can eater be the channel name, it's id, or it being mentioned.\n *\n * @param channelArg The string to get the channel from\n * @param wrapper The Guild wrapper for the {@link Guild} that you want to get the channel from\n * @return null if the channel couldn't be found otherwise a {@link TextChannel}\n */\n public static TextChannel getChannel(String channelArg, GuildWrapper wrapper) {\n try {\n long channelId = Long.parseLong(channelArg.replaceAll(\"[^0-9]\", \"\"));\n return wrapper != null ? wrapper.getGuild().getTextChannelById(channelId) : Getters.getChannelById(channelId);\n } catch (NumberFormatException e) {\n if (wrapper != null) {\n List<TextChannel> tcs = wrapper.getGuild().getTextChannelsByName(channelArg, true);\n if (!tcs.isEmpty()) {\n return tcs.get(0);\n }\n }\n return null;\n }\n }\n\n /**\n * Gets an {@link Emote} from an id.\n *\n * @param l the id as a long of the emote\n * @return null if the id is invalid or wasn't found, otherwise a {@link Emote}\n */\n public static Emote getEmoteById(long l) {\n return Getters.getGuildCache().stream().map(g -> g.getEmoteById(l))\n .filter(Objects::nonNull).findFirst().orElse(null);\n }\n\n /**\n * Gets weather or not the bot can change nick.\n * This checks for {@link Permission#NICKNAME_CHANGE}.\n * If we don't have the then it checks for {@link Permission#NICKNAME_MANAGE}.\n *\n * @param guildId The string guildid to check if we can change nick\n * @return If we change change nick\n */\n public static boolean canChangeNick(String guildId) {\n Guild guild = Getters.getGuildById(guildId);\n return guild != null &&\n (guild.getSelfMember().hasPermission(Permission.NICKNAME_CHANGE) ||\n guild.getSelfMember().hasPermission(Permission.NICKNAME_MANAGE));\n }\n\n /**\n * Joins the bot to a {@link TextChannel}.\n *\n * @param channel The chanel to send an error message to in case this fails.\n * @param member The member requesting the join. This is also how we determine what channel to join.\n */\n public static void joinChannel(TextChannel channel, Member member) {\n if (channel.getGuild().getSelfMember()\n .hasPermission(member.getVoiceState().getChannel(), Permission.VOICE_CONNECT) &&\n channel.getGuild().getSelfMember()\n .hasPermission(member.getVoiceState().getChannel(), Permission.VOICE_SPEAK)) {\n if (member.getVoiceState().getChannel().getUserLimit() > 0 && member.getVoiceState().getChannel()\n .getMembers().size()\n >= member.getVoiceState().getChannel().getUserLimit() && !member.getGuild().getSelfMember()\n .hasPermission(member.getVoiceState().getChannel(), Permission.MANAGE_CHANNEL)) {\n MessageUtils.sendErrorMessage(\"We can't join :(\\n\\nThe channel user limit has been reached and we don't have the 'Manage Channel' permission to \" +\n \"bypass it!\", channel);\n return;\n }\n PlayerManager musicManager = FlareBot.instance().getMusicManager();\n channel.getGuild().getAudioManager().openAudioConnection(member.getVoiceState().getChannel());\n musicManager.getPlayer(channel.getGuild().getId()).play();\n\n if (musicManager.getPlayer(channel.getGuild().getId()).getPaused()) {\n MessageUtils.sendWarningMessage(\"The music is currently paused do `{%}resume`\", channel);\n }\n } else {\n MessageUtils.sendErrorMessage(\"I do not have permission to \" + (!channel.getGuild().getSelfMember()\n .hasPermission(member.getVoiceState()\n .getChannel(), Permission.VOICE_CONNECT) ?\n \"connect\" : \"speak\") + \" in your voice channel!\", channel);\n }\n }\n}", "public class VariableUtils {\n\n private static final Pattern random = Pattern.compile(\"\\\\{random(:(-?\\\\d+)(?:,(-?\\\\d+))?)?}\");\n private static final Pattern arguments = Pattern.compile(\"\\\\{\\\\$([1-9])+(?:,(.+))?}\");\n\n public static String parseVariables(@Nonnull String message) {\n return parseVariables(message, null, null, null, null);\n }\n\n public static String parseVariables(@Nonnull String message,\n @Nullable GuildWrapper wrapper) {\n return parseVariables(message, wrapper, null, null, null);\n }\n\n public static String parseVariables(@Nonnull String message,\n @Nullable GuildWrapper wrapper,\n @Nullable TextChannel channel) {\n return parseVariables(message, wrapper, channel, null, null);\n }\n\n public static String parseVariables(@Nonnull String message,\n @Nullable GuildWrapper wrapper,\n @Nullable TextChannel channel,\n @Nullable User user) {\n return parseVariables(message, wrapper, channel, user, null);\n }\n\n /**\n * This method is used to parse variables in a message, this means that we can allow users to pass things into\n * their command messages, things like usernames, mentions and channel names to name a few.\n *\n * Variable list:\n * <h2>User Variables</h2>\n * `{user}` - User's name.\n * `{username}` - User's name.\n * `{nickname}` - User's nickname for a guild or their username if the guild is not passed or they're not a member.\n * `{tag}` - User's name and discrim in tag format - Username#discrim.\n * `{mention}` - User mention.\n * `{user_id}` - User's ID.\n *\n * <hr />\n *\n * <h2>Guild Variables</h2>\n * `{guild}` - Guild name.\n * `{region}` - Guild region (Pretty name - Amsterdam, Amsterdam (VIP)).\n * `{members}` - Total guild members.\n * `{owner}` - Guild owner's name.\n * `{owner_id}` - Guild owner's ID.\n * `{owner_mention}` - Guild owner mention.\n *\n * <hr />\n *\n * <h2>Channel Variables</h2>\n * `{channel}` - Channel name.\n * `{channel_mention}` - Channel mention.\n * `{topic}` - Channel topic.\n * `{category}` - Category name or 'no category'.\n *\n * <hr />\n *\n * <h2>Utility Variables</h2>\n * `{random}` - Random value from 1-10.\n * `{random:y}` - Random value from 1 to Y.\n * `{random:x,y}` - Random value from X to Y.\n *\n * @return The parsed message\n */\n public static String parseVariables(@Nonnull String message,\n @Nullable GuildWrapper wrapper,\n @Nullable TextChannel channel,\n @Nullable User user,\n @Nullable String[] args) {\n @Nullable\n Guild guild = null;\n @Nullable\n Member member = null;\n if (wrapper != null) {\n guild = wrapper.getGuild();\n if (user != null)\n member = guild.getMember(user);\n }\n\n String parsed = message;\n // User variables\n if (user != null) {\n parsed = parsed\n .replace(\"{user}\", user.getName())\n .replace(\"{username}\", user.getName())\n .replace(\"{nickname}\", member == null ? user.getName() : member.getEffectiveName())\n .replace(\"{tag}\", user.getName() + \"#\" + user.getDiscriminator())\n .replace(\"{mention}\", user.getAsMention())\n .replace(\"{user_id}\", user.getId());\n }\n // Guild variables\n if (guild != null) {\n parsed = parsed\n .replace(\"{guild}\", guild.getName())\n .replace(\"{region}\", guild.getRegion().getName())\n .replace(\"{members}\", String.valueOf(guild.getMemberCache().size()))\n .replace(\"{owner}\", guild.getOwner().getEffectiveName())\n .replace(\"{owner_id}\", guild.getOwner().getUser().getId())\n .replace(\"{owner_mention}\", guild.getOwner().getUser().getAsMention());\n }\n // Channel variables\n if (channel != null) {\n parsed = parsed\n .replace(\"{channel}\", channel.getName())\n .replace(\"{channel_mention}\", channel.getAsMention())\n .replace(\"{topic}\", channel.getTopic() == null ? \"No Topic\" : channel.getTopic())\n .replace(\"{category}\", (channel.getParent() != null ? channel.getParent().getName() : \"no category\"));\n }\n\n // Utility variables\n Matcher matcher = random.matcher(parsed);\n if (matcher.find()) {\n int min = 1;\n int max = 100;\n if (matcher.groupCount() >= 2) {\n min = (matcher.group(2) != null ? GeneralUtils.getInt(matcher.group(2), min) : min);\n max = (matcher.group(3) != null ? GeneralUtils.getInt(matcher.group(3), max) : max);\n }\n parsed = matcher.replaceAll(String.valueOf(RandomUtils.getInt(min, max)));\n }\n\n String[] variableArgs = args;\n if (args == null || args.length == 0)\n variableArgs = new String[]{};\n\n matcher = arguments.matcher(parsed);\n while (matcher.find()) {\n int argIndex = GeneralUtils.getPositiveInt(matcher.group(1), 0);\n String arg = matcher.groupCount() == 2 && matcher.group(2) != null ? matcher.group(2) : \"William\";\n\n if (variableArgs.length >= argIndex)\n arg = variableArgs[argIndex-1];\n parsed = matcher.replaceAll(arg);\n }\n return parsed;\n }\n}" ]
import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.audit.ActionType; import net.dv8tion.jda.core.audit.AuditLogChange; import net.dv8tion.jda.core.audit.AuditLogEntry; import net.dv8tion.jda.core.entities.Channel; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.MessageEmbed; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.events.channel.text.GenericTextChannelEvent; import net.dv8tion.jda.core.events.channel.text.TextChannelCreateEvent; import net.dv8tion.jda.core.events.channel.text.TextChannelDeleteEvent; import net.dv8tion.jda.core.events.channel.voice.GenericVoiceChannelEvent; import net.dv8tion.jda.core.events.channel.voice.VoiceChannelCreateEvent; import net.dv8tion.jda.core.events.channel.voice.VoiceChannelDeleteEvent; import net.dv8tion.jda.core.events.guild.GenericGuildEvent; import net.dv8tion.jda.core.events.guild.GuildBanEvent; import net.dv8tion.jda.core.events.guild.member.*; import net.dv8tion.jda.core.events.guild.update.GenericGuildUpdateEvent; import net.dv8tion.jda.core.events.guild.update.GuildUpdateExplicitContentLevelEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceJoinEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent; import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent; import net.dv8tion.jda.core.events.message.GenericMessageEvent; import net.dv8tion.jda.core.events.message.MessageDeleteEvent; import net.dv8tion.jda.core.events.message.MessageUpdateEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.events.role.GenericRoleEvent; import net.dv8tion.jda.core.events.role.RoleCreateEvent; import net.dv8tion.jda.core.events.role.RoleDeleteEvent; import net.dv8tion.jda.core.events.role.update.GenericRoleUpdateEvent; import net.dv8tion.jda.core.events.role.update.RoleUpdatePositionEvent; import net.dv8tion.jda.core.hooks.EventListener; import stream.flarebot.flarebot.database.RedisController; import stream.flarebot.flarebot.database.RedisMessage; import stream.flarebot.flarebot.mod.modlog.ModlogEvent; import stream.flarebot.flarebot.mod.modlog.ModlogHandler; import stream.flarebot.flarebot.objects.GuildWrapper; import stream.flarebot.flarebot.util.MessageUtils; import stream.flarebot.flarebot.util.general.FormatUtils; import stream.flarebot.flarebot.util.general.GeneralUtils; import stream.flarebot.flarebot.util.general.GuildUtils; import stream.flarebot.flarebot.util.general.VariableUtils; import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull;
package stream.flarebot.flarebot; public class ModlogEvents implements EventListener { private long roleResponseNumber = 0; private long guildResponseNumber = 0; @Override public void onEvent(Event event) { if (!(event instanceof GenericGuildEvent) && !(event instanceof GenericRoleEvent) && !(event instanceof GenericTextChannelEvent) && !(event instanceof GenericVoiceChannelEvent) && !(event instanceof GenericMessageEvent)) return; Guild g = null; if (event instanceof GenericGuildEvent && ((GenericGuildEvent) event).getGuild() != null) g = ((GenericGuildEvent) event).getGuild(); else if (event instanceof GenericRoleEvent && ((GenericRoleEvent) event).getGuild() != null) g = ((GenericRoleEvent) event).getGuild(); else if (event instanceof GenericTextChannelEvent && ((GenericTextChannelEvent) event).getGuild() != null) g = ((GenericTextChannelEvent) event).getGuild(); else if (event instanceof GenericVoiceChannelEvent && ((GenericVoiceChannelEvent) event).getGuild() != null) g = ((GenericVoiceChannelEvent) event).getGuild(); else if (event instanceof GenericMessageEvent && ((GenericMessageEvent) event).getGuild() != null) g = ((GenericMessageEvent) event).getGuild(); if (g == null) return; GuildWrapper guildWrapper = FlareBotManager.instance().getGuild(g.getId()); if (guildWrapper == null) return; // GUILD if (event instanceof GuildBanEvent) onGuildBan((GuildBanEvent) event, guildWrapper); else if (event instanceof GuildMemberJoinEvent) onGuildMemberJoin((GuildMemberJoinEvent) event, guildWrapper); else if (event instanceof GuildMemberLeaveEvent) onGuildMemberLeave((GuildMemberLeaveEvent) event, guildWrapper); else if (event instanceof GuildVoiceJoinEvent) onGuildVoiceJoin((GuildVoiceJoinEvent) event, guildWrapper); else if (event instanceof GuildVoiceLeaveEvent) onGuildVoiceLeave((GuildVoiceLeaveEvent) event, guildWrapper); // ROLES else if (event instanceof RoleCreateEvent) onRoleCreate((RoleCreateEvent) event, guildWrapper); else if (event instanceof RoleDeleteEvent) onRoleDelete((RoleDeleteEvent) event, guildWrapper); else if (event instanceof GenericRoleUpdateEvent) onGenericRoleUpdate((GenericRoleUpdateEvent) event, guildWrapper); else if (event instanceof GuildMemberRoleAddEvent) onGuildMemberRoleAdd((GuildMemberRoleAddEvent) event, guildWrapper); else if (event instanceof GuildMemberRoleRemoveEvent) onGuildMemberRoleRemove((GuildMemberRoleRemoveEvent) event, guildWrapper); // CHANNEL else if (event instanceof TextChannelCreateEvent) onTextChannelCreate((TextChannelCreateEvent) event, guildWrapper); else if (event instanceof VoiceChannelCreateEvent) onVoiceChannelCreate((VoiceChannelCreateEvent) event, guildWrapper); else if (event instanceof TextChannelDeleteEvent) onTextChannelDelete((TextChannelDeleteEvent) event, guildWrapper); else if (event instanceof VoiceChannelDeleteEvent) onVoiceChannelDelete((VoiceChannelDeleteEvent) event, guildWrapper); // MESSAGES /*else if (event instanceof GuildMessageReceivedEvent) onGuildMessageReceived((GuildMessageReceivedEvent) event, guildWrapper);*/ else if (event instanceof MessageUpdateEvent) onMessageUpdate((MessageUpdateEvent) event, guildWrapper); else if (event instanceof MessageDeleteEvent) onMessageDelete((MessageDeleteEvent) event, guildWrapper); // GUILD else if (event instanceof GuildUpdateExplicitContentLevelEvent) onGuildUpdateExplicitContentLevel((GuildUpdateExplicitContentLevelEvent) event, guildWrapper); else if (event instanceof GuildMemberNickChangeEvent) onGuildMemberNickChange((GuildMemberNickChangeEvent) event, guildWrapper); else if (event instanceof GenericGuildUpdateEvent) onGenericGuildUpdate((GenericGuildUpdateEvent) event, guildWrapper); else if (event instanceof GuildVoiceMoveEvent) onGuildVoiceMove((GuildVoiceMoveEvent) event, guildWrapper); } private void onGuildBan(GuildBanEvent event, @Nonnull GuildWrapper wrapper) { if (cannotHandle(wrapper, ModlogEvent.USER_BANNED)) return; event.getGuild().getAuditLogs().limit(1).type(ActionType.BAN).queue(auditLogEntries -> { AuditLogEntry entry = auditLogEntries.get(0); // We don't want dupes. if (entry.getUser().getIdLong() == FlareBot.instance().getClient().getSelfUser().getIdLong()) return; boolean validEntry = entry.getTargetId().equals(event.getUser().getId());
ModlogHandler.getInstance().postToModlog(wrapper, ModlogEvent.USER_BANNED, event.getUser(),
3
comodoro/FractalZoo
app/src/main/java/com/draabek/fractal/canvas/FractalCpuView.java
[ "public interface FractalViewWrapper {\n void saveBitmap();\n void setVisibility(int visibility);\n boolean isRendering();\n void setRenderListener(RenderListener renderListener);\n void clear();\n}", "public interface RenderListener {\n void onRenderRequested();\n void onRenderComplete(long millis);\n}", "public class SaveBitmapActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{\n\n private static final String LOG_KEY = SaveBitmapActivity.class.getName();\n private static final int REQUEST_WRITE = 1;\n private static final int REQUEST_WALLPAPER = 2;\n\n // UI references.\n private RadioGroup radioGroup;\n EditText filenameEdit;\n private File bitmapFile;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_save_bitmap);\n radioGroup = findViewById(R.id.save_bitmap_radio_group);\n filenameEdit = findViewById(R.id.bitmap_filename);\n Button button = findViewById(R.id.save_bitmap_ok_button);\n bitmapFile = new File(this.getIntent().getStringExtra(getString(R.string.intent_extra_bitmap_file)));\n File suggestedPath = getFile();\n filenameEdit.getText().append(suggestedPath.getAbsolutePath());\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (radioGroup.getCheckedRadioButtonId() == R.id.bitmap_filename_radio) {\n if (handlePermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,\n getString(R.string.save_bitmap_storage_write_rationale), REQUEST_WRITE)) {\n saveToFile();\n }\n } else if (radioGroup.getCheckedRadioButtonId() == R.id.bitmap_set_as_background_radio) {\n // handlePermissions(Manifest.permission.SET_WALLPAPER,\n // getString(R.string.save_bitmap_set_wallpaper_rationale), REQUEST_WALLPAPER);\n setAsWallpaper();\n } else {\n Log.e(this.getClass().getName(), \"Unknown radio button in SaveBitmapActivity\");\n }\n }\n });\n }\n\n private void saveToFile() {\n String filename = filenameEdit.getText().toString();\n String path = filename.substring(0, filename.lastIndexOf(\"/\")-1);\n File dir = new File(path);\n if (!storageAvailable()) {\n Log.e(LOG_KEY, \"External storage not available\");\n return;\n }\n if ((!dir.exists()) && (!dir.mkdirs())) {\n Log.e(LOG_KEY, \"Directory specified does not exist and could not be created\");\n return;\n }\n File f = new File(filename);\n saveBitmap(bitmapFile, f);\n Toast.makeText(SaveBitmapActivity.this, getString(R.string.save_bitmap_success_toast)\n + f.getAbsolutePath(),\n Toast.LENGTH_LONG).show();\n finish();\n }\n\n private void setAsWallpaper() {\n WallpaperManager myWallpaperManager = WallpaperManager.getInstance(SaveBitmapActivity.this);\n try {\n myWallpaperManager.setStream(new FileInputStream(bitmapFile));\n } catch (IOException e) {\n // Just be ugly in the logcat\n e.printStackTrace();\n finish();\n }\n finish();\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n if (requestCode == REQUEST_WRITE) {\n if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n saveToFile();\n } else {\n Toast.makeText(SaveBitmapActivity.this, getString(R.string.save_bitmap_storage_write_rationale),\n Toast.LENGTH_SHORT).show();\n }\n } else if (requestCode == REQUEST_WALLPAPER) {\n if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n setAsWallpaper();\n } else {\n Toast.makeText(SaveBitmapActivity.this, getString(R.string.save_bitmap_set_wallpaper_rationale),\n Toast.LENGTH_SHORT).show();\n }\n }\n finish();\n }\n\n private boolean handlePermissions(final String permission, final String rationale, final int code) {\n if (ContextCompat.checkSelfPermission(SaveBitmapActivity.this, permission)\n != PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(SaveBitmapActivity.this,permission)) {\n //Just display a Toast\n Toast.makeText(SaveBitmapActivity.this, rationale, Toast.LENGTH_SHORT).show();\n final Handler handler = new Handler();\n handler.postDelayed(() -> ActivityCompat.requestPermissions(SaveBitmapActivity.this,\n new String[]{permission}, code), Toast.LENGTH_SHORT);\n } else {\n // No explanation needed, we can request the permission.\n ActivityCompat.requestPermissions(SaveBitmapActivity.this,\n new String[]{permission}, code);\n }\n return false;\n }\n return true;\n }\n\n private void saveBitmap(File bitmapTempFile, File path) {\n FileChannel sourceChannel = null;\n FileChannel destChannel = null;\n try {\n sourceChannel = new FileInputStream(bitmapTempFile).getChannel();\n destChannel = new FileOutputStream(path).getChannel();\n destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n } catch (IOException e) {\n e.printStackTrace();\n } finally{\n try {\n if (sourceChannel != null) {\n sourceChannel.close();\n }\n if (destChannel != null) {\n destChannel.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public boolean storageAvailable() {\n String state = Environment.getExternalStorageState();\n // We can read and write the media\n return Environment.MEDIA_MOUNTED.equals(state);\n }\n\n\n private File getFile() {\n String fileName = FractalRegistry.getInstance().getCurrent().toString() + System.currentTimeMillis() + \".jpg\";\n return new File(getExternalStoragePublicDirectory(DIRECTORY_PICTURES).getAbsolutePath(), fileName);\n }\n\n}", "public class Utils {\n public static final String FRACTALS_PREFERENCE\t= \"FRACTALS_PREFERENCE\";\n public static final String PREFS_CURRENT_FRACTAL_KEY = \"prefs_current_fractal_key\";\n public static final String PREFS_CURRENT_FRACTAL_PATH = \"prefs_current_fractal_path\";\n public static final boolean DEBUG = BuildConfig.DEBUG;\n\n public static Bitmap getBitmapFromAsset(AssetManager mgr, String path) {\n InputStream is = null;\n Bitmap bitmap;\n try {\n is = mgr.open(path);\n bitmap = BitmapFactory.decodeStream(is);\n } catch (final IOException e) {\n bitmap = null;\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException ignored) {\n }\n }\n }\n return bitmap;\n }\n}", "public final class FractalRegistry {\n\tprivate static final String LOG_KEY = FractalRegistry.class.getName();\n\tprivate static FractalRegistry instance = null;\n\tprivate Map<String, Fractal> fractals;\n\tprivate SimpleTree<String> hierarchy;\n\tprivate Fractal currentFractal = null;\n\n\tprivate FractalRegistry() {\n\t fractals = new LinkedHashMap<>();\n\t hierarchy = new SimpleTree<>(\"All fractals\");\n\t}\n\n\tprivate boolean initialized = false;\n\n\tpublic static FractalRegistry getInstance() {\n\t\tif (instance == null) { //throw new IllegalStateException(\"Fractal registry not initialized\");\n instance = new FractalRegistry();\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic Map<String, Fractal> getFractals() {\n\t\treturn fractals;\n\t}\n\n private Fractal fractalFromJsonObject(JsonObject jsonObject) {\n String name = jsonObject.get(\"name\").getAsString();\n String clazz = jsonObject.get(\"class\").getAsString();\n String shaders = jsonObject.get(\"shaders\") != null ? jsonObject.get(\"shaders\").getAsString() : null;\n String settingsString = jsonObject.get(\"parameters\") != null ?\n jsonObject.get(\"parameters\").toString() : null;\n String thumbPath = jsonObject.get(\"thumbnail\") != null ?\n jsonObject.get(\"thumbnail\").getAsString() : null;\n String paletteString = jsonObject.get(\"palette\") != null ?\n jsonObject.get(\"palette\").getAsString() : null;\n Context ctx = FractalZooApplication.getContext();\n String[] loadedShaders = loadShaders(ctx, shaders);\n Class cls;\n try {\n cls = forName(clazz);\n //this is frontal lobotomy\n Fractal fractal = (Fractal) cls.newInstance();\n fractal.setName(name);\n if (thumbPath != null) {\n fractal.setThumbPath(\"thumbs/\" + thumbPath);\n }\n if (fractal instanceof GLSLFractal) {\n if (loadedShaders == null) {\n if (Utils.DEBUG) {\n throw new RuntimeException(\"No shaders loaded for \" + fractal);\n } else {\n Log.e(LOG_KEY, \"No shaders loaded for \" + fractal);\n return null;\n }\n }\n ((GLSLFractal) fractal).setShaders(loadedShaders);\n }\n if (settingsString != null) {\n Map<String, Float> retMap = new Gson().fromJson(\n settingsString, new TypeToken<HashMap<String, Float>>() {\n }.getType()\n );\n fractal.updateSettings(retMap);\n }\n if (paletteString != null) {\n ColorPalette colorPalette = (ColorPalette) Class.forName(paletteString).newInstance();\n fractal.setColorPalette(colorPalette);\n }\n return fractal;\n } catch (ClassNotFoundException e) {\n Log.w(LOG_KEY, \"Cannot find fractal class \" + clazz);\n } catch (IllegalAccessException e) {\n Log.w(LOG_KEY, \"Cannot access fractal class \" + clazz);\n } catch (InstantiationException e) {\n if (Utils.DEBUG) {\n throw new RuntimeException(e);\n } else {\n Log.w(LOG_KEY, \"Cannot instantiate fractal class \" + clazz);\n }\n }\n return null;\n }\n\n\tprivate String[] loadShaders(Context ctx, String shaderPath) {\n\t\tif (shaderPath == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (!(shaderPath.contains(\"/\"))) shaderPath = \"shaders/\" + shaderPath;\n\t\ttry {\n\t\t\tBufferedReader br = new BufferedReader(new InputStreamReader(\n\t\t\t\t\tctx.getAssets().open(shaderPath + \"_fragment.glsl\")\n\t\t\t));\n\t\t\tStringBuilder fragmentShader = new StringBuilder();\n\t\t\tString line;\n\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\tfragmentShader.append(line).append(\"\\n\");\n\t\t\t}\n\t\t\tInputStream vertexIS;\n\t\t\ttry {\n\t\t\t\tvertexIS = ctx.getAssets().open(shaderPath + \"_vertex.glsl\");\n\t\t\t} catch(IOException e) {\n\t\t\t\tLog.d(LOG_KEY, \"Using default vertex shader for \" + shaderPath);\n\t\t\t\tvertexIS = ctx.getAssets().open(\"shaders/default_vertex.glsl\");\n\t\t\t}\n\t\t\tif (vertexIS == null) {//fallback to simplest vertex shader\n\t\t\t\tLog.e(LOG_KEY, \"Not even default vertex shader found for fractal \" + shaderPath);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tbr = new BufferedReader(new InputStreamReader(vertexIS));\n\t\t\tStringBuilder vertexShader = new StringBuilder();\n\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\tvertexShader.append(line).append(\"\\n\");\n\t\t\t}\n\t\t\treturn new String[] {vertexShader.toString(), fragmentShader.toString()};\n\t\t} catch(IOException e) {\n\t\t\tLog.w(LOG_KEY, \"IOException loading fractal shaders for\" + shaderPath);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate void processJsonElement(JsonElement jsonElement) {\n JsonObject jsonObject = jsonElement.getAsJsonObject();\n String pathInList = jsonObject.get(\"path\").getAsString();\n jsonObject.remove(\"path\");\n String[] s = pathInList.split(\"\\\\|\");\n Fractal fractal = fractalFromJsonObject(jsonObject);\n if (fractal != null) {\n fractals.put(fractal.getName(), fractal);\n hierarchy.putPath(s, fractal.getName());\n } else {\n Log.e(LOG_KEY, String.format(\"Cannot load fractal %s\",\n jsonObject.get(\"name\").getAsString()));\n }\n }\n\n\tpublic void init(String[] fractalList) {\n\t\tif (initialized) return;\n\t\tfor (String fractal : fractalList) {\n JsonElement jsonElement = new Gson().fromJson(fractal, JsonElement.class);\n processJsonElement(jsonElement);\n }\n\t\tinitialized = true;\n\t}\n\n\tpublic Fractal get(String name) {\n\t\t/*Fractal f = fractals.get(name);\n\t\tif (f != null) return f;\n\t\tif (Utils.DEBUG) {\n throw new RuntimeException(\"Fractal not found in registry: \" + name);\n } else {\n Log.w(LOG_KEY, \"Fractal not found in registry: \" + name);\n return get(\"Mandelbrot\");\n }*/\n\t\treturn fractals.get(name);\n\t}\n\n\tpublic List<String> getOnLevel(Deque<String> level) {\n return hierarchy.getChildren(level);\n }\n\n\tpublic Fractal getCurrent() {\n\t\treturn currentFractal;\n\t}\n\n\tpublic void setCurrent(Fractal currentFractal) {\n\t\tthis.currentFractal = currentFractal;\n\t}\n}" ]
import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.RectF; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Toast; import com.draabek.fractal.fractal.FractalViewWrapper; import com.draabek.fractal.R; import com.draabek.fractal.fractal.RenderListener; import com.draabek.fractal.activity.SaveBitmapActivity; import com.draabek.fractal.util.Utils; import com.draabek.fractal.fractal.FractalRegistry; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;
package com.draabek.fractal.canvas; @SuppressWarnings("SynchronizeOnNonFinalField") public class FractalCpuView extends SurfaceView implements SurfaceHolder.Callback, FractalViewWrapper //,GestureDetector.OnDoubleTapListener, GestureDetector.OnGestureListener { private static final String LOG_KEY = FractalCpuView.class.getName(); private Bitmap fractalBitmap; private CpuFractal fractal; private RectF position; private RectF oldPosition; private Paint paint; private Canvas bufferCanvas = null; private SurfaceHolder holder; private SharedPreferences prefs; private boolean rendering; private RenderListener renderListener; public FractalCpuView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public FractalCpuView(Context context) { super(context); init(context); } private void init(Context context) { holder = getHolder(); holder.addCallback(this); this.setOnTouchListener(new MotionTracker()); paint = new Paint(); prefs = PreferenceManager.getDefaultSharedPreferences(context); } @Override protected void onDraw(Canvas canvas) { rendering = true; if (renderListener != null) { this.renderListener.onRenderRequested(); } long start = System.currentTimeMillis(); Log.d(LOG_KEY,"onDraw"); this.holder = getHolder(); synchronized (this.holder) { if ((fractalBitmap == null) || (fractalBitmap.getHeight() != canvas.getHeight()) || (fractalBitmap.getWidth() != canvas.getWidth()) || (bufferCanvas == null)) { Log.v(LOG_KEY, "Reallocate buffer"); fractalBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); bufferCanvas = new Canvas(fractalBitmap); } if (fractal instanceof BitmapDrawFractal) { Log.v(LOG_KEY, "Start drawing to buffer"); fractalBitmap = ((BitmapDrawFractal)fractal).redrawBitmap(fractalBitmap, position); } else if (fractal instanceof CanvasFractal) { Log.v(LOG_KEY, "Draw to canvas"); ((CanvasFractal)fractal).draw(bufferCanvas); } else { throw new RuntimeException("Wrong fractal type for " + this.getClass().getName()); } canvas.drawBitmap(fractalBitmap, 0, 0, paint); } Log.d(LOG_KEY, "finished onDraw"); rendering = false; if (renderListener != null) { renderListener.onRenderComplete(System.currentTimeMillis() - start); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { this.holder = holder; Log.d(LOG_KEY,"surface changed"); fractal = (CpuFractal) FractalRegistry.getInstance().getCurrent(); invalidate(); } @Override public void surfaceCreated(SurfaceHolder holder) { setWillNotDraw(false); Log.d(LOG_KEY,"surface created"); fractalBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); position = new RectF(1, -2, -1, 1); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d(LOG_KEY, "surface destroyed"); bufferCanvas = null; fractalBitmap = null; //consider apply instead of commit
prefs.edit().putString(Utils.PREFS_CURRENT_FRACTAL_KEY, FractalRegistry.getInstance().getCurrent().getName()).apply();
3
schnatterer/nusic
nusic-core-android/src/main/java/info/schnatterer/nusic/core/impl/RemoteMusicDatabaseServiceMusicBrainz.java
[ "public interface RemoteMusicDatabaseService {\n\n /**\n * Finds releases by artist.\n * \n * @param artist\n * the artist to query releases for.\n * @param fromDate\n * the lower boundary of the time range in which release were\n * published\n * @param endDate\n * the upper boundary of the time range in which release were\n * published\n * @return an artists object that contains all the releases that were\n * published in the specified time range\n * @throws ServiceException\n */\n Artist findReleases(Artist artist, Date fromDate, Date endDate)\n throws ServiceException;\n}", "public class ServiceException extends Exception {\n static final long serialVersionUID = 1L;\n\n /**\n * Constructs a new exception with the specified detail message. The cause\n * is not initialized, and may subsequently be initialized by a call to\n * {@link #initCause}.\n *\n * @param message\n * the detail message. The detail message is saved for later\n * retrieval by the {@link #getMessage()} method.\n */\n public ServiceException(String message) {\n super(message);\n }\n\n /**\n * Constructs a new exception with the specified detail message and cause.\n * <p>\n * Note that the detail message associated with {@code cause} is <i>not</i>\n * automatically incorporated in this exception's detail message.\n *\n * @param message\n * the detail message (which is saved for later retrieval by the\n * {@link #getMessage()} method).\n * @param cause\n * the cause (which is saved for later retrieval by the\n * {@link #getCause()} method). (A <tt>null</tt> value is\n * permitted, and indicates that the cause is nonexistent or\n * unknown.)\n * @since 1.4\n */\n public ServiceException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a new exception with the specified cause and a detail message\n * of <tt>(cause==null ? null : cause.toString())</tt> (which typically\n * contains the class and detail message of <tt>cause</tt>). This\n * constructor is useful for exceptions that are little more than wrappers\n * for other throwables (for example,\n * {@link java.security.PrivilegedActionException}).\n *\n * @param cause\n * the cause (which is saved for later retrieval by the\n * {@link #getCause()} method). (A <tt>null</tt> value is\n * permitted, and indicates that the cause is nonexistent or\n * unknown.)\n * @since 1.4\n */\n public ServiceException(Throwable cause) {\n super(cause);\n }\n}", "public enum CoreMessageKey {\n ERROR_WRITING_TO_DB(\"ServiceException_errorWritingToDb\"),\n\n ERROR_READING_FROM_DB(\"ServiceException_errorReadingFromDb\"),\n\n ERROR_QUERYING_MUSIC_BRAINZ(\"ServiceException_errorQueryingMusicBrainz\"),\n\n ERROR_FINDING_RELEASE_ARTIST(\"ServiceException_errorFindingReleasesArtist\"),\n\n ERROR_LOADING_ARTISTS(\"ServiceException_errorLoadingArtists\");\n\n public static final String CORE_BUNDLE_NAME = \"CoreBundle\";\n /**\n * Fully qualified core bundle name.\n */\n public static final String CORE_BUNDLE_NAME_FQ = CoreMessageKey.class\n .getPackage().getName() + \".\" + CORE_BUNDLE_NAME;\n private String messageKey;\n\n private CoreMessageKey(String msgKey) {\n this.messageKey = msgKey;\n }\n\n public String get() {\n return messageKey;\n }\n\n /**\n * Finds the named {@code ResourceBundle} for the specified {@code Locale}\n * and the caller {@code ClassLoader}.\n *\n * @param bundleName\n * the name of the {@code ResourceBundle}.\n * @param locale\n * the {@code Locale}.\n * @return the requested resource bundle.\n * @throws MissingResourceException\n * if the resource bundle cannot be found.\n */\n public static ResourceBundle getBundle(Locale loc)\n throws MissingResourceException {\n return ResourceBundle.getBundle(CORE_BUNDLE_NAME_FQ, loc);\n }\n\n /**\n * Finds the named resource bundle for the default {@code Locale} and the\n * caller's {@code ClassLoader}.\n *\n * @param bundleName\n * the name of the {@code ResourceBundle}.\n * @return the requested {@code ResourceBundle}.\n * @throws MissingResourceException\n * if the {@code ResourceBundle} cannot be found.\n */\n public static ResourceBundle getBundle() throws MissingResourceException {\n return ResourceBundle.getBundle(CORE_BUNDLE_NAME_FQ);\n }\n}", "public class DatabaseException extends Exception {\n private static final long serialVersionUID = 1L;\n\n /**\n * Constructs a new exception with <code>null</code> as its detail message.\n * The cause is not initialized, and may subsequently be initialized by a\n * call to {@link #initCause}.\n */\n public DatabaseException() {\n super();\n }\n\n /**\n * Constructs a new exception with the specified detail message. The cause\n * is not initialized, and may subsequently be initialized by a call to\n * {@link #initCause}.\n * \n * @param message\n * the detail message. The detail message is saved for later\n * retrieval by the {@link #getMessage()} method.\n */\n public DatabaseException(String message) {\n super(message);\n }\n\n /**\n * Constructs a new exception with the specified detail message and cause.\n * <p>\n * Note that the detail message associated with <code>cause</code> is\n * <i>not</i> automatically incorporated in this exception's detail message.\n * \n * @param message\n * the detail message (which is saved for later retrieval by the\n * {@link #getMessage()} method).\n * @param cause\n * the cause (which is saved for later retrieval by the\n * {@link #getCause()} method). (A <tt>null</tt> value is\n * permitted, and indicates that the cause is nonexistent or\n * unknown.)\n * @since 1.4\n */\n public DatabaseException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a new exception with the specified cause and a detail message\n * of <tt>(cause==null ? null : cause.toString())</tt> (which typically\n * contains the class and detail message of <tt>cause</tt>). This\n * constructor is useful for exceptions that are little more than wrappers\n * for other throwables (for example,\n * {@link java.security.PrivilegedActionDbException}).\n * \n * @param cause\n * the cause (which is saved for later retrieval by the\n * {@link #getCause()} method). (A <tt>null</tt> value is\n * permitted, and indicates that the cause is nonexistent or\n * unknown.)\n * @since 1.4\n */\n public DatabaseException(Throwable cause) {\n super(cause);\n }\n}", "public interface ArtworkDao {\n\n public enum ArtworkType {\n SMALL;\n }\n\n /**\n * Stores an artwork, if does not exist yet.\n * \n * @param release\n * @param type\n * @param artwork\n * @return <code>true</code> if the artwork was saved, <code>false</code> if\n * it wasn't saved because it existed before\n * \n * @throws DatabaseException\n * error writing data, etc.\n */\n public boolean save(Release release, ArtworkType type, InputStream artwork)\n throws DatabaseException;\n\n /**\n * Provides a stream to the artwork data.\n * \n * @param release\n * @param type\n * @return a stream to artwork data or <code>null</code> if there is none\n * @throws DatabaseException\n */\n public InputStream findStreamByRelease(Release release, ArtworkType type)\n throws DatabaseException;\n\n boolean exists(Release release, ArtworkType type) throws DatabaseException;\n\n /**\n * Provides an URI String to the artwork data, e.g.\n * <code>file:////my/directory/myfile.ext</code>\n * \n * @param release\n * @param type\n * @return an URI string to artwork data or <code>null</code> if there is\n * none\n * @throws DatabaseException\n */\n String findUriByRelease(Release release, ArtworkType type)\n throws DatabaseException;\n\n}", "public enum ArtworkType {\n SMALL;\n}", "public class Artist implements Entity {\n private static final String HTTP = \"http://\";\n private static final String HTTPS = \"https://\";\n private static final String MUSIC_BRAINZ_BASE_URI = \"musicbrainz.org/artist/\";\n private static final String MUSIC_BRAINZ_BASE_URI_HTTP = HTTP\n + MUSIC_BRAINZ_BASE_URI;\n private static final String MUSIC_BRAINZ_BASE_URI_HTTPS = HTTPS\n + MUSIC_BRAINZ_BASE_URI;\n\n private Long id;\n private Long androidAudioArtistId;\n private String musicBrainzId;\n /**\n * Artist name from android db\n */\n private String artistName;\n private List<Release> releases = new LinkedList<Release>();\n private Date dateCreated;\n private Boolean isHidden;\n\n public Artist() {\n }\n\n public Artist(Date dateCreated) {\n setDateCreated(dateCreated);\n }\n\n public List<Release> getReleases() {\n return releases;\n }\n\n public void setReleases(List<Release> releases) {\n this.releases = releases;\n }\n\n public String getArtistName() {\n return artistName;\n }\n\n public void setArtistName(String artistName) {\n this.artistName = artistName;\n }\n\n public Release getNewestRelease() {\n if (releases != null && releases.size() > 0) {\n return releases.get(0);\n }\n return null;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long l) {\n this.id = l;\n }\n\n public Date getDateCreated() {\n return dateCreated;\n }\n\n public void setDateCreated(Date dateCreated) {\n this.dateCreated = dateCreated;\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 Artist other = (Artist) obj;\n if (id != other.id)\n return false;\n return true;\n }\n\n public String getMusicBrainzId() {\n return musicBrainzId;\n }\n\n public void setMusicBrainzId(String musicBrainzId) {\n this.musicBrainzId = musicBrainzId;\n }\n\n public Long getAndroidAudioArtistId() {\n return androidAudioArtistId;\n }\n\n public void setAndroidAudioArtistId(Long androidAudioArtistId) {\n this.androidAudioArtistId = androidAudioArtistId;\n }\n\n public Boolean isHidden() {\n return isHidden;\n }\n\n public void setHidden(Boolean isHidden) {\n this.isHidden = isHidden;\n }\n\n public String getMusicBrainzUri() {\n return MUSIC_BRAINZ_BASE_URI_HTTP + getMusicBrainzId();\n }\n\n public String getMusicBrainzUriHttps() {\n return MUSIC_BRAINZ_BASE_URI_HTTPS + getMusicBrainzId();\n }\n\n @Override\n public void prePersist() {\n if (dateCreated == null)\n setDateCreated(new Date());\n\n }\n\n @Override\n public String toString() {\n return \"Artist [id=\" + id + \", androidAudioArtistId=\"\n + androidAudioArtistId + \", musicBrainzId=\" + musicBrainzId\n + \", artistName=\" + artistName + \", releases=\" + releases\n + \", dateCreated=\" + dateCreated + \", isHidden=\" + isHidden\n + \"]\";\n }\n}", "public class Release implements Entity {\n private static final String HTTP = \"http://\";\n private static final String HTTPS = \"https://\";\n private static final String MUSIC_BRAINZ_BASE_URI = \"musicbrainz.org/release-group/\";\n private static final String MUSIC_BRAINZ_BASE_URI_HTTP = HTTP\n + MUSIC_BRAINZ_BASE_URI;\n private static final String MUSIC_BRAINZ_BASE_URI_HTTPS = HTTPS\n + MUSIC_BRAINZ_BASE_URI;\n\n private Long id;\n /** MusicBrainz Id of the release group */\n private String musicBrainzId;\n /** ID of the cover art at Cover Art Archive. */\n private Long coverartArchiveId;\n\n private Artist artist;\n private String releaseName;\n private Date releaseDate;\n private Date dateCreated;\n // private ? releaseType;\n\n private Boolean isHidden;\n\n public Release() {\n }\n\n public Release(Date dateCreated) {\n setDateCreated(dateCreated);\n }\n\n public String getArtistName() {\n return artist.getArtistName();\n }\n\n public Artist getArtist() {\n return artist;\n }\n\n public void setArtist(Artist artist) {\n this.artist = artist;\n }\n\n public String getReleaseName() {\n return releaseName;\n }\n\n public void setReleaseName(String releaseName) {\n this.releaseName = releaseName;\n }\n\n public Date getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(Date releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((artist == null) ? 0 : artist.hashCode());\n result = prime * result\n + ((releaseName == null) ? 0 : releaseName.hashCode());\n result = prime * result\n + ((releaseDate == null) ? 0 : releaseDate.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 Release other = (Release) obj;\n if (artist == null) {\n if (other.artist != null)\n return false;\n } else if (!artist.equals(other.artist))\n return false;\n if (releaseName == null) {\n if (other.releaseName != null)\n return false;\n } else if (!releaseName.equals(other.releaseName))\n return false;\n if (releaseDate == null) {\n if (other.releaseDate != null)\n return false;\n } else if (!releaseDate.equals(other.releaseDate))\n return false;\n return true;\n }\n\n public Date getDateCreated() {\n return dateCreated;\n }\n\n public void setDateCreated(Date dateCreated) {\n this.dateCreated = dateCreated;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getMusicBrainzId() {\n return musicBrainzId;\n }\n\n public void setMusicBrainzId(String musicBrainzId) {\n this.musicBrainzId = musicBrainzId;\n }\n\n public Boolean isHidden() {\n return isHidden;\n }\n\n public void setHidden(Boolean isHidden) {\n this.isHidden = isHidden;\n }\n\n public String getMusicBrainzUri() {\n return MUSIC_BRAINZ_BASE_URI_HTTP + getMusicBrainzId();\n }\n\n public String getMusicBrainzUriHttps() {\n return MUSIC_BRAINZ_BASE_URI_HTTPS + getMusicBrainzId();\n }\n\n @Override\n public void prePersist() {\n if (dateCreated == null)\n setDateCreated(new Date());\n\n }\n\n @Override\n public String toString() {\n return \"Release [id=\" + id + \", musicBrainzId=\" + musicBrainzId\n + \", artist=\" + getArtistName() + \", releaseName=\"\n + releaseName + \", releaseDate=\" + releaseDate\n + \", dateCreated=\" + dateCreated + \", isHidden=\" + isHidden\n + \"]\";\n }\n\n public void setCoverartArchiveId(Long coverartArchiveId) {\n this.coverartArchiveId = coverartArchiveId;\n }\n\n public Long getCoverartArchiveId() {\n return coverartArchiveId;\n }\n\n}" ]
import fm.last.musicbrainz.coverart.CoverArt; import fm.last.musicbrainz.coverart.CoverArtArchiveClient; import fm.last.musicbrainz.coverart.CoverArtImage; import fm.last.musicbrainz.coverart.impl.DefaultCoverArtArchiveClient; import info.schnatterer.nusic.core.RemoteMusicDatabaseService; import info.schnatterer.nusic.core.ServiceException; import info.schnatterer.nusic.core.i18n.CoreMessageKey; import info.schnatterer.nusic.data.DatabaseException; import info.schnatterer.nusic.data.dao.ArtworkDao; import info.schnatterer.nusic.data.dao.ArtworkDao.ArtworkType; import info.schnatterer.nusic.data.model.Artist; import info.schnatterer.nusic.data.model.Release; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import javax.inject.Inject; import org.musicbrainz.MBWS2Exception; import org.musicbrainz.model.ArtistCreditWs2; import org.musicbrainz.model.NameCreditWs2; import org.musicbrainz.model.entity.ReleaseWs2; import org.musicbrainz.model.searchresult.ReleaseResultWs2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.RateLimiter; import com.google.inject.BindingAnnotation;
/** * Copyright (C) 2013 Johannes Schnatterer * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This file is part of nusic. * * nusic 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. * * nusic 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 nusic. If not, see <http://www.gnu.org/licenses/>. */ package info.schnatterer.nusic.core.impl; /** * {@link RemoteMusicDatabaseService} that queries information from MusicBrainz. * * @author schnatterer * */ public class RemoteMusicDatabaseServiceMusicBrainz implements RemoteMusicDatabaseService { private static final Logger LOG = LoggerFactory .getLogger(RemoteMusicDatabaseServiceMusicBrainz.class); /** * See http://musicbrainz.org/doc/Development/XML_Web_Service/Version_2# * Release_Type_and_Status */ private static final String SEARCH_BASE = "type:album"; private static final String SEARCH_DATE_BASE = " AND date:["; private static final String SEARCH_DATE_TO = " TO "; // 2019/07: "?" seems to no longer work, results in a huge number of results private static final String SEARCH_DATE_OPEN_END = "9999-12-31"; private static final String SEARCH_DATE_FINAL = "]"; private static final String SEARCH_ARTIST_1 = " AND artist:\""; private static final String SEARCH_ARTIST_2 = "\""; /** * MusicBrainz allows at max 22 requests in 20 seconds. However, we still * get 503s then. Try 1 request per second. */ private static final double PERMITS_PER_SECOND = 1.0; private final RateLimiter rateLimiter = RateLimiter .create(PERMITS_PER_SECOND); private CoverArtArchiveClient client = new DefaultCoverArtArchiveClient(); /** Application name used in user agent string of request. */ private String appName; /** Application version used in user agent string of request. */ private String appVersion; /** * Contact URL or author email used in user agent string of request. */ private String appContact; @Inject private ArtworkDao artworkDao; /** * Creates a service instance for finding releases. * * @param appName * application name used in user agent string of request * * @param appVersion * application version used in user agent string of request * * @param appContact * contact URL or author email used in user agent string of * request */ @Inject public RemoteMusicDatabaseServiceMusicBrainz( @ApplicationName String appName, @ApplicationVersion String appVersion, @ApplicationContact String appContact) { this.appName = appName; this.appVersion = appVersion; this.appContact = appContact; } private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); @Override public Artist findReleases(Artist artist, Date fromDate, Date endDate) throws ServiceException { if (artist == null || artist.getArtistName() == null) { return null; } String artistName = artist.getArtistName(); Map<String, Release> releases = new HashMap<String, Release>(); try { // List<ReleaseResultWs2> releaseResults = findReleases(); org.musicbrainz.controller.Release releaseSearch = createReleaseSearch( appName, appVersion, appContact); releaseSearch.search(appendDate(fromDate, endDate, new StringBuffer(SEARCH_BASE)).append(SEARCH_ARTIST_1) .append(artistName).append(SEARCH_ARTIST_2).toString()); // Limit request rate to avoid server bans rateLimiter.acquire(); processReleaseResults(artistName, artist, releases, releaseSearch.getFirstSearchResultPage()); while (releaseSearch.hasMore()) { // TODO check if internet connection still there? // Limit request rate to avoid server bans rateLimiter.acquire(); processReleaseResults(artistName, artist, releases, releaseSearch.getNextSearchResultPage()); } } catch (MBWS2Exception mBWS2Exception) { throw new AndroidServiceException(
CoreMessageKey.ERROR_QUERYING_MUSIC_BRAINZ, mBWS2Exception,
2
Skyost/SkyDocs
src/main/java/fr/skyost/skydocs/frame/ProjectsFrame.java
[ "public class Constants {\n\t\n\t/**\n\t * ==============\n\t * APP PROPERTIES\n\t * ==============\n\t */\n\t\n\t/**\n\t * App's name.\n\t */\n\t\n\tpublic static final String APP_NAME = \"SkyDocs\";\n\n\t/**\n\t * App's state.\n\t */\n\n\tpublic static final String APP_STATE = \"Beta\";\n\t\n\t/**\n\t * App's version.\n\t */\n\t\n\tpublic static final String APP_VERSION = \"v\" + BuildConfig.VERSION + \" \" + APP_STATE;\n\t\n\t/**\n\t * App's authors.\n\t */\n\t\n\tpublic static final String APP_AUTHORS = \"Skyost\";\n\t\n\t/**\n\t * App's website.\n\t */\n\t\n\tpublic static final String APP_WEBSITE = \"https://skydocs.skyost.eu\";\n\t\n\t/**\n\t * ========\n\t * COMMANDS\n\t * ========\n\t */\n\t\n\t/**\n\t * The create a new project command.\n\t */\n\t\n\tpublic static final String COMMAND_NEW = \"new\";\n\t\n\t/**\n\t * The new command syntax.\n\t */\n\t\n\tpublic static final String COMMAND_NEW_SYNTAX = COMMAND_NEW + \" -directory [directory] - Creates a new documentation in the specified directory.\";\n\t\n\t/**\n\t * The build a project command.\n\t */\n\t\n\tpublic static final String COMMAND_BUILD = \"build\";\n\t\n\t/**\n\t * The build command syntax.\n\t */\n\t\n\tpublic static final String COMMAND_BUILD_SYNTAX = COMMAND_BUILD + \" -directory [directory] - Builds the documentation located in the specified directory.\";\n\t\n\t/**\n\t * The serve a project command.\n\t */\n\t\n\tpublic static final String COMMAND_SERVE = \"serve\";\n\t\n\t/**\n\t * The serve command syntax.\n\t */\n\t\n\tpublic static final String COMMAND_SERVE_SYNTAX = COMMAND_SERVE + \" -directory [directory] -port [port] -manualRebuild [true|false] - Builds the documentation located in the specified directory and serve it on localhost with the specified port.\";\n\t\n\t/**\n\t * The update app command.\n\t */\n\t\n\tpublic static final String COMMAND_UPDATE = \"update\";\n\t\n\t/**\n\t * The update command syntax.\n\t */\n\t\n\tpublic static final String COMMAND_UPDATE_SYNTAX = COMMAND_UPDATE + \" - Checks for updates.\";\n\t\n\t/**\n\t * The help command.\n\t */\n\t\n\tpublic static final String COMMAND_HELP = \"help\";\n\t\n\t/**\n\t * The help command syntax.\n\t */\n\t\n\tpublic static final String COMMAND_HELP_SYNTAX = COMMAND_HELP + \" -command [command] - Shows the available command with their description.\";\n\t\n\t/**\n\t * The GUI command.\n\t */\n\t\n\tpublic static final String COMMAND_GUI = \"gui\";\n\t\n\t/**\n\t * The GUI command syntax.\n\t */\n\t\n\tpublic static final String COMMAND_GUI_SYNTAX = COMMAND_GUI + \" - Opens up a GUI.\";\n\t\n\t/**\n\t * ================\n\t * YAML HEADER KEYS\n\t * ================\n\t */\n\t\n\t/**\n\t * The title key.\n\t */\n\t\n\tpublic static final String KEY_HEADER_TITLE = \"title\";\n\t\n\t/**\n\t * The language key.\n\t */\n\t\n\tpublic static final String KEY_HEADER_LANGUAGE = \"language\";\n\t\n\t/**\n\t * The previous key.\n\t */\n\t\n\tpublic static final String KEY_HEADER_PREVIOUS = \"previous\";\n\t\n\t/**\n\t * The next key.\n\t */\n\t\n\tpublic static final String KEY_HEADER_NEXT = \"next\";\n\t\n\t/**\n\t * ==============\n\t * YAML MENU KEYS\n\t * ==============\n\t */\n\t\n\t/**\n\t * Title of the menu item key.\n\t */\n\t\n\tpublic static final String KEY_MENU_TITLE = \"title\";\n\t\n\t/**\n\t * Link of the menu item key.\n\t */\n\t\n\tpublic static final String KEY_MENU_LINK = \"link\";\n\t\n\t/**\n\t * Weight of the menu item key.\n\t */\n\t\n\tpublic static final String KEY_MENU_WEIGHT = \"weight\";\n\t\n\t/**\n\t * Whether the menu item should be opened in a new tab.\n\t */\n\t\n\tpublic static final String KEY_MENU_NEW_TAB = \"new_tab\";\n\t\n\t/**\n\t * Children of the menu item key.\n\t */\n\t\n\tpublic static final String KEY_MENU_CHILDREN = \"children\";\n\t\n\t/**\n\t * ==========================\n\t * YAML PROJECT KEYS AND TAGS\n\t * ==========================\n\t */\n\t\n\t/**\n\t * Project's name key.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_NAME = \"project_name\";\n\t\n\t/**\n\t * Project's description key.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_DESCRIPTION = \"project_description\";\n\t\n\t/**\n\t * Project's url key.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_URL = \"project_url\";\n\t\n\t/**\n\t * Project's default language key.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_LANGUAGE = \"default_language\";\n\t\n\t/**\n\t * Whether the default order should be alphabetical.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_DEFAULT_ORDER_ALPHABETICAL = \"default_order_alphabetical\";\n\t\n\t/**\n\t * Whether lunr search is enabled.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_ENABLE_LUNR = \"enable_lunr\";\n\t\n\t/**\n\t * Whether minification is enabled in production mode.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_ENABLE_MINIFICATION = \"enable_minification\";\n\t\n\t/**\n\t * Whether less compilation is enabled.\n\t */\n\t\n\tpublic static final String KEY_PROJECT_ENABLE_LESS = \"enable_less\";\n\t\n\t/**\n\t * lunr search key.\n\t */\n\t\n\t@Deprecated\n\tpublic static final String KEY_PROJECT_LUNR_SEARCH = \"lunr_search\";\n\t\n\t/**\n\t * =============================\n\t * PROJECT FILES AND DIRECTORIES\n\t * =============================\n\t */\n\t\n\t/**\n\t * YAML project data file.\n\t */\n\t\n\tpublic static final String FILE_PROJECT_DATA = \"project.yml\";\n\t\n\t/**\n\t * GUI history.\n\t */\n\t\n\tpublic static final String FILE_GUI_HISTORY = \"history\";\n\t\n\t/**\n\t * YAML menu data file prefix.\n\t */\n\t\n\tpublic static final String FILE_MENU_PREFIX = \"menu\";\n\t\n\t/**\n\t * YAML menu data file suffix.\n\t */\n\t\n\tpublic static final String FILE_MENU_SUFFIX = \".yml\";\n\t\n\t/**\n\t * Content directory.\n\t */\n\t\n\tpublic static final String FILE_CONTENT_DIRECTORY = \"content\";\n\t\n\t/**\n\t * Build directory.\n\t */\n\t\n\tpublic static final String FILE_BUILD_DIRECTORY = \"build\";\n\t\n\t/**\n\t * Theme directory.\n\t */\n\t\n\tpublic static final String FILE_THEME_DIRECTORY = \"theme\";\n\t\n\t/**\n\t * Template page file.\n\t */\n\t\n\tpublic static final String FILE_THEME_PAGE_FILE = \"page.html\";\n\t\n\t/**\n\t * Theme assets directory.\n\t */\n\t\n\tpublic static final String FILE_ASSETS_DIRECTORY = \"assets\";\n\t\n\t/**\n\t * =========\n\t * RESOURCES\n\t * =========\n\t */\n\t\n\t/**\n\t * The redirect language file path.\n\t */\n\t\n\tpublic static final String RESOURCE_REDIRECT_LANGUAGE_PATH = \"main/resources/redirect_language_page/\";\n\t\n\t/**\n\t * The redirect language file.\n\t */\n\t\n\tpublic static final String RESOURCE_REDIRECT_LANGUAGE_FILE = \"index.html\";\n\t\n\t/**\n\t * The default theme directory path.\n\t */\n\t\n\tpublic static final String RESOURCE_DEFAULT_THEME_PATH = \"main/resources/\";\n\t\n\t/**\n\t * The default theme directory.\n\t */\n\t\n\tpublic static final String RESOURCE_DEFAULT_THEME_DIRECTORY = \"default_theme\";\n\t\n\t/**\n\t * The search page file path.\n\t */\n\t\n\tpublic static final String RESOURCE_SEARCH_PAGE_PATH = \"main/resources/search_page/\";\n\t\n\t/**\n\t * The search page file.\n\t */\n\t\n\tpublic static final String RESOURCE_SEARCH_PAGE_FILE = \"search.html\";\n\t\n\t/**\n\t * The new project directory path.\n\t */\n\t\n\tpublic static final String RESOURCE_NEW_PROJECT_PATH = \"main/resources/\";\n\t\n\t/**\n\t * The new project directory.\n\t */\n\t\n\tpublic static final String RESOURCE_NEW_PROJECT_DIRECTORY = \"new_project\";\n\t\n\t/**\n\t * The project's icon location. No need to use another icon as it is already stored somewhere in the application.\n\t */\n\t\n\tpublic static final String RESOURCE_PROJECT_ICON = \"/main/resources/default_theme/assets/img/icon.png\";\n\t\n\t/**\n\t * ==============================\n\t * CUSTOM VARIABLES AND FUNCTIONS\n\t * ==============================\n\t */\n\t\n\t/**\n\t * The include file function.\n\t */\n\t\n\tpublic static final String FUNCTION_INCLUDE_FILE = \"includeFile\";\n\t\n\t/**\n\t * The range function.\n\t */\n\t\n\tpublic static final String FUNCTION_RANGE = \"range\";\n\t\n\t/**\n\t * The SkyDocs variable.\n\t */\n\t\n\tpublic static final String VARIABLE_GENERATOR_NAME = \"generator_name\";\n\t\n\t/**\n\t * The SkyDocs version.\n\t */\n\t\n\tpublic static final String VARIABLE_GENERATOR_VERSION = \"generator_version\";\n\t\n\t/**\n\t * The SkyDocs website.\n\t */\n\t\n\tpublic static final String VARIABLE_GENERATOR_WEBSITE = \"generator_website\";\n\t\n\t/**\n\t * The project variable.\n\t */\n\t\n\tpublic static final String VARIABLE_PROJECT = \"project\";\n\t\n\t/**\n\t * The page variable.\n\t */\n\t\n\tpublic static final String VARIABLE_PAGE = \"page\";\n\t\n\t/**\n\t * The redirection url variable.\n\t */\n\t\n\tpublic static final String VARIABLE_REDIRECTION_URL = \"redirectionUrl\";\n\t\n\t/**\n\t * The lunr data variable.\n\t */\n\t\n\tpublic static final String VARIABLE_LUNR_DATA = \"lunrData\";\n\t\n\t/**\n\t * ==============\n\t * SERVE COMMMAND\n\t * ==============\n\t */\n\t\n\t/**\n\t * This will be the interval between two files check.\n\t */\n\t\n\tpublic static final long SERVE_FILE_POLLING_INTERVAL = 2 * 1000L;\n\t\n\t/**\n\t * Modifying one of this file or folder will results in a re-build.\n\t */\n\t\n\tpublic static final String[] SERVE_REBUILD_PREFIX = new String[]{FILE_CONTENT_DIRECTORY, FILE_THEME_DIRECTORY, FILE_MENU_PREFIX, FILE_PROJECT_DATA};\n\t\n\t/**\n\t * Going to http://localhost:port/SERVE_LASTBUILD_URL will print the last build date in milliseconds.\n\t */\n\t\n\tpublic static final String SERVE_LASTBUILD_URL = \"lastbuild\";\n\t\n\t/**\n\t * ============\n\t * GUI ELEMENTS\n\t * ============\n\t */\n\t\n\t/**\n\t * The frame's title.\n\t */\n\t\n\tpublic static final String GUI_FRAME_TITLE = APP_NAME + \" \" + APP_VERSION + \" - GUI\";\n\t\n\t/**\n\t * The create button text.\n\t */\n\t\n\tpublic static final String GUI_BUTTON_CREATE = \"Create project...\";\n\t\n\t/**\n\t * The add button text.\n\t */\n\t\n\tpublic static final String GUI_BUTTON_OPEN = \"Open project...\";\n\t\n\t/**\n\t * The remove button text.\n\t */\n\t\n\tpublic static final String GUI_BUTTON_REMOVE = \"Remove project\";\n\t\n\t/**\n\t * The build button text.\n\t */\n\t\n\tpublic static final String GUI_BUTTON_BUILD = \"Build project\";\n\t\n\t/**\n\t * The serve button text.\n\t */\n\t\n\tpublic static final String GUI_BUTTON_SERVE = \"Serve project\";\n\t\n\t/**\n\t * The stop button text.\n\t */\n\t\n\tpublic static final String GUI_BUTTON_STOP = \"Stop\";\n\t\n\t/**\n\t * The file chooser description.\n\t */\n\t\n\tpublic static final String GUI_CHOOSER_DESCRIPTION = \"Project data (\" + FILE_PROJECT_DATA + \")\";\n\t\n\t/**\n\t * The error dialog message.\n\t */\n\t\n\tpublic static final String GUI_DIALOG_ERROR_MESSAGE = \"An error occurred :\\n%s\";\n\t\n\t/**\n\t * ======\n\t * OTHERS\n\t * ======\n\t */\n\t\n\t/**\n\t * Header marks (like YAML front matter).\n\t */\n\t\n\tpublic static final String HEADER_MARK = \"---\";\n\t\n\t/**\n\t * The default serve port.\n\t */\n\t\n\tpublic static final int DEFAULT_PORT = 4444;\n\n\t/**\n\t * Auto rebuild message.\n\t */\n\n\tpublic static final String SERVE_AUTO_REBUILD = \"Press CTRL+C to quit (auto rebuild is enabled) :\";\n\n\t/**\n\t * Manual & auto rebuild message.\n\t */\n\n\tpublic static final String SERVE_MANUAL_REBUILD = \"Enter nothing to rebuild the website or enter something to stop the server (auto & manual rebuild are enabled). You can also press CTRL+C to quit :\";\n\n}", "public abstract class DocsRunnable<T> {\n\n\t/**\n\t * Contains all runnable listeners.\n\t */\n\n\tprivate final HashSet<RunnableListener> listeners = new HashSet<>();\n\n\t/**\n\t * The output stream.\n\t */\n\n\tprivate PrintStream out;\n\n\t/**\n\t * The input scanner.\n\t */\n\n\tprivate Scanner in;\n\n\t/**\n\t * Whether this command is interrupted.\n\t */\n\n\tprivate boolean isInterrupted = true;\n\n\t/**\n\t * All sub tasks (they need to be interrupted when this runnable is interrupted).\n\t */\n\n\tprivate DocsRunnable[] subTasks;\n\n\t/**\n\t * Creates a new runnable instance.\n\t */\n\n\tpublic DocsRunnable() {\n\t\tthis(System.out);\n\t}\n\n\t/**\n\t * Creates a new runnable instance.\n\t *\n\t * @param out The output stream.\n\t */\n\n\tpublic DocsRunnable(final PrintStream out) {\n\t\tthis(out, System.in);\n\t}\n\n\t/**\n\t * Creates a new runnable instance.\n\t *\n\t * @param out The output stream.\n\t * @param in The input stream.\n\t */\n\n\tpublic DocsRunnable(final PrintStream out, final InputStream in) {\n\t\tthis(out, in, new DocsRunnable[0]);\n\t}\n\n\t/**\n\t * Creates a new runnable instance.\n\t *\n\t * @param out The output stream.\n\t * @param in The input stream.\n\t * @param subTasks The sub tasks.\n\t */\n\n\tpublic DocsRunnable(final PrintStream out, final InputStream in, final DocsRunnable... subTasks) {\n\t\tthis.out = out;\n\t\tsetInputStream(in);\n\n\t\tthis.subTasks = subTasks;\n\t}\n\n\t/**\n\t * Adds some listeners.\n\t *\n\t * @param listeners The listeners.\n\t */\n\n\tpublic final void addListeners(final RunnableListener... listeners) {\n\t\tthis.listeners.addAll(Arrays.asList(listeners));\n\t}\n\n\t/**\n\t * Removes a listener.\n\t *\n\t * @param listener The listener.\n\t */\n\n\tpublic final void removeListener(final RunnableListener listener) {\n\t\tlisteners.remove(listener);\n\t}\n\n\t/**\n\t * Clears all listeners.\n\t */\n\n\tpublic final void clearListeners() {\n\t\tlisteners.clear();\n\t}\n\n\t/**\n\t * Returns whether the runnable can output some message.\n\t *\n\t * @return Whether the runnable can output some message.\n\t */\n\n\tpublic boolean canOutput() {\n\t\treturn out != null;\n\t}\n\n\t/**\n\t * Returns the output stream.\n\t *\n\t * @return The output stream.\n\t */\n\n\tpublic PrintStream getOutputStream() {\n\t\treturn out;\n\t}\n\n\t/**\n\t * Sets the output stream.\n\t *\n\t * @param out The output stream.\n\t */\n\n\tpublic void setOutputStream(final PrintStream out) {\n\t\tthis.out = out;\n\t}\n\n\t/**\n\t * Outputs a message.\n\t *\n\t * @param message The message.\n\t */\n\n\tpublic void output(final String message) {\n\t\tif(out == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tout.print(message);\n\t}\n\n\t/**\n\t * Outputs a line.\n\t *\n\t * @param message The line.\n\t */\n\n\tpublic void outputLine(final String message) {\n\t\tif(out == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tout.println(message);\n\t}\n\n\t/**\n\t * Outputs a blank line.\n\t */\n\n\tpublic void blankLine() {\n\t\tif(out == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tout.println();\n\t}\n\n\t/**\n\t * Returns whether the command can input a message.\n\t *\n\t * @return Whether the command can input a message.\n\t */\n\n\tpublic boolean canInput() {\n\t\treturn in != null;\n\t}\n\n\t/**\n\t * Returns the input scanner.\n\t *\n\t * @return The input scanner.\n\t */\n\n\tpublic Scanner getScanner() {\n\t\treturn in;\n\t}\n\n\t/**\n\t * Sets the input stream.\n\t *\n\t * @param in The input stream.\n\t */\n\n\tpublic void setInputStream(final InputStream in) {\n\t\tthis.in = in == null ? null : new Scanner(in, StandardCharsets.UTF_8.name());\n\t}\n\n\t/**\n\t * Inputs a line.\n\t *\n\t * @return The line.\n\t */\n\n\tpublic String inputLine() {\n\t\tif(in == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif(in.hasNextLine() && !isInterrupted) {\n\t\t\treturn in.nextLine();\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns all sub tasks.\n\t *\n\t * @return All sub tasks.\n\t */\n\n\tpublic DocsRunnable[] getSubTasks() {\n\t\treturn subTasks;\n\t}\n\n\t/**\n\t * Sets all sub tasks.\n\t *\n\t * @param subTasks All sub tasks.\n\t */\n\n\tpublic void setSubTasks(final DocsRunnable... subTasks) {\n\t\tthis.subTasks = subTasks;\n\t}\n\n\t/**\n\t * Interrupts this runnable and all its sub tasks.\n\t */\n\n\tpublic void interrupt() {\n\t\tisInterrupted = true;\n\n\t\tfor(final DocsRunnable subTask : subTasks) {\n\t\t\tsubTask.interrupt();\n\t\t}\n\n\t\tif(in != null) {\n\t\t\tin.close();\n\t\t}\n\n\t\tfor(final RunnableListener listener : listeners) {\n\t\t\tlistener.onRunnableFinished(this);\n\t\t}\n\t}\n\n\t/**\n\t * Returns whether this runnable is interrupted.\n\t *\n\t * @return Whether this runnable is interrupted.\n\t */\n\n\tpublic boolean isInterrupted() {\n\t\treturn isInterrupted;\n\t}\n\n\t/**\n\t * Exits if interrupted.\n\t *\n\t * @throws InterruptionException The interruption signal.\n\t */\n\n\tprotected void exitIfInterrupted() throws InterruptionException {\n\t\tif(!isInterrupted) {\n\t\t\treturn;\n\t\t}\n\t\tthrow new InterruptionException();\n\t}\n\n\t/**\n\t * Runs this runnable.\n\t *\n\t * @return The result.\n\t */\n\n\tpublic T run() {\n\t\treturn run(true);\n\t}\n\n\t/**\n\t * Runs this runnable.\n\t *\n\t * @param showTime Whether the execution time should be shown.\n\t *\n\t * @return The result.\n\t */\n\n\tpublic T run(final boolean showTime) {\n\t\ttry {\n\t\t\tfor(final RunnableListener listener : listeners) {\n\t\t\t\tlistener.onRunnableStarted(this);\n\t\t\t}\n\n\t\t\tisInterrupted = false;\n\t\t\tfinal long first = System.currentTimeMillis();\n\n\t\t\tfinal T result = execute();\n\t\t\tif(result == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tfinal long second = System.currentTimeMillis();\n\t\t\tif(showTime) {\n\t\t\t\toutputLine(\"Done in \" + (second - first) / 1000f + \" seconds !\");\n\t\t\t}\n\t\t\tinterrupt();\n\n\t\t\treturn result;\n\t\t}\n\t\tcatch(final Exception ex) {\n\t\t\tfor(final RunnableListener listener : listeners) {\n\t\t\t\tlistener.onRunnableError(this, ex);\n\t\t\t}\n\t\t\tblankLine();\n\t\t\toutputLine(\"An exception occurred while executing the command :\");\n\t\t\tif(out != null) {\n\t\t\t\tex.printStackTrace(out);\n\t\t\t}\n\n\t\t\tif(out != System.out) {\n\t\t\t\tex.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Executes this runnable.\n\t *\n\t * @return The execution result.\n\t *\n\t * @throws Exception Whether any exception occurs.\n\t */\n\n\tprotected abstract T execute() throws Exception;\n\n\t/**\n\t * Represents a runnable listener.\n\t */\n\n\tpublic interface RunnableListener {\n\n\t\t/**\n\t\t * Triggered when the runnable execution started.\n\t\t *\n\t\t * @param runnable The runnable.\n\t\t */\n\n\t\tvoid onRunnableStarted(final DocsRunnable runnable);\n\n\t\t/**\n\t\t * Triggered when the runnable execution finished.\n\t\t *\n\t\t * @param runnable The runnable.\n\t\t */\n\n\t\tvoid onRunnableFinished(final DocsRunnable runnable);\n\n\t\t/**\n\t\t * Triggered when the runnable encounters an error.\n\t\t *\n\t\t * @param runnable The runnable.\n\t\t */\n\n\t\tvoid onRunnableError(final DocsRunnable runnable, final Throwable error);\n\n\t}\n\n\t/**\n\t * The interruption signal.\n\t */\n\n\tpublic static class InterruptionException extends Exception {\n\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\tpublic InterruptionException() {\n\t\t\tsuper(\"Interrupted !\");\n\t\t}\n\n\t}\n\n}", "public class BuildCommand extends Command<BuildCommand.Arguments> {\n\t\n\t/**\n\t * If you are in production mode.\n\t */\n\t\n\tprivate final boolean prod;\n\t\n\t/**\n\t * The current project.\n\t */\n\t\n\tprivate DocsProject project;\n\n\t/**\n\t * Task that allows to create the build directory.\n\t */\n\n\tprivate final CreateBuildDirectoryTask createBuildDirectoryTask;\n\n\t/**\n\t * Task that allows to copy & to convert files.\n\t */\n\n\tprivate final ConvertFilesTask convertFilesTask;\n\n\t/**\n\t * Task that allows to copy assets.\n\t */\n\n\tprivate final CopyAssetsTask copyAssetsTask;\n\n\t/**\n\t * Creates a new Command instance.\n\t *\n\t * @param prod Whether we are in production mode.\n\t * @param args User arguments.\n\t */\n\n\tpublic BuildCommand(final boolean prod, final String... args) {\n\t\tthis(prod, System.out, args);\n\t}\n\n\t/**\n\t * Creates a new Command instance.\n\t *\n\t * @param prod Whether we are in production mode.\n\t * @param out The output stream.\n\t * @param args User arguments.\n\t */\n\t\n\tpublic BuildCommand(final boolean prod, final PrintStream out, final String... args) {\n\t\tsuper(out, null, args, new Arguments());\n\n\t\tthis.prod = prod;\n\n\t\tthis.createBuildDirectoryTask = new CreateBuildDirectoryTask(null, out);\n\t\tthis.convertFilesTask = new ConvertFilesTask(null, prod, out);\n\t\tthis.copyAssetsTask = new CopyAssetsTask(null, null, prod, out);\n\n\t\tthis.setSubTasks(createBuildDirectoryTask, convertFilesTask, copyAssetsTask);\n\t\treloadProject();\n\t}\n\t\n\t@Override\n\tpublic final Boolean execute() {\n\t\tif(project == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\toutputLine(\"Running build command...\");\n\n\t\tif(createBuildDirectoryTask.run() == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfinal HashSet<File> copied = convertFilesTask.run();\n\t\tif(copied == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tcopyAssetsTask.setAlreadyCopiedFileList(copied);\n\t\tif(copyAssetsTask.run() == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\toutputLine(\"Finished ! You just have to put the content of \\\"\" + project.getBuildDirectory().getPath() + \"\\\" on your web server.\");\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * Checks if the command is in prod mode.\n\t * \n\t * @return Whether the command is in prod mode.\n\t */\n\t\n\tpublic final boolean isProdMode() {\n\t\treturn prod;\n\t}\n\t\n\t/**\n\t * Reloads the project (pages, menus, ...).\n\t */\n\t\n\tpublic final void reloadProject() {\n\t\tnew ReloadProjectTask(this, new File(this.getArguments().directory), this.getOutputStream()).run();\n\t}\n\t\n\t/**\n\t * Gets the current project.\n\t * \n\t * @return The current project.\n\t */\n\t\n\tpublic final DocsProject getProject() {\n\t\treturn project;\n\t}\n\t\n\t/**\n\t * Sets the current project.\n\t * \n\t * @param project The new project.\n\t */\n\t\n\tpublic final void setProject(final DocsProject project) {\n\t\tthis.project = project;\n\n\t\tcreateBuildDirectoryTask.setProject(project);\n\t\tconvertFilesTask.setProject(project);\n\t\tcopyAssetsTask.setProject(project);\n\t}\n\n\t/**\n\t * Returns the task that allows to create the build directory.\n\t *\n\t * @return The task that allows to create the build directory.\n\t */\n\n\tpublic CreateBuildDirectoryTask getCreateBuildDirectoryTask() {\n\t\treturn createBuildDirectoryTask;\n\t}\n\n\t/**\n\t * Returns the task that allows to copy & convert the files.\n\t *\n\t * @return The task that allows to copy & convert the files.\n\t */\n\n\tpublic ConvertFilesTask getConvertFilesTask() {\n\t\treturn convertFilesTask;\n\t}\n\n\t/**\n\t * Returns the task that allows to copy assets.\n\t *\n\t * @return The task that allows to copy assets.\n\t */\n\n\tpublic CopyAssetsTask getCopyAssetsTask() {\n\t\treturn copyAssetsTask;\n\t}\n\n\t/**\n\t * Command arguments.\n\t */\n\n\tpublic static class Arguments {\n\n\t\t@Parameter(names = {\"-directory\", \"-d\"}, description = \"Sets the current build directory.\")\n\t\tpublic String directory = System.getProperty(\"user.dir\");\n\n\t}\n\t\n}", "public class NewCommand extends Command<NewCommand.Arguments> {\n\n\t/**\n\t * Creates a new Command instance.\n\t *\n\t * @param args User arguments.\n\t */\n\n\tpublic NewCommand(final String... args) {\n\t\tthis(System.out, System.in, args);\n\t}\n\n\t/**\n\t * Creates a new Command instance.\n\t *\n\t * @param out The output stream.\n\t * @param in The input stream.\n\t * @param args User arguments.\n\t */\n\n\tpublic NewCommand(final PrintStream out, final InputStream in, final String... args) {\n\t\tsuper(out, in, args, new Arguments());\n\t}\n\t\n\t@Override\n\tpublic final Boolean execute() throws ProjectAlreadyExistsException, InterruptionException, IOException, URISyntaxException {\n\t\tfinal File directory = new File(this.getArguments().directory);\n\n\t\tif(new File(directory, Constants.FILE_PROJECT_DATA).exists()) {\n\t\t\tthrow new ProjectAlreadyExistsException(\"A project already exists in that location !\");\n\t\t}\n\n\t\toutput(\"Creating a new project in the directory \\\"\" + directory + \"\\\"... \");\n\t\tUtils.extract(Constants.RESOURCE_NEW_PROJECT_PATH, Constants.RESOURCE_NEW_PROJECT_DIRECTORY, directory);\n\n\t\tfinal File jar = Utils.getJARFile();\n\t\tif(jar == null) {\n\t\t\tthrow new NullPointerException(\"Failed to locate JAR !\");\n\t\t}\n\n\t\tfinal String jarPath = jar.getPath();\n\t\tfinal String prefix = com.google.common.io.Files.getFileExtension(jarPath).equalsIgnoreCase(\"jar\") ? \"java -jar \" : \"\";\n\n\t\tfor(final String extension : new String[]{\"bat\", \"sh\", \"command\"}) {\n\t\t\texitIfInterrupted();\n\n\t\t\tcreateFile(jarPath, new File(directory, \"build.\" + extension), prefix + \"\\\"%s\\\" build\");\n\t\t\tcreateFile(jarPath, new File(directory, \"serve.\" + extension), prefix + \"\\\"%s\\\" serve\");\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * Creates a file, content will be formatted with JAR's file location.\n\t *\n\t * @param jarPath The JAR path.\n\t * @param file The file.\n\t * @param content Content of the file.\n\t * \n\t * @throws IOException If an exception occurs while saving the file.\n\t */\n\t\n\tprivate void createFile(final String jarPath, final File file, final String content) throws IOException {\n\t\tFiles.write(file.toPath(), String.format(content, jarPath).getBytes(StandardCharsets.UTF_8));\n\t}\n\n\t/**\n\t * Command arguments.\n\t */\n\n\tpublic static class Arguments {\n\n\t\t@Parameter(names = {\"-directory\", \"-d\"}, description = \"Sets the new project directory.\")\n\t\tpublic String directory = System.getProperty(\"user.dir\");\n\n\t}\n\t\n}", "public class ServeCommand extends Command<ServeCommand.Arguments> {\n\n\t/**\n\t * The docs server.\n\t */\n\n\tprivate DocsServer server;\n\n\t/**\n\t * The build command.\n\t */\n\n\tprivate final BuildCommand command;\n\n\t/**\n\t * The task that allows to run the first build.\n\t */\n\n\tprivate final NewBuildTask newBuildTask;\n\n\t/**\n\t * The task that allows to run a new build.\n\t */\n\n\tprivate final FirstBuildTask firstBuildTask;\n\n\t/**\n\t * The current directory watcher.\n\t */\n\n\tprivate DirectoryWatcher watcher;\n\n\t/**\n\t * Creates a new Command instance.\n\t *\n\t * @param args User arguments.\n\t */\n\n\tpublic ServeCommand(final String... args) {\n\t\tthis(System.out, System.in, args);\n\t}\n\n\t/**\n\t * Creates a new Command instance.\n\t *\n\t * @param out The output stream.\n\t * @param in The input stream.\n\t * @param args User arguments.\n\t */\n\t\n\tpublic ServeCommand(final PrintStream out, final InputStream in, final String... args) {\n\t\tsuper(out, in, args, new Arguments());\n\n\t\tfinal Arguments arguments = this.getArguments();\n\t\tcommand = new BuildCommand(false, null, arguments.directory == null ? null : new String[]{\"-directory\", arguments.directory});\n\n\t\tnewBuildTask = new NewBuildTask(command, true, out);\n\t\tfirstBuildTask = new FirstBuildTask(this, arguments.port, out);\n\n\t\tthis.setSubTasks(command, newBuildTask, firstBuildTask);\n\t}\n\t\n\t@Override\n\tpublic final Boolean execute() throws IOException {\n\t\tfinal Arguments arguments = this.getArguments();\n\t\tblankLine();\n\n\t\tif(!arguments.manualRebuild || this.getScanner() == null) {\n\t\t\tnewBuildTask.run();\n\t\t\tserver = firstBuildTask.run(false);\n\t\t\tregisterFileListener(server);\n\t\t\treturn null;\n\t\t}\n\n\t\tboolean firstBuild = true;\n\t\tString line = \"\";\n\t\twhile(line == null || line.isEmpty()) {\n\t\t\tfinal Long buildTime = newBuildTask.run();\n\t\t\tif(buildTime == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tif(server != null) {\n\t\t\t\tserver.setLastBuild(buildTime);\n\t\t\t}\n\n\t\t\tif(firstBuild) {\n\t\t\t\tserver = firstBuildTask.run(false);\n\t\t\t\tregisterFileListener(server);\n\t\t\t}\n\t\t\tfirstBuild = false;\n\n\t\t\toutputLine(Constants.SERVE_MANUAL_REBUILD);\n\t\t\tblankLine();\n\n\t\t\tif(isInterrupted()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tline = inputLine();\n\t\t}\n\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic final void interrupt() {\n\t\tif(server != null) {\n\t\t\ttry {\n\t\t\t\tserver.stop();\n\t\t\t}\n\t\t\tcatch(final Exception ex) {\n\t\t\t\tex.printStackTrace(this.getOutputStream() == null ? System.err : this.getOutputStream());\n\t\t\t}\n\t\t}\n\n\t\tif(watcher != null) {\n\t\t\ttry {\n\t\t\t\twatcher.close();\n\t\t\t}\n\t\t\tcatch(Exception ex) {\n\t\t\t\tex.printStackTrace(this.getOutputStream() == null ? System.err : this.getOutputStream());\n\t\t\t}\n\t\t}\n\n\t\tsuper.interrupt();\n\t}\n\n\t/**\n\t * Returns the build command.\n\t *\n\t * @return The build command.\n\t */\n\n\tpublic final BuildCommand getBuildCommand() {\n\t\treturn command;\n\t}\n\n\t/**\n\t * Returns the task that allows to run the first build.\n\t *\n\t * @return The task that allows to run the first build.\n\t */\n\n\tpublic final FirstBuildTask getFirstBuildTask() {\n\t\treturn firstBuildTask;\n\t}\n\n\t/**\n\t * Returns the task that allows to run a new build.\n\t *\n\t * @return The task that allows to run a new build.\n\t */\n\n\tpublic final NewBuildTask getNewBuildTask() {\n\t\treturn newBuildTask;\n\t}\n\n\t/**\n\t * Returns the directory watcher.\n\t *\n\t * @return The directory watcher.\n\t */\n\n\tpublic final DirectoryWatcher getWatcher() {\n\t\treturn watcher;\n\t}\n\n\t/**\n\t * Creates and registers a file listener with the help of the specified build command.\n\t *\n\t * @param server The current docs server.\n\t *\n\t * @throws IOException If any I/O exception occurs.\n\t */\n\n\tprivate void registerFileListener(final DocsServer server) throws IOException {\n\t\twatcher = DirectoryWatcher\n\t\t\t\t.builder()\n\t\t\t\t.path(command.getProject().getDirectory().toPath())\n\t\t\t\t.listener(event -> {\n\t\t\t\t\tfinal File file = event.path().toFile();\n\t\t\t\t\trebuildIfNeeded(server, event.eventType() != DirectoryChangeEvent.EventType.MODIFY || server.getProject().shouldReloadProject(file), file);\n\t\t\t\t})\n\t\t\t\t.build();\n\t\twatcher.watchAsync();\n\t}\n\n\t/**\n\t * Rebuilds the project if needed.\n\t *\n\t * @param server The docs server.\n\t * @param reloadProject Whether the project should be reloaded.\n\t * @param file The file that has changed.\n\t */\n\n\tprivate synchronized void rebuildIfNeeded(final DocsServer server, final boolean reloadProject, final File file) {\n\t\tfinal String path = file.getPath().replace(command.getProject().getDirectory().getPath(), \"\").substring(1);\n\t\tboolean reBuild = false;\n\t\tfor(final String toRebuild : Constants.SERVE_REBUILD_PREFIX) {\n\t\t\tif(path.startsWith(toRebuild)) {\n\t\t\t\treBuild = true;\n\t\t\t}\n\t\t}\n\t\tif(!reBuild) {\n\t\t\treturn;\n\t\t}\n\n\t\tfinal Long buildTime = new NewBuildTask(command, reloadProject, this.getOutputStream()).run();\n\t\tif(buildTime != null) {\n\t\t\tserver.setLastBuild(buildTime);\n\t\t}\n\n\t\toutputLine(this.getArguments().manualRebuild ? Constants.SERVE_MANUAL_REBUILD : Constants.SERVE_AUTO_REBUILD);\n\t\tblankLine();\n\t}\n\n\t/**\n\t * Command arguments.\n\t */\n\n\tpublic static class Arguments {\n\n\t\t@Parameter(names = {\"-directory\", \"-d\"}, description = \"Sets the current serve directory.\")\n\t\tpublic String directory;\n\n\t\t@Parameter(names = {\"-port\", \"-p\"}, description = \"Sets the server port.\")\n\t\tpublic int port = Constants.DEFAULT_PORT;\n\n\t\t@Parameter(names = {\"-manualRebuild\", \"-mr\"}, description = \"Toggles the manual rebuild.\")\n\t\tpublic boolean manualRebuild = true;\n\n\t}\n\t\n}", "public class GithubUpdater extends Thread {\r\n\t\r\n\tpublic static final String UPDATER_NAME = \"GithubUpdater\";\r\n\tpublic static final String UPDATER_VERSION = \"0.1.2\";\r\n\t\r\n\tpublic static final String UPDATER_GITHUB_USERNAME = \"Skyost\";\r\n\tpublic static final String UPDATER_GITHUB_REPO = \"SkyDocs\";\r\n\t\t\r\n\tprivate final String localVersion;\r\n\tprivate final GithubUpdaterResultListener caller;\r\n\t\r\n\t/**\r\n\t * Creates a new <b>GithubUpdater</b> instance.\r\n\t * \r\n\t * @param localVersion The local version.\r\n\t * @param caller The caller.\r\n\t */\r\n\t\r\n\tpublic GithubUpdater(final String localVersion, final GithubUpdaterResultListener caller) {\r\n\t\tthis.localVersion = localVersion;\r\n\t\tthis.caller = caller;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic final void run() {\r\n\t\tcaller.updaterStarted();\r\n\t\ttry {\r\n\t\t\tfinal HttpURLConnection connection = (HttpURLConnection)new URL(\"https://api.github.com/repos/\" + UPDATER_GITHUB_USERNAME + \"/\" + UPDATER_GITHUB_REPO + \"/releases/latest\").openConnection();\r\n\t\t\tconnection.addRequestProperty(\"User-Agent\", UPDATER_NAME + \" v\" + UPDATER_VERSION);\r\n\t\t\t\r\n\t\t\tfinal String response = connection.getResponseCode() + \" \" + connection.getResponseMessage();\r\n\t\t\tcaller.updaterResponse(response);\r\n\t\t\t\r\n\t\t\tfinal InputStream input = response.startsWith(\"2\") ? connection.getInputStream() : connection.getErrorStream();\r\n\t\t\tfinal InputStreamReader inputStreamReader = new InputStreamReader(input, StandardCharsets.UTF_8);\r\n\t\t\tfinal BufferedReader bufferedReader = new BufferedReader(inputStreamReader);\r\n\t\t\tfinal JsonObject latest = Json.parse(bufferedReader.readLine()).asObject();\r\n\t\t\tinput.close();\r\n\t\t\tinputStreamReader.close();\r\n\t\t\tbufferedReader.close();\r\n\t\t\t\r\n\t\t\tfinal String remoteVersion = latest.getString(\"tag_name\", \"v0\").substring(1);\r\n\t\t\tif(compareVersions(remoteVersion, localVersion)) {\r\n\t\t\t\tcaller.updaterUpdateAvailable(localVersion, remoteVersion);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tcaller.updaterNoUpdate(localVersion, remoteVersion);\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch(final Exception ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t\tcaller.updaterException(ex);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Compares two versions.\r\n\t * \r\n\t * @param versionTo The version you want to compare to.\r\n\t * @param versionWith The version you want to compare with.\r\n\t * \r\n\t * @return <b>true</b> If <b>versionTo</b> is inferior than <b>versionWith</b>.\r\n\t * <br><b>false</b> If <b>versionTo</b> is superior or equals to <b>versionWith</b>.\r\n\t */\r\n\t\r\n\tprivate static boolean compareVersions(final String versionTo, final String versionWith) {\r\n\t\treturn normalisedVersion(versionTo, \".\", 4).compareTo(normalisedVersion(versionWith, \".\", 4)) > 0;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the formatted name of a version.\r\n\t * <br>Used for the method <b>compareVersions(...)</b> of this class.\r\n\t * \r\n\t * @param version The version you want to format.\r\n\t * @param separator The separator between the numbers of this version.\r\n\t * @param maxWidth The max width of the formatted version.\r\n\t * \r\n\t * @return A string which the formatted version of your version.\r\n\t * \r\n\t * @author Peter Lawrey.\r\n\t */\r\n\r\n\tprivate static String normalisedVersion(final String version, final String separator, final int maxWidth) {\r\n\t\tfinal StringBuilder stringBuilder = new StringBuilder();\r\n\t\tfor(final String normalised : Pattern.compile(separator, Pattern.LITERAL).split(version)) {\r\n\t\t\tstringBuilder.append(String.format(\"%\" + maxWidth + 's', normalised));\r\n\t\t}\r\n\t\treturn stringBuilder.toString();\r\n\t}\r\n\t\r\n\tpublic interface GithubUpdaterResultListener {\r\n\t\t\r\n\t\t/**\r\n\t\t * When the updater starts.\r\n\t\t */\r\n\t\t\r\n\t\tvoid updaterStarted();\r\n\t\t\r\n\t\t/**\r\n\t\t * When an Exception occurs.\r\n\t\t * \r\n\t\t * @param ex The Exception.\r\n\t\t */\r\n\t\t\r\n\t\tvoid updaterException(final Exception ex);\r\n\t\t\r\n\t\t/**\r\n\t\t * The response of the request.\r\n\t\t * \r\n\t\t * @param response The response.\r\n\t\t */\r\n\t\t\r\n\t\tvoid updaterResponse(final String response);\r\n\t\t\r\n\t\t/**\r\n\t\t * If an update is available.\r\n\t\t * \r\n\t\t * @param localVersion The local version (used to create the updater).\r\n\t\t * @param remoteVersion The remote version.\r\n\t\t */\r\n\t\t\r\n\t\tvoid updaterUpdateAvailable(final String localVersion, final String remoteVersion);\r\n\t\t\r\n\t\t/**\r\n\t\t * If there is no update.\r\n\t\t * \r\n\t\t * @param localVersion The local version (used to create the updater).\r\n\t\t * @param remoteVersion The remote version.\r\n\t\t */\r\n\t\t\r\n\t\tvoid updaterNoUpdate(final String localVersion, final String remoteVersion);\r\n\t\t\r\n\t}\r\n\r\n}", "public interface GithubUpdaterResultListener {\r\n\t\t\r\n\t/**\r\n\t * When the updater starts.\r\n\t */\r\n\t\t\r\n\tvoid updaterStarted();\r\n\t\t\r\n\t/**\r\n\t * When an Exception occurs.\r\n\t * \r\n\t * @param ex The Exception.\r\n\t */\r\n\t\t\r\n\tvoid updaterException(final Exception ex);\r\n\t\t\r\n\t/**\r\n\t * The response of the request.\r\n\t * \r\n\t * @param response The response.\r\n\t */\r\n\t\t\r\n\tvoid updaterResponse(final String response);\r\n\t\t\r\n\t/**\r\n\t * If an update is available.\r\n\t * \r\n\t * @param localVersion The local version (used to create the updater).\r\n\t * @param remoteVersion The remote version.\r\n\t */\r\n\t\t\r\n\tvoid updaterUpdateAvailable(final String localVersion, final String remoteVersion);\r\n\t\t\r\n\t/**\r\n\t * If there is no update.\r\n\t * \r\n\t * @param localVersion The local version (used to create the updater).\r\n\t * @param remoteVersion The remote version.\r\n\t */\r\n\t\t\r\n\tvoid updaterNoUpdate(final String localVersion, final String remoteVersion);\r\n\t\t\r\n}\r", "public class Utils {\r\n\t\r\n\t/**\r\n\t * System independent line separator.\r\n\t */\r\n\t\r\n\tpublic static final String LINE_SEPARATOR = System.lineSeparator();\r\n\t\r\n\t/**\r\n\t * The auto refresh page script.\r\n\t */\r\n\t\r\n\tpublic static final String AUTO_REFRESH_SCRIPT;\r\n\t\r\n\tstatic {\r\n\t\tfinal AutoLineBreakStringBuilder builder = new AutoLineBreakStringBuilder(Utils.LINE_SEPARATOR + \"<!-- Auto refresh script, this is not part of your built page so just ignore it ! -->\");\r\n\t\tbuilder.append(\"<script type=\\\"text/javascript\\\">\");\r\n\t\tbuilder.append(\"var lastRefresh = new Date().getTime();\");\r\n\t\tbuilder.append(\"function httpGetAsync() {\");\r\n\t\tbuilder.append(\"\tvar request = new XMLHttpRequest();\");\r\n\t\tbuilder.append(\"\trequest.onreadystatechange = function() { \");\r\n\t\tbuilder.append(\"\t\tif(request.readyState == 4) {\");\r\n\t\tbuilder.append(\"\t\t\tif(request.status == 200 && lastRefresh < request.responseText) {\");\r\n\t\tbuilder.append(\"\t\t\t\tlocation.reload();\");\r\n\t\tbuilder.append(\"\t\t\t\treturn;\");\r\n\t\tbuilder.append(\"\t\t\t}\");\r\n\t\tbuilder.append(\"\t\t\tsetTimeout(httpGetAsync, \" + Constants.SERVE_FILE_POLLING_INTERVAL + \");\");\r\n\t\tbuilder.append(\"\t\t}\");\r\n\t\tbuilder.append(\"\t}\");\r\n\t\tbuilder.append(\"\trequest.open('GET', '/\" + Constants.SERVE_LASTBUILD_URL + \"', true);\");\r\n\t\tbuilder.append(\"\trequest.send(null);\");\r\n\t\tbuilder.append(\"}\");\r\n\t\tbuilder.append(\"httpGetAsync();\");\r\n\t\tbuilder.append(\"</script>\");\r\n\t\tAUTO_REFRESH_SCRIPT = builder.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Creates a file or a directory if it does not exist.\r\n\t * \r\n\t * @param file The file or directory.\r\n\t * \r\n\t * @return The file.\r\n\t * \r\n\t * @throws IOException If an error occurs while trying to create the file.\r\n\t */\r\n\t\r\n\tpublic static File createFileIfNotExist(final File file) throws IOException {\r\n\t\tif(!file.exists()) {\r\n\t\t\tif(file.isDirectory()) {\r\n\t\t\t\tfile.mkdirs();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tfile.createNewFile();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn file;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Tries to parse an Integer from a String.\r\n\t * \r\n\t * @param string The String.\r\n\t * \r\n\t * @return The Integer or null.\r\n\t */\r\n\t\r\n\tpublic static Integer parseInt(final String string) {\r\n\t\ttry {\r\n\t\t\treturn Integer.parseInt(string);\r\n\t\t}\r\n\t\tcatch(final Exception ex) {}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Tries to parse a Boolean from a String.\r\n\t * \r\n\t * @param string The String.\r\n\t * \r\n\t * @return The Boolean or null.\r\n\t */\r\n\t\r\n\tpublic static Boolean parseBoolean(final String string) {\r\n\t\ttry {\r\n\t\t\treturn Boolean.parseBoolean(string);\r\n\t\t}\r\n\t\tcatch(final Exception ex) {}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the JAR file.\r\n\t * \r\n\t * @return The JAR file.\r\n\t */\r\n\t\r\n\tpublic static File getJARFile() {\r\n\t\ttry {\r\n\t\t\treturn new File(SkyDocs.class.getProtectionDomain().getCodeSource().getLocation().toURI());\r\n\t\t}\r\n\t\tcatch(final Exception ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the JAR parent folder.\r\n\t * \r\n\t * @return The JAR parent folder.\r\n\t */\r\n\t\r\n\tpublic static File getParentFolder() {\r\n\t\tfinal File jar = Utils.getJARFile();\r\n\t\tif(jar == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn jar.getParentFile();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Reads a file and separate header from content.\r\n\t * \r\n\t * @param file The part.\r\n\t * \r\n\t * @return A String array, index 0 is the header and index 1 is the content.\r\n\t */\r\n\t\r\n\tpublic static String[] separateFileHeader(final File file) {\r\n\t\ttry {\r\n\t\t\tfinal List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);\r\n\t\t\tif(lines.isEmpty()) {\r\n\t\t\t\treturn new String[]{null, \"\"};\r\n\t\t\t}\r\n\t\t\tif(!lines.get(0).equals(Constants.HEADER_MARK)) {\r\n\t\t\t\treturn new String[]{null, Utils.join(LINE_SEPARATOR, lines)};\r\n\t\t\t}\r\n\t\t\tint headerLimit = -1;\r\n\t\t\tfor(int i = 0; i != lines.size(); i++) {\r\n\t\t\t\tif(i != 0 && lines.get(i).equals(Constants.HEADER_MARK)) {\r\n\t\t\t\t\theaderLimit = i;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(headerLimit == -1) {\r\n\t\t\t\treturn new String[]{null, Utils.join(LINE_SEPARATOR, lines)};\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn new String[]{\r\n\t\t\t\t\tUtils.join(LINE_SEPARATOR, lines.subList(1, headerLimit)),\r\n\t\t\t\t\tUtils.join(LINE_SEPARATOR, lines.subList(headerLimit + 1, lines.size()))\r\n\t\t\t};\r\n\t\t}\r\n\t\tcatch(final Exception ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t}\r\n\t\treturn new String[]{null, null};\r\n\t}\r\n\t\r\n\t/**\r\n\t * Decodes a file's header.\r\n\t * \r\n\t * @param header The header.\r\n\t * \r\n\t * @return A map representing the YAML content key : value.\r\n\t */\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic static Map<String, Object> decodeFileHeader(final String header) {\r\n\t\tif(header == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tfinal Yaml yaml = new Yaml();\r\n\t\treturn (Map<String, Object>)yaml.load(header);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Copies a directory.\r\n\t * \r\n\t * @param directory The directory.\r\n\t * @param destination The destination.\r\n\t * \r\n\t * @throws IOException If an error occurs while trying to create the directory.\r\n\t */\r\n\t\r\n\tpublic static void copyDirectory(final File directory, final File destination) throws IOException {\r\n\t\tif(directory.isFile()) {\r\n\t\t\tFiles.copy(directory.toPath(), destination.toPath());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tdestination.mkdirs();\r\n\t\tfor(final File file : directory.listFiles()) {\r\n\t\t\tcopyDirectory(file, new File(destination, file.getName()));\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Deletes a directory.\r\n\t * \r\n\t * @param directory The directory.\r\n\t */\r\n\t\r\n\tpublic static void deleteDirectory(final File directory) {\r\n\t\tif(directory.isFile()) {\r\n\t\t\tdirectory.delete();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfor(final File file : directory.listFiles()) {\r\n\t\t\tdeleteDirectory(file);\r\n\t\t}\r\n\t\tdirectory.delete();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Extracts a file to the specified directory.\r\n\t * \r\n\t * @param path Path of the file or directory.\r\n\t * @param toExtract The file or directory to extract.\r\n\t * @param destination The destination directory.\r\n\t * \r\n\t * @throws IOException If an exception occurs when trying to extract the file.\r\n\t * @throws URISyntaxException If an exception occurs when trying to locate the file on disk.\r\n\t */\r\n\t\r\n\tpublic static void extract(final String path, final String toExtract, File destination) throws IOException, URISyntaxException {\r\n\t\tfinal File appLocation = new File(SkyDocs.class.getProtectionDomain().getCodeSource().getLocation().toURI());\r\n\t\tif(appLocation.isFile()) {\r\n\t\t\tfinal JarFile jar = new JarFile(appLocation);\r\n\t\t\tfinal Enumeration<JarEntry> enumEntries = jar.entries();\r\n\t\t\t\r\n\t\t\twhile(enumEntries.hasMoreElements()) {\r\n\t\t\t\tfinal JarEntry file = enumEntries.nextElement();\r\n\t\t\t\tif(file.isDirectory() || !file.getName().contains(path + toExtract)) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tFile destFile = new File(destination.getPath() + File.separator + file.getName().replace(path, \"\").replace(toExtract, \"\"));\r\n\t\t\t\tif(destFile.isDirectory()) {\r\n\t\t\t\t\tdestFile = new File(destFile.getPath() + File.separator + toExtract);\r\n\t\t\t\t}\r\n\t\t\t\tif(!destFile.getParentFile().exists()) {\r\n\t\t\t\t\tdestFile.getParentFile().mkdirs();\r\n\t\t\t\t}\r\n\t\t\t\tfinal InputStream is = jar.getInputStream(file);\r\n\t\t\t\tfinal FileOutputStream fos = new FileOutputStream(destFile);\r\n\t\t\t\twhile(is.available() > 0) {\r\n\t\t\t\t\tfos.write(is.read());\r\n\t\t\t\t}\r\n\t\t\t\tfos.close();\r\n\t\t\t\tis.close();\r\n\t\t\t}\r\n\t\t\tjar.close();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfinal File file = new File(appLocation.getPath() + File.separator + path + toExtract);\r\n\t\tif(!file.exists()) {\r\n\t\t\tthrow new FileNotFoundException(file.getPath() + \" not found.\");\r\n\t\t}\r\n\t\t\r\n\t\tif(file.isFile()) {\r\n\t\t\tFiles.copy(file.toPath(), (destination.isFile() ? destination : new File(destination, file.getName())).toPath());\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif(destination.isFile()) {\r\n\t\t\t\tdestination = destination.getParentFile();\r\n\t\t\t}\r\n\t\t\tUtils.copyDirectory(file, destination);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Strips HTML from a String.\r\n\t * \r\n\t * @param string The String.\r\n\t * \r\n\t * @return The String without HTML.\r\n\t */\r\n\t\r\n\tpublic static String stripHTML(final String string) {\r\n\t\treturn string.replaceAll(\"<.*?>\", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Joins a String list.\r\n\t * \r\n\t * @param joiner The String used to join arrays.\r\n\t * @param list The list.\r\n\t * \r\n\t * @return The joined list.\r\n\t */\r\n\r\n\tpublic static String join(final String joiner, final List<String> list) {\r\n\t\treturn join(joiner, list.toArray(new String[list.size()]));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Joins a String array.\r\n\t * \r\n\t * @param joiner The String used to join arrays.\r\n\t * @param strings The array.\r\n\t * \r\n\t * @return The joined array.\r\n\t */\r\n\r\n\tpublic static String join(final String joiner, final String... strings) {\r\n\t\tif(strings.length == 1) {\r\n\t\t\treturn strings[0];\r\n\t\t}\r\n\t\telse if(strings.length == 0) {\r\n\t\t\treturn \"\";\r\n\t\t}\r\n\t\tfinal StringBuilder builder = new StringBuilder();\r\n\t\tfor(final String string : strings) {\r\n\t\t\tbuilder.append(string + joiner);\r\n\t\t}\r\n\t\tbuilder.setLength(builder.length() - joiner.length());\r\n\t\treturn builder.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Just a StringBuilder simulator that adds a line break between each append(...).\r\n\t */\r\n\t\r\n\tpublic static final class AutoLineBreakStringBuilder {\r\n\t\t\r\n\t\tprivate final StringBuilder builder = new StringBuilder();\r\n\t\t\r\n\t\tpublic AutoLineBreakStringBuilder() {}\r\n\t\t\r\n\t\tpublic AutoLineBreakStringBuilder(final String string) {\r\n\t\t\tappend(string);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final void append(final String string) {\r\n\t\t\tdefaultAppend(string + LINE_SEPARATOR);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final void defaultAppend(final String string) {\r\n\t\t\tbuilder.append(string);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final void reset() {\r\n\t\t\tbuilder.setLength(0);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final String toString() {\r\n\t\t\treturn builder.toString();\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Represents a Pair of two elements.\r\n\t *\r\n\t * @param <A> Element A.\r\n\t * @param <B> Element B.\r\n\t */\r\n\t\r\n\tpublic static class Pair<A,B> {\r\n\t\t\r\n\t\tpublic final A a;\r\n\t\tpublic final B b;\r\n\r\n\t\tpublic Pair(A a, B b) {\r\n\t\t\tthis.a = a;\r\n\t\t\tthis.b = b;\r\n\t\t}\r\n\t}\r\n\t\r\n}" ]
import com.google.common.io.Files; import fr.skyost.skydocs.Constants; import fr.skyost.skydocs.DocsRunnable; import fr.skyost.skydocs.command.BuildCommand; import fr.skyost.skydocs.command.NewCommand; import fr.skyost.skydocs.command.ServeCommand; import fr.skyost.skydocs.utils.GithubUpdater; import fr.skyost.skydocs.utils.GithubUpdater.GithubUpdaterResultListener; import fr.skyost.skydocs.utils.Utils; import javax.swing.*; import javax.swing.GroupLayout.Alignment; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.filechooser.FileFilter; import javax.swing.text.DefaultCaret; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List;
}); this.pack(); this.setLocationRelativeTo(null); } @Override public final void onRunnableStarted(final DocsRunnable runnable) { if(runnable instanceof NewCommand) { createProjectButton.setEnabled(false); buildProjectButton.setEnabled(false); serveProjectButton.setEnabled(false); } else if(runnable instanceof BuildCommand) { createProjectButton.setEnabled(false); buildProjectButton.setText(Constants.GUI_BUTTON_STOP); serveProjectButton.setEnabled(false); } else { createProjectButton.setEnabled(false); buildProjectButton.setEnabled(false); serveProjectButton.setText(Constants.GUI_BUTTON_STOP); } removeProjectButton.setEnabled(false); } @Override public final void onRunnableFinished(final DocsRunnable runnable) { final int index = projectsList.getSelectedIndex(); final boolean enabled = 0 <= index && index < projectsModel.size(); if(runnable instanceof NewCommand) { newCommand = null; projectsModel.addElement(((NewCommand)runnable).getArguments().directory); createProjectButton.setEnabled(true); buildProjectButton.setEnabled(enabled); serveProjectButton.setEnabled(enabled); } else if(runnable instanceof BuildCommand) { buildCommand = null; createProjectButton.setEnabled(true); buildProjectButton.setText(Constants.GUI_BUTTON_BUILD); serveProjectButton.setEnabled(enabled); } else { serveCommand = null; createProjectButton.setEnabled(true); buildProjectButton.setEnabled(enabled); serveProjectButton.setText(Constants.GUI_BUTTON_SERVE); } removeProjectButton.setEnabled(true); runnable.blankLine(); logTextArea.setCaretPosition(logTextArea.getText().length()); } @Override public final void onRunnableError(final DocsRunnable runnable, final Throwable error) { JOptionPane.showMessageDialog(this, String.format(Constants.GUI_DIALOG_ERROR_MESSAGE, error.getMessage()), error.getClass().getName(), JOptionPane.ERROR_MESSAGE); } @Override public final void updaterStarted() {} @Override public final void updaterException(final Exception ex) {} @Override public final void updaterResponse(final String response) {} @Override public final void updaterUpdateAvailable(final String localVersion, final String remoteVersion) { final String link = "https://github.com/" + GithubUpdater.UPDATER_GITHUB_USERNAME + "/" + GithubUpdater.UPDATER_GITHUB_REPO + "/releases/latest"; if(JOptionPane.showConfirmDialog(this, "<html>An update is available : v" + remoteVersion + " !<br/>" + "Would you like to visit " + link + " to download it ?</html>", Constants.APP_NAME, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { try { if(Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { Desktop.getDesktop().browse(new URI(link)); } } catch(final Exception ex) { ex.printStackTrace(guiPrintStream); ex.printStackTrace(); JOptionPane.showMessageDialog(ProjectsFrame.this, String.format(Constants.GUI_DIALOG_ERROR_MESSAGE, ex.getMessage()), ex.getClass().getName(), JOptionPane.ERROR_MESSAGE); } } } @Override public final void updaterNoUpdate(final String localVersion, final String remoteVersion) {} /** * Builds a list of icons to use with Swing. * * @return A list of icons to use with Swing. */ private List<Image> buildIconsList() { final Image icon = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(Constants.RESOURCE_PROJECT_ICON)); return Arrays.asList( icon.getScaledInstance(16, 16, Image.SCALE_SMOOTH), icon.getScaledInstance(32, 32, Image.SCALE_SMOOTH), icon.getScaledInstance(64, 64, Image.SCALE_SMOOTH), icon.getScaledInstance(128, 128, Image.SCALE_SMOOTH), icon.getScaledInstance(256, 256, Image.SCALE_SMOOTH), icon//.getScaledInstance(512, 512, Image.SCALE_SMOOTH) // Already in 512x512. ); } /** * Checks for updates. */ public final void checkForUpdates() { new GithubUpdater(Constants.APP_VERSION.split(" ")[0].substring(1), this).start(); } /** * Loads projects from the history. */ public final void loadHistory() { try {
final File history = new File(Utils.getParentFolder(), Constants.FILE_GUI_HISTORY);
7
cvbrandoe/REDEN
src/fr/lip6/reden/ldextractor/per/QueryAuthorBNF.java
[ "public class QuerySource implements QuerySourceInterface {\n\n\t/**\n\t * Prepare the SPARQL statement. Children must implement their own queries.\n\t * \n\t * @param domain\n\t * configuration\n\t * @param firstleter,\n\t * optional filtering for queries\n\t * @return\n\t */\n\tpublic Query formulateSPARQLQuery(List<TopicExtent> domainParams, String firstleter, String outDictionnaireDir) {\n\t\treturn null;\n\t}\n\n\t/**\n\t * Execute query in SPARQL endpoint. \n\t * Same methods for all children.\n\t * @param query, query to execute\n\t * @param sparqlendpoint, URL of the SPARQL endpoint\n\t * @param timeout, query timeout\n\t * @return the result\n\t */\n\tpublic ResultSet executeQuery(Query query, String sparqlendpoint,\n\t\t\tString timeout, String outDictionnaireDir, String letter) {\n\t\t\n\t\ttry {\n\t\t\t// wait 20 seconds for every query\n\t\t\tThread.sleep(10000); \n\t\t\ttry {\n\t\t\t\tQueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlendpoint, query);\n\t\t\t\tResultSet results = qexec.execSelect() ;\n\t\t\t results = ResultSetFactory.copyResults(results) ;\n\t\t\t qexec.close();\n\t\t\t return results ; // Passes the result set out of the try-resources\t\t\t \n\t\t\t} catch (Exception e){\n\t\t\t\tSystem.err.println(\"error in sparql query execution\");\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Process and write results. Children must implement their own result\n\t * processing.\n\t * \n\t * @param res,\n\t * query results\n\t * @param outDictionnaireDir,\n\t * name of the folder where to write the dictionary file\n\t * @param prefixDictionnaireFile,\n\t * prefix of the dico files\n\t * @param letter,\n\t * optional parameter for large repos\n\t */\n\n\tpublic void processResults(ResultSet res, String outDictionnaireDir, String letter,\n\t\t\tList<TopicExtent> domainParams) {\n\t}\n\n}", "public interface QuerySourceInterface {\n\t\t\n\t/**\n\t * Prepare the SPARQL query.\n\t * @param domain configuration\n\t * @param firstleter, optional filtering for queries\n\t * @return the query\n\t */\n\tQuery formulateSPARQLQuery(List<TopicExtent> domainParams, String firstleter, \n\t\t\tString outDictionnaireDir);\n\t\t\n\t/**\n\t * Execute query in SPARQL endpoint.\n\t * @param query, query to execute\n\t * @param sparqlendpoint, URL of the SPARQL endpoint\n\t * @param timeout, query timeout\n\t * @return the result\n\t */\n\tResultSet executeQuery(Query query, String sparqlendpoint, String timeout, \n\t\t\tString outDictionnaireDir, String letter);\n\t\n\t/**\n\t * Process and write results.\n\t * @param res, query results\n\t * @param outDictionnaireDir, name of the folder where to write the dictionary file\n\t * @param prefixDictionnaireFile, prefix of the dico files\n\t * @param optional parameter in the presence of large repos\n\t */\n\tvoid processResults(ResultSet res, String outDictionnaireDir, String letter, List<TopicExtent> domainParams);\n\t\n}", "public class SpatialExtent extends TopicExtent {\n\n\tprivate Double lat1;\n\t\n\tprivate Double lon1;\n\t\n\tprivate Double lat2;\n\t\n\tprivate Double lon2;\n\t\n\tprivate Double lat3;\n\t\n\tprivate Double lon3;\n\t\n\tprivate Double lat4;\n\t\n\tprivate Double lon4;\n\n\tpublic Double getLat1() {\n\t\treturn lat1;\n\t}\n\n\tpublic void setLat1(Double lat1) {\n\t\tthis.lat1 = lat1;\n\t}\n\n\tpublic Double getLon1() {\n\t\treturn lon1;\n\t}\n\n\tpublic void setLon1(Double lon1) {\n\t\tthis.lon1 = lon1;\n\t}\n\n\tpublic Double getLat2() {\n\t\treturn lat2;\n\t}\n\n\tpublic void setLat2(Double lat2) {\n\t\tthis.lat2 = lat2;\n\t}\n\n\tpublic Double getLon2() {\n\t\treturn lon2;\n\t}\n\n\tpublic void setLon2(Double lon2) {\n\t\tthis.lon2 = lon2;\n\t}\n\n\tpublic Double getLat3() {\n\t\treturn lat3;\n\t}\n\n\tpublic void setLat3(Double lat3) {\n\t\tthis.lat3 = lat3;\n\t}\n\n\tpublic Double getLon3() {\n\t\treturn lon3;\n\t}\n\n\tpublic void setLon3(Double lon3) {\n\t\tthis.lon3 = lon3;\n\t}\n\n\tpublic Double getLat4() {\n\t\treturn lat4;\n\t}\n\n\tpublic void setLat4(Double lat4) {\n\t\tthis.lat4 = lat4;\n\t}\n\n\tpublic Double getLon4() {\n\t\treturn lon4;\n\t}\n\n\tpublic void setLon4(Double lon4) {\n\t\tthis.lon4 = lon4;\n\t}\n\t\n}", "public class TemporalExtent extends TopicExtent {\n\t\n\t/**\n\t * A date must be lesser than this date \n\t */\n\tprivate Date lesserThan;\n\t\n\t/**\n\t * A date must be greater than this date\n\t */\n\tprivate Date greaterThan;\n\t\n\tpublic Date getLesserThan() {\n\t\treturn lesserThan;\n\t}\n\tpublic void setLesserThan(Date lesserThan) {\n\t\tthis.lesserThan = lesserThan;\n\t}\n\tpublic Date getGreaterThan() {\n\t\treturn greaterThan;\n\t}\n\tpublic void setGreaterThan(Date greaterThan) {\n\t\tthis.greaterThan = greaterThan;\n\t}\n\t\n}", "public class TopicExtent {\n\n}" ]
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.apache.jena.query.Query; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import com.opencsv.CSVWriter; import fr.lip6.reden.ldextractor.QuerySource; import fr.lip6.reden.ldextractor.QuerySourceInterface; import fr.lip6.reden.ldextractor.SpatialExtent; import fr.lip6.reden.ldextractor.TemporalExtent; import fr.lip6.reden.ldextractor.TopicExtent;
package fr.lip6.reden.ldextractor.per; /** * This class queries the authors catalog in the BnF SPARQL end point. * * @author Brando & Frontini */ public class QueryAuthorBNF extends QuerySource implements QuerySourceInterface { private static Logger logger = Logger.getLogger(QueryAuthorBNF.class); /** * Mandatory fields */ public String SPARQL_END_POINT = "http://data.bnf.fr/sparql"; public Integer TIMEOUT = 200000; public Boolean LARGE_REPO = true; public String prefixDictionnaireFile = "authorBNF"; /** * Default constructor. */ public QueryAuthorBNF () { super(); } /** * Formulate a query which is decomposed in several sub-queries because of size of the BnF repo. * */ @Override
public Query formulateSPARQLQuery(List<TopicExtent> domainParams,
4
mosmetro-android/mosmetro-android
app/src/main/java/pw/thedrhax/mosmetro/updater/UpdateChecker.java
[ "public class SafeViewActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (!getIntent().hasExtra(\"data\")) {\n finish(); return;\n }\n\n Uri data = Uri.parse(getIntent().getStringExtra(\"data\"));\n Intent intent = new Intent(Intent.ACTION_VIEW, data);\n\n if (getIntent().hasExtra(\"action\")) {\n intent.setAction(getIntent().getStringExtra(\"action\"));\n }\n\n try {\n startActivity(intent);\n } catch (ActivityNotFoundException ex) {\n Toast.makeText(this, R.string.toast_view_exception, Toast.LENGTH_LONG).show();\n }\n\n finish();\n }\n}", "public class CachedRetriever {\n private SharedPreferences settings;\n private JSONArray cache_storage;\n private Client client;\n\n public enum Type {\n URL, JSON\n }\n\n public CachedRetriever (Context context) {\n this.settings = PreferenceManager.getDefaultSharedPreferences(context);\n\n try {\n cache_storage = (JSONArray)new JSONParser().parse(settings.getString(\"CachedRetriever\", \"[]\"));\n } catch (ParseException ex) {\n cache_storage = new JSONArray();\n }\n\n client = new OkHttp(context);\n }\n\n private long getTimestamp () {\n return System.currentTimeMillis() / 1000L;\n }\n\n private JSONObject findCachedUrl (String url) {\n for (Object object : cache_storage) {\n JSONObject json = (JSONObject)object;\n\n if (json.get(\"url\").equals(url)) return json;\n }\n return null;\n }\n\n public void remove(String url) {\n Collection<Object> remove = new LinkedList<Object>();\n for (Object object : cache_storage)\n if (((JSONObject)object).get(\"url\").equals(url))\n remove.add(object);\n cache_storage.removeAll(remove);\n\n // Write cache to preferences\n settings.edit().putString(\"CachedRetriever\", cache_storage.toString()).apply();\n }\n\n private void writeCachedUrl (String url, String content) {\n // Remove old entries\n remove(url);\n\n // Create new entry\n JSONObject result = new JSONObject();\n result.put(\"url\", url);\n result.put(\"content\", content);\n result.put(\"timestamp\", getTimestamp());\n\n // Add entry to cache\n cache_storage.add(result);\n\n // Write cache to preferences\n settings.edit().putString(\"CachedRetriever\", cache_storage.toString()).apply();\n }\n\n public String get (String url, int ttl, String default_value, Type type) {\n JSONObject cached_url = findCachedUrl(url);\n String result = null;\n\n // Get content from cache if it isn't expired\n if (cached_url != null) {\n long timestamp = (Long) cached_url.get(\"timestamp\");\n if (timestamp + ttl > getTimestamp())\n return cached_url.get(\"content\").toString();\n }\n\n // Try to retrieve content from server\n try {\n HttpResponse response = client.get(url).execute();\n\n if (response.getResponseCode() != 200) {\n throw new IOException(\"Invalid response: \" + response.getResponseCode());\n }\n\n result = response.getPage().trim();\n\n // Validate answer\n if (type == Type.URL && !Patterns.WEB_URL.matcher(result).matches()) {\n throw new Exception(\"Invalid URL: \" + result);\n }\n if (type == Type.JSON) {\n new JSONParser().parse(result); // throws ParseException\n }\n\n // Write new content to cache\n writeCachedUrl(url, result);\n } catch (Exception ex) { // Exception type doesn't matter here\n Logger.log(this, ex.toString());\n\n // Get expired cache if can't retrieve content\n if (cached_url != null) {\n result = cached_url.get(\"content\").toString();\n } else {\n result = null;\n }\n }\n\n return result != null ? result : default_value;\n }\n\n public String get (String url, String default_value, Type type) {\n return get(url, 24*60*60, default_value, type);\n }\n}", "public class Logger {\n public static final String CUT = \"--------[ cut here ]--------\";\n\n public enum LEVEL {INFO, DEBUG}\n\n private static final Map<LEVEL,LogWriter> logs = new HashMap<LEVEL,LogWriter>() {{\n for (LEVEL level : LEVEL.values()) {\n put(level, new LogWriter());\n }\n }};\n\n private static long last_timestamp = 0;\n\n private static String timestamp() {\n long diff = System.currentTimeMillis() - last_timestamp;\n last_timestamp = System.currentTimeMillis();\n\n if (diff > 99000) {\n return \"[+>99s]\";\n } else if (diff > 9999) {\n return String.format(Locale.ENGLISH, \"[+%03ds]\", diff / 1000);\n } else {\n return String.format(Locale.ENGLISH, \"[+%04d]\", diff);\n }\n }\n\n /*\n * Configuration\n */\n\n private static boolean pref_debug_logcat = false;\n private static boolean pref_debug_testing = false;\n\n public static void configure(Context context) {\n SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);\n pref_debug_logcat = settings.getBoolean(\"pref_debug_logcat\", false);\n pref_debug_testing = settings.getBoolean(\"pref_debug_testing\", false);\n\n for (LEVEL level : LEVEL.values()) {\n if (logs.containsKey(level)) {\n logs.get(level).close();\n logs.remove(level);\n }\n\n LogWriter writer = new LogWriter(\n context.getFilesDir(),\n \"log-\" + level.toString().toLowerCase() + \".txt\",\n level == LEVEL.INFO ? 100 : 2000\n );\n\n logs.put(level, writer);\n }\n\n log(LEVEL.DEBUG, CUT);\n }\n\n /*\n * Inputs\n */\n\n public static void log (LEVEL level, CharSequence message) {\n synchronized (logs) {\n if (level == LEVEL.DEBUG && message != CUT) {\n if (pref_debug_logcat) {\n Log.d(\"pw.thedrhax.mosmetro\", message.toString());\n }\n message = timestamp() + \" \" + message;\n }\n if (logs.containsKey(level)) {\n logs.get(level).add(message);\n }\n }\n onUpdate(level, message);\n }\n\n public static void log (LEVEL level, Throwable ex) {\n // getStackTraceString ignores DNS errors\n if (ex instanceof UnknownHostException) {\n log(level, ex.toString());\n } else {\n log(level, Log.getStackTraceString(ex));\n }\n }\n\n public static void log (CharSequence message) {\n for (LEVEL level : LEVEL.values()) {\n log(level, message);\n }\n }\n\n public static void log (Object obj, CharSequence message) {\n if (obj instanceof Metadata) {\n log(LEVEL.DEBUG, String.format(Locale.ENGLISH, \"%s (%d) [%s] | %s\",\n obj.getClass().getSimpleName(),\n System.identityHashCode(obj),\n ((Metadata)obj).tag(),\n message\n ));\n } else {\n log(LEVEL.DEBUG, String.format(Locale.ENGLISH, \"%s (%d) | %s\",\n obj.getClass().getSimpleName(),\n System.identityHashCode(obj),\n message\n ));\n }\n }\n\n /*\n * Logger Utils\n */\n\n public static void date(String prefix) {\n log(prefix + DateFormat.getDateTimeInstance().format(new Date()));\n }\n\n public static void wipe() {\n synchronized (logs) {\n for (LogWriter writer : logs.values()) {\n writer.clear();\n }\n }\n }\n\n public static void report(String message) {\n if (!pref_debug_testing) return;\n Logger.log(LEVEL.DEBUG, \"Sending automated report | \" + message);\n ACRA.getErrorReporter().handleSilentException(new Exception(message));\n }\n\n /*\n * Outputs\n */\n\n public static LinkedList<CharSequence> read(LEVEL level) {\n synchronized (logs) {\n return logs.get(level);\n }\n }\n\n public static String toString(LEVEL level) {\n StringBuilder result = new StringBuilder();\n for (CharSequence message : read(level)) {\n result.append(message).append(\"\\n\");\n }\n return result.toString();\n }\n\n /**\n * Log file writer\n */\n\n public static class LogWriter extends LinkedList<CharSequence> {\n private File file;\n private FileWriter writer = null;\n\n private static List<String> tail(File file, int lines) {\n List<String> history = new LinkedList<>();\n\n if (!file.exists()) return history;\n\n try (FileReader is = new FileReader(file)) {\n BufferedReader reader = new BufferedReader(is);\n\n String line;\n while ((line = reader.readLine()) != null) {\n history.add(line);\n }\n } catch (IOException ignored) {}\n\n if (history.size() > lines) {\n int start = history.size() - lines, end = history.size();\n history = history.subList(start, end);\n }\n\n return history;\n }\n\n public LogWriter(File dir, String filename, int truncate) {\n file = new File(dir, filename);\n\n List<String> history = tail(file, truncate);\n\n clear();\n\n if (history.size() > 0) {\n addAll(history);\n }\n }\n\n public LogWriter() {\n file = null;\n }\n\n @Override\n public boolean add(CharSequence e) {\n try {\n if (writer != null) {\n writer.write(e.toString() + '\\n');\n writer.flush();\n }\n } catch (IOException ignored) {}\n return super.add(e);\n }\n\n @Override\n public boolean addAll(Collection<? extends CharSequence> c) {\n for (CharSequence line : c) {\n try {\n if (writer != null) writer.write(line.toString() + '\\n');\n } catch (IOException ignored) {}\n }\n\n try {\n if (writer != null) writer.flush();\n } catch (IOException ignored) {} \n\n return super.addAll(c);\n }\n\n @Override\n public void clear() {\n if (writer != null) {\n try {\n writer.close();\n } catch (IOException ignored) {}\n writer = null;\n }\n\n if (file != null) {\n try {\n writer = new FileWriter(file, false);\n } catch (IOException ignored) {}\n }\n\n super.clear();\n }\n\n public void close() {\n try {\n if (writer != null) {\n writer.close();\n writer = null;\n }\n } catch (IOException ignored) {}\n }\n }\n\n /**\n * Log sharing routines\n */\n\n public static Uri writeToFile(Context context) throws IOException {\n File log_file = new File(context.getFilesDir(), \"pw.thedrhax.mosmetro.txt\");\n\n FileWriter writer = new FileWriter(log_file);\n writer.write(toString(Logger.LEVEL.DEBUG));\n writer.flush(); writer.close();\n\n return FileProvider.getUriForFile(context, \"pw.thedrhax.mosmetro.provider\", log_file);\n }\n\n public static void share(Context context) {\n Intent share = new Intent(Intent.ACTION_SEND).setType(\"text/plain\")\n .putExtra(Intent.EXTRA_EMAIL,\n new String[] {context.getString(R.string.report_email_address)}\n )\n .putExtra(Intent.EXTRA_SUBJECT,\n context.getString(R.string.report_email_subject, Version.getFormattedVersion())\n );\n\n try {\n share.putExtra(Intent.EXTRA_STREAM, writeToFile(context));\n } catch (IOException ex) {\n Logger.log(Logger.LEVEL.DEBUG, ex);\n Logger.log(context.getString(R.string.error, context.getString(R.string.error_log_file)));\n share.putExtra(Intent.EXTRA_TEXT, read(Logger.LEVEL.DEBUG));\n }\n\n context.startActivity(Intent.createChooser(\n share, context.getString(R.string.report_choose_client)\n ));\n }\n\n /**\n * Metadata interface\n * \n * Allows to override default message format for Logger.log(this, ...)\n */\n public interface Metadata {\n String tag();\n }\n\n /**\n * Callback interface\n *\n * This abstract class will receive messages from another thread\n * and forward them safely to the current thread, so it can be\n * used with the Android UI.\n */\n public static abstract class Callback {\n\n /**\n * Handler object used to forward messages between threads\n */\n private Handler handler;\n\n protected Callback() {\n handler = new Handler(new Handler.Callback() {\n @Override\n public boolean handleMessage(Message msg) {\n log(\n LEVEL.valueOf(msg.getData().getString(\"level\")),\n msg.getData().getCharSequence(\"message\")\n );\n return true;\n }\n });\n }\n\n /**\n * This method is being called from another thread\n * @param level One of values stored in LEVEL enum\n * @param message Text of the message being forwarded\n */\n void call(LEVEL level, CharSequence message) {\n Bundle data = new Bundle();\n data.putString(\"level\", level.name());\n data.putCharSequence(\"message\", message);\n\n Message msg = new Message();\n msg.setData(data);\n\n handler.sendMessage(msg);\n }\n\n /**\n * This method must be implemented by all sub classes\n * to be able to receive the forwarded messages.\n * @param level One of values stored in LEVEL enum\n * @param message Text of the message being forwarded\n */\n public abstract void log(LEVEL level, CharSequence message);\n }\n\n /**\n * Map of registered Callback objects\n */\n private static Map<Object,Callback> callbacks = new HashMap<>();\n\n /**\n * Register the Callback object in the Logger\n * @param key Any object used to identify the Callback\n * @param callback Callback object to be registered\n */\n public static void registerCallback(Object key, Callback callback) {\n callbacks.put(key, callback);\n }\n\n /**\n * Unregister the Callback object\n * @param key Any object used to identify the Callback\n */\n public static void unregisterCallback(Object key) {\n callbacks.remove(key);\n }\n\n /**\n * Get the registered Callback by it's key object\n * @param key Any object used to identify the Callback\n * @return Callback object identified by this key\n */\n public static Callback getCallback(Object key) {\n return callbacks.get(key);\n }\n\n private static void onUpdate(LEVEL level, CharSequence message) {\n for (Callback callback : callbacks.values()) {\n callback.call(level, message);\n }\n }\n}", "public class UUID {\n public static String get(Context context) {\n SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);\n String uuid = settings.getString(\"uuid\", \"none\");\n if (\"none\".equals(uuid)) {\n uuid = java.util.UUID.randomUUID().toString();\n settings.edit().putString(\"uuid\", uuid).apply();\n }\n return uuid;\n }\n}", "public final class Version {\n private Version() {}\n\n @NonNull public static String getVersionName() {\n return BuildConfig.VERSION_NAME;\n }\n\n public static int getVersionCode() {\n return BuildConfig.VERSION_CODE;\n }\n\n @NonNull public static String getFormattedVersion() {\n if (getBranch().equals(\"play\")) {\n return getVersionName();\n } else {\n return String.format(Locale.ENGLISH,\"%s #%d\", getBranch(), getBuildNumber());\n }\n }\n\n @NonNull public static String getBranch() {\n return BuildConfig.BRANCH_NAME;\n }\n\n public static int getBuildNumber() {\n return BuildConfig.BUILD_NUMBER;\n }\n}" ]
import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.DownloadManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.preference.PreferenceManager; import android.widget.Toast; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.File; import java.util.HashMap; import java.util.Map; import pw.thedrhax.mosmetro.BuildConfig; import pw.thedrhax.mosmetro.R; import pw.thedrhax.mosmetro.activities.SafeViewActivity; import pw.thedrhax.mosmetro.httpclient.CachedRetriever; import pw.thedrhax.util.Logger; import pw.thedrhax.util.UUID; import pw.thedrhax.util.Version;
/** * Wi-Fi в метро (pw.thedrhax.mosmetro, Moscow Wi-Fi autologin) * Copyright © 2015 Dmitry Karikh <the.dr.hax@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pw.thedrhax.mosmetro.updater; public class UpdateChecker { // Info from the app private final Context context; private final DownloadManager dm; private final SharedPreferences settings;
private final CachedRetriever retriever;
1
johannilsson/sthlmtraveling
sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/routing/Router.java
[ "public interface ApiService {\n @GET(\"/v1/planner/\")\n void getPlan(\n @Query(\"from\") PlaceQuery from,\n @Query(\"to\") PlaceQuery to,\n @Query(\"mode\") String mode,\n @Query(\"alternative\") boolean alternative,\n @Query(\"via\") PlaceQuery via,\n @Query(\"arriveBy\") boolean arriveBy,\n @Query(\"time\") String time,\n @Query(\"travelMode\") TravelModeQuery travelMode,\n @Query(\"dir\") String dir,\n @Query(\"paginateRef\") String paginateRef,\n Callback<Plan> callback);\n\n @GET(\"/v1/planner/intermediate/\")\n void getIntermediateStops(\n @Query(\"reference\") List<String> reference,\n Callback<IntermediateResponse> callback);\n\n @GET(\"/v1/semistatic/site/near/\")\n void getNearbyStops(\n @Query(\"latitude\") double latitude,\n @Query(\"longitude\") double longitude,\n Callback<NearbyStopsResponse> callback);\n}", "public class PlaceQuery {\n private String id;\n private String name;\n private double lon;\n private double lat;\n\n private PlaceQuery(Builder builder) {\n this.id = builder.id;\n this.name = builder.name;\n this.lat = builder.lat;\n this.lon = builder.lon;\n }\n\n public String getId() {\n return id;\n }\n\n public double getLat() {\n return lat;\n }\n\n public double getLon() {\n return lon;\n }\n\n public String getName() {\n return name;\n }\n\n public String toString() {\n if (id != null) {\n if (this.lat != 0D && this.lon != 0D) {\n return String.format(Locale.US, \"%s,%s:%s:%s\", lat, lon, id, name);\n }\n return String.format(Locale.US, \"%s:%s\", id, name);\n }\n return String.format(Locale.US, \"%s,%s:%s\", lat, lon, name);\n }\n\n public static final class Builder {\n private String id;\n private String name;\n private double lon;\n private double lat;\n\n public Builder place(Place place) {\n this.id = place.getId();\n this.name = place.getName();\n this.lat = place.getLat();\n this.lon = place.getLon();\n return this;\n }\n\n public Builder location(String name, Location location) {\n this.name = name;\n this.lat = location.getLatitude();\n this.lon = location.getLongitude();\n return this;\n }\n\n public Builder location(String name, double lat, double lon) {\n this.name = name;\n this.lat = lat;\n this.lon = lon;\n return this;\n }\n\n public Builder param(String param) {\n name = param.substring(param.lastIndexOf(\":\") + 1);\n String idAndLocation = param.substring(0, param.lastIndexOf(\":\"));\n if (idAndLocation.contains(\",\")) {\n String locationStr;\n if (idAndLocation.contains(\":\")) {\n locationStr = idAndLocation.substring(0, idAndLocation.indexOf(\":\"));\n id = idAndLocation.substring(idAndLocation.indexOf(\":\") + 1);\n } else {\n locationStr = idAndLocation;\n }\n String[] locationParts = TextUtils.split(locationStr, \",\");\n lat = Double.parseDouble(locationParts[0]);\n lon = Double.parseDouble(locationParts[1]);\n } else {\n id = idAndLocation;\n }\n return this;\n }\n\n public PlaceQuery build() {\n return new PlaceQuery(this);\n }\n }\n}", "public class TravelModeQuery {\n\n private List<TravelMode> modes;\n\n public TravelModeQuery(@NonNull List<TravelMode> mode) {\n this.modes = mode;\n }\n\n public void addMode(TravelMode travelMode) {\n this.modes.add(travelMode);\n }\n\n public List<TravelMode> getModes() {\n return modes;\n }\n\n public static TravelModeQuery fromStringList(String travelModes) {\n if (travelModes == null) {\n return new TravelModeQuery(Collections.<TravelMode>emptyList());\n }\n String[] rawModes = travelModes.split(\",\");\n List<TravelMode> modes = new ArrayList<>();\n for (String mode : rawModes) {\n modes.add(new TravelMode(mode));\n }\n return new TravelModeQuery(modes);\n }\n\n @Override\n public String toString() {\n return TextUtils.join(\",\", modes);\n }\n}", "public class Plan implements Parcelable {\n private final List<Route> routes;\n private final String paginateRef;\n private final List<RouteError> errors;\n private String tariffZones;\n private long updatedAtMillis;\n\n public Plan(List<Route> routes, String paginateRef, List<RouteError> errors) {\n this.routes = routes;\n this.paginateRef = paginateRef;\n this.errors = errors;\n }\n\n protected Plan(Parcel in) {\n routes = new ArrayList<>();\n in.readTypedList(routes, Route.CREATOR);\n paginateRef = in.readString();\n errors = new ArrayList<>();\n in.readTypedList(errors, RouteError.CREATOR);\n in.readLong();\n }\n\n public static final Creator<Plan> CREATOR = new Creator<Plan>() {\n @Override\n public Plan createFromParcel(Parcel in) {\n return new Plan(in);\n }\n\n @Override\n public Plan[] newArray(int size) {\n return new Plan[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeTypedList(routes);\n dest.writeString(paginateRef);\n dest.writeTypedList(errors);\n dest.writeLong(updatedAtMillis);\n }\n\n public List<Route> getRoutes() {\n return routes;\n }\n\n public boolean hasRoutes() {\n return routes != null && routes.size() > 0;\n }\n\n public boolean hasErrors(@NonNull String mode) {\n if (errors == null || errors.size() == 0) {\n return false;\n }\n for (RouteError routeError : errors) {\n if (mode.equals(routeError.getMode())) {\n return true;\n }\n }\n return false;\n }\n\n public List<RouteError> getErrors() {\n return errors;\n }\n\n public RouteError getError(@NonNull String mode) {\n if (errors == null) {\n return null;\n }\n for (RouteError routeError : errors) {\n if (mode.equals(routeError.getMode())) {\n return routeError;\n }\n }\n return null;\n }\n\n public String getPaginateRef() {\n return paginateRef;\n }\n\n public boolean canBuySmsTicket() {\n if (!hasRoutes()) {\n return false;\n }\n return false;\n // TODO: Finish this.\n// String tariffZones = null;\n// for (Route route : routes) {\n// if (!route.canBuySmsTicket()) {\n// return false;\n// }\n// if (tariffZones != null && !tariffZones.equals(route.tariffZones)) {\n// tariffZones = null;\n// return false;\n// }\n// tariffZones = trip.tariffZones;\n// }\n// return true;\n }\n\n public String tariffZones() {\n return tariffZones;\n }\n\n public boolean shouldRefresh(long timeMillis) {\n if (!hasRoutes()) {\n return false;\n }\n for (Route route : routes) {\n for (Leg leg : route.getLegs()) {\n if (leg.shouldRefresh(timeMillis)) {\n return true;\n }\n }\n }\n if (updatedAtMillis != 0 && updatedAtMillis < timeMillis - 3600000) {\n return true;\n }\n return false;\n }\n\n public long getUpdatedAtMillis() {\n return updatedAtMillis;\n }\n\n public void setUpdatedAtMillis(long updatedAtMillis) {\n this.updatedAtMillis = updatedAtMillis;\n }\n}", "public class TravelMode {\n public final static String FOOT = \"foot\";\n public final static String BIKE = \"bike\";\n public final static String BIKE_RENTAL = \"bikeRent\";\n public final static String CAR = \"car\";\n public final static String METRO = \"metro\";\n public final static String BUS = \"bus\";\n public final static String TRAIN = \"train\";\n public final static String LIGHT_TRAIN = \"lightTrain\";\n public final static String TRAM = \"tram\";\n public final static String BOAT = \"boat\";\n\n private final String mode;\n\n public TravelMode(String mode) {\n this.mode = mode;\n }\n\n public String getMode() {\n return mode;\n }\n\n @Override\n public String toString() {\n return mode;\n }\n}", "public class JourneyQuery implements Parcelable {\n public Site origin;\n public Site destination;\n public Site via;\n public Date time;\n public boolean isTimeDeparture = true;\n public boolean alternativeStops = false;\n public List<String> transportModes = new ArrayList<>();\n public String ident;\n public boolean hasPromotions;\n public int promotionNetwork = -1;\n // Storing the state of the current ident and scroll dir to allow refresh of paginated\n // results\n @Nullable public String previousIdent;\n @Nullable public String previousDir;\n\n public JourneyQuery() {\n }\n\n public JourneyQuery(Parcel parcel) {\n origin = parcel.readParcelable(Site.class.getClassLoader());\n destination = parcel.readParcelable(Site.class.getClassLoader());\n via = parcel.readParcelable(Site.class.getClassLoader());\n time = new Date(parcel.readLong());\n isTimeDeparture = (parcel.readInt() == 1);\n alternativeStops = (parcel.readInt() == 1);\n transportModes = new ArrayList<String>();\n parcel.readStringList(transportModes);\n ident = parcel.readString();\n hasPromotions = (parcel.readInt() == 1);\n promotionNetwork = parcel.readInt();\n previousIdent = parcel.readString();\n previousDir = parcel.readString();\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.writeParcelable(origin, 0);\n dest.writeParcelable(destination, 0);\n dest.writeParcelable(via, 0);\n dest.writeLong(time.getTime());\n dest.writeInt(isTimeDeparture ? 1 : 0);\n dest.writeInt(alternativeStops ? 1 : 0);\n dest.writeStringList(transportModes);\n dest.writeString(ident);\n dest.writeInt(hasPromotions ? 1 : 0);\n dest.writeInt(promotionNetwork);\n dest.writeString(previousIdent);\n dest.writeString(previousDir);\n }\n\n /**\n * Checks if the query contains has via.\n * \n * @return Returns <code>true</code> if a via location is set,\n * <code>false</code> otherwise.\n */\n public boolean hasVia() {\n return via != null && via.hasName();\n }\n\n /**\n * Returns true if anything has than the defaults has been modified.\n *\n * @return true if any filtering is active.\n */\n public boolean hasAdditionalFiltering() {\n if (hasVia()) {\n return true;\n }\n if (alternativeStops) {\n return true;\n }\n if (transportModes != null) {\n return !hasDefaultTransportModes();\n }\n return false;\n }\n\n public boolean hasDefaultTransportModes() {\n if (transportModes != null) {\n List<String> defaults = Arrays.asList(TransportMode.METRO, TransportMode.BUS,\n TransportMode.WAX, TransportMode.TRAIN, TransportMode.TRAM);\n if (transportModes.containsAll(defaults)) {\n return true;\n }\n }\n return false;\n }\n\n\n public static final Creator<JourneyQuery> CREATOR = new Creator<JourneyQuery>() {\n public JourneyQuery createFromParcel(Parcel parcel) {\n return new JourneyQuery(parcel);\n }\n\n public JourneyQuery[] newArray(int size) {\n return new JourneyQuery[size];\n }\n };\n\n public static JSONObject siteToJson(Site site) throws JSONException {\n JSONObject json = new JSONObject();\n\n json.put(\"id\", site.getId());\n json.put(\"name\", site.getName());\n if (site.isMyLocation()) {\n json.put(\"latitude\", 0);\n json.put(\"longitude\", 0);\n } else if (site.hasLocation()) {\n json.put(\"latitude\", (int) (site.getLocation().getLatitude() * 1E6));\n json.put(\"longitude\", (int) (site.getLocation().getLongitude() * 1E6));\n }\n json.put(\"source\", site.getSource());\n json.put(\"locality\", site.getLocality());\n\n return json;\n }\n\n public static Site jsonToSite(JSONObject json) throws JSONException {\n Site site = new Site();\n\n if (json.has(\"id\")) {\n site.setId(json.getString(\"id\"));\n }\n if (json.has(\"locality\")) {\n site.setLocality(json.getString(\"locality\"));\n }\n if (json.has(\"source\")) {\n site.setSource(json.getInt(\"source\"));\n }\n if (json.has(\"latitude\") && json.has(\"longitude\")) {\n site.setLocation(json.getInt(\"latitude\"), json.getInt(\"longitude\"));\n }\n\n site.setName(json.getString(\"name\"));\n\n return site;\n }\n\n\n public JSONObject toJson(boolean all) throws JSONException {\n JSONObject jsonOrigin = siteToJson(origin);\n JSONObject jsonDestination = siteToJson(destination);\n\n JSONObject jsonQuery = new JSONObject();\n if (via != null) {\n JSONObject jsonVia = siteToJson(via);\n jsonQuery.put(\"via\", jsonVia);\n }\n\n if (transportModes != null) {\n jsonQuery.put(\"transportModes\", new JSONArray(transportModes));\n }\n\n jsonQuery.put(\"alternativeStops\", alternativeStops);\n jsonQuery.put(\"origin\", jsonOrigin);\n jsonQuery.put(\"destination\", jsonDestination);\n\n// if (all) {\n// jsonQuery.put(\"ident\", ident);\n// jsonQuery.put(\"time\", time.format(\"%F %R\"));\n// jsonQuery.put(\"isTimeDeparture\", this.isTimeDeparture);\n// }\n\n return jsonQuery;\n }\n\n public static JourneyQuery fromJson(JSONObject jsonObject)\n throws JSONException {\n JourneyQuery journeyQuery = new JourneyQuery.Builder()\n .origin(jsonObject.getJSONObject(\"origin\"))\n .destination(jsonObject.getJSONObject(\"destination\"))\n .transportModes(jsonObject.has(\"transportModes\")\n ? jsonObject.getJSONArray(\"transportModes\") : null)\n .create();\n\n if (jsonObject.has(\"isTimeDeparture\")) {\n journeyQuery.isTimeDeparture =\n jsonObject.getBoolean(\"isTimeDeparture\");\n }\n if (jsonObject.has(\"alternativeStops\")) {\n journeyQuery.alternativeStops =\n jsonObject.getBoolean(\"alternativeStops\");\n }\n if (jsonObject.has(\"via\")) {\n JSONObject jsonVia = jsonObject.getJSONObject(\"via\");\n journeyQuery.via = jsonToSite(jsonVia);\n }\n\n return journeyQuery;\n }\n\n public Uri toUri(boolean withTime) {\n if (origin == null || destination == null) {\n return null;\n }\n\n Uri routesUri;\n\n PlaceQuery fromQuery = new PlaceQuery.Builder().place(origin.asPlace()).build();\n PlaceQuery toQuery = new PlaceQuery.Builder().place(destination.asPlace()).build();\n\n routesUri = Uri.parse(\"journeyplanner://routes?\");\n\n routesUri = routesUri.buildUpon()\n .appendQueryParameter(\"version\", \"2\")\n .appendQueryParameter(\"from\", Uri.encode(fromQuery.toString()))\n .appendQueryParameter(\"fromSource\", String.valueOf(origin.getSource()))\n .appendQueryParameter(\"to\", Uri.encode(toQuery.toString()))\n .appendQueryParameter(\"toSource\", String.valueOf(destination.getSource()))\n .appendQueryParameter(\"alternative\", String.valueOf(alternativeStops))\n .build();\n\n if (withTime) {\n if (time != null) {\n String timeString = DateTimeUtil.format2445(time);\n routesUri = routesUri.buildUpon()\n .appendQueryParameter(\"time\", timeString)\n .appendQueryParameter(\"isTimeDeparture\", String.valueOf(isTimeDeparture))\n .build();\n }\n }\n\n if (hasVia()) {\n routesUri = routesUri.buildUpon()\n .appendQueryParameter(\"via\", Uri.encode(\n new PlaceQuery.Builder().place(via.asPlace()).build().toString()))\n .build();\n }\n\n if (transportModes != null && !transportModes.isEmpty()) {\n // Convert transport modes to travel modes.\n List<TravelMode> travelModes = LegUtil.transportModesToTravelModes(transportModes);\n TravelModeQuery travelModeQuery = new TravelModeQuery(travelModes);\n routesUri = routesUri.buildUpon()\n .appendQueryParameter(\"travelMode\", travelModeQuery.toString())\n .build();\n }\n\n return routesUri;\n }\n\n /* (non-Javadoc)\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return \"JourneyQuery [alternativeStops=\" + alternativeStops\n + \", destination=\" + destination + \", ident=\" + ident\n + \", isTimeDeparture=\" + isTimeDeparture + \", origin=\" + origin\n + \", time=\" + time + \", transportModes=\"\n + transportModes + \", via=\" + via + \"]\";\n }\n\n public static class Builder {\n private Site mOrigin;\n private Site mDestination;\n private Site mVia;\n private Date mTime;\n private boolean mIsTimeDeparture = true;\n private boolean mAlternativeStops = false;\n private List<String> mTransportModes;\n\n public Builder() {\n \n }\n\n public Builder origin(Site origin) {\n mOrigin = origin;\n return this;\n }\n\n public Builder origin(String name, int latitude, int longitude) {\n mOrigin = new Site();\n mOrigin.setName(name);\n mOrigin.setLocation(latitude, longitude);\n return this;\n }\n\n public Builder origin(JSONObject jsonObject) throws JSONException {\n mOrigin = jsonToSite(jsonObject);\n return this;\n }\n \n public Builder destination(Site destination) {\n mDestination = destination;\n return this;\n }\n\n public Builder destination(JSONObject jsonObject) throws JSONException {\n mDestination = jsonToSite(jsonObject);\n return this;\n }\n \n public Builder destination(String name, int latitude, int longitude) {\n mDestination = new Site();\n mDestination.setName(name);\n mDestination.setLocation(latitude, longitude);\n return this;\n }\n\n public Builder via(Site via) {\n if (via != null && via.hasName()) {\n mVia = via;\n }\n return this;\n }\n\n public Builder via(JSONObject jsonObject) throws JSONException {\n mVia = jsonToSite(jsonObject);\n return this;\n }\n\n public Builder time(Date time) {\n mTime = time;\n return this;\n }\n\n public Builder isTimeDeparture(boolean isTimeDeparture) {\n mIsTimeDeparture = isTimeDeparture;\n return this;\n }\n\n public Builder alternativeStops(boolean alternativeStops) {\n mAlternativeStops = alternativeStops;\n return this;\n }\n\n public Builder transportModes(List<String> transportModes) {\n mTransportModes = transportModes;\n return this;\n }\n\n public Builder transportModes(JSONArray jsonArray) throws JSONException {\n if (jsonArray == null) {\n return this;\n }\n mTransportModes = new ArrayList<String>();\n for (int i = 0; i < jsonArray.length(); i++) {\n mTransportModes.add(jsonArray.getString(i));\n }\n return this;\n }\n\n public Builder uri(Uri uri) {\n String version = uri.getQueryParameter(\"version\");\n if (version == null) {\n return uriV1(uri);\n }\n return uriV2(uri);\n }\n\n public Builder uriV2(Uri uri) {\n Site origin = fromQueryParameter(Uri.decode(uri.getQueryParameter(\"from\")));\n origin.setSource(Integer.parseInt(uri.getQueryParameter(\"fromSource\")));\n origin(origin);\n\n Site destination = fromQueryParameter(Uri.decode(uri.getQueryParameter(\"to\")));\n destination.setSource(Integer.parseInt(uri.getQueryParameter(\"fromSource\")));\n destination(destination);\n\n via(fromQueryParameter(Uri.decode(uri.getQueryParameter(\"via\"))));\n alternativeStops(Boolean.parseBoolean(uri.getQueryParameter(\"alternative\")));\n\n String timeStr = uri.getQueryParameter(\"time\");\n if (timeStr != null) {\n time(DateTimeUtil.parse2445(timeStr));\n isTimeDeparture(Boolean.parseBoolean(uri.getQueryParameter(\"isTimeDeparture\")));\n } else {\n isTimeDeparture(true);\n }\n\n TravelModeQuery travelModeQuery = TravelModeQuery.fromStringList(\n Uri.decode(uri.getQueryParameter(\"travelMode\")));\n transportModes(LegUtil.travelModesToTransportModes(travelModeQuery.getModes()));\n\n return this;\n }\n\n Site fromQueryParameter(String parameter) {\n if (parameter == null) {\n return null;\n }\n Site site = new Site();\n PlaceQuery fromQuery = new PlaceQuery.Builder().param(parameter).build();\n site.setName(fromQuery.getName());\n\n if (fromQuery.getId() != null) {\n site.setId(fromQuery.getId());\n }\n if (fromQuery.getLat() != 0 && fromQuery.getLon() != 0) {\n site.setLocation(fromQuery.getLat(), fromQuery.getLon());\n }\n\n fromQuery = null;\n return site;\n }\n\n public Builder uriV1(Uri uri) {\n Site origin = new Site();\n origin.setName(uri.getQueryParameter(\"start_point\"));\n String originId = uri.getQueryParameter(\"start_point_id\");\n if (!TextUtils.isEmpty(originId) && !\"null\".equals(originId)) {\n origin.setId(originId);\n }\n if (!TextUtils.isEmpty(uri.getQueryParameter(\"start_point_lat\"))\n && !TextUtils.isEmpty(uri.getQueryParameter(\"start_point_lng\"))) {\n origin.setLocation(\n (int) (Double.parseDouble(uri.getQueryParameter(\"start_point_lat\")) * 1E6),\n (int) (Double.parseDouble(uri.getQueryParameter(\"start_point_lng\")) * 1E6));\n }\n if (!TextUtils.isEmpty(uri.getQueryParameter(\"start_point_source\"))) {\n origin.setSource(Integer.parseInt(uri.getQueryParameter(\"start_point_source\")));\n }\n this.origin(origin);\n\n Site destination = new Site();\n destination.setName(uri.getQueryParameter(\"end_point\"));\n String destinationId = uri.getQueryParameter(\"end_point_id\");\n if (!TextUtils.isEmpty(destinationId) && !\"null\".equals(destinationId)) {\n destination.setId(destinationId);\n }\n if (!TextUtils.isEmpty(uri.getQueryParameter(\"end_point_lat\"))\n && !TextUtils.isEmpty(uri.getQueryParameter(\"end_point_lng\"))) {\n destination.setLocation(\n (int) (Double.parseDouble(uri.getQueryParameter(\"end_point_lat\")) * 1E6),\n (int) (Double.parseDouble(uri.getQueryParameter(\"end_point_lng\")) * 1E6));\n }\n if (!TextUtils.isEmpty(uri.getQueryParameter(\"end_point_source\"))) {\n destination.setSource(Integer.parseInt(uri.getQueryParameter(\"end_point_source\")));\n }\n this.destination(destination);\n\n boolean isTimeDeparture = true;\n if (!TextUtils.isEmpty(uri.getQueryParameter(\"isTimeDeparture\"))) {\n isTimeDeparture = Boolean.parseBoolean(\n uri.getQueryParameter(\"isTimeDeparture\"));\n }\n this.isTimeDeparture(isTimeDeparture);\n\n\n Date time = new Date();\n String timeString = uri.getQueryParameter(\"time\");\n if (!TextUtils.isEmpty(timeString)) {\n // TODO: What is the format here?\n //jq.time.parse(timeString);\n } else {\n time.setTime(System.currentTimeMillis());\n }\n this.time(time);\n\n return this;\n }\n\n public JourneyQuery create() {\n JourneyQuery journeyQuery = new JourneyQuery();\n journeyQuery.origin = mOrigin;\n journeyQuery.destination = mDestination;\n journeyQuery.via = mVia;\n\n if (mTime == null) {\n mTime = new Date();\n }\n journeyQuery.time = mTime;\n journeyQuery.isTimeDeparture = mIsTimeDeparture;\n journeyQuery.alternativeStops = mAlternativeStops;\n if (mTransportModes == null || mTransportModes.isEmpty()) {\n mTransportModes = Arrays.asList(TransportMode.METRO, TransportMode.BUS,\n TransportMode.WAX, TransportMode.TRAIN, TransportMode.TRAM);\n }\n journeyQuery.transportModes = mTransportModes;\n\n return journeyQuery;\n }\n\n }\n\n}", "public class DateTimeUtil {\n private static final String TAG = \"DateTimeUtil\";\n public static final long SECOND_IN_MILLIS = 1000;\n public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;\n public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;\n public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;\n public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;\n private static final SimpleDateFormat HOUR_MINUTE_FORMAT =\n new SimpleDateFormat(\"HH:mm\", Locale.US);\n private static final SimpleDateFormat DATE_TIME_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.US);\n private static final SimpleDateFormat DATE_TIME_FORMAT_2445 =\n new SimpleDateFormat(\"yyyyMMdd'T'HHmmss\", Locale.US);\n\n\n public static String format2445(Date date) {\n return DATE_TIME_FORMAT_2445.format(date);\n }\n\n public static Date parse2445(String dateStr) {\n try {\n return DATE_TIME_FORMAT_2445.parse(dateStr);\n } catch (ParseException e) {\n return null;\n }\n }\n\n /**\n * Constructs a Date from the provided date and time.\n *\n * @param dateString In the yy.MM.dd format\n * @param timeString In the HH:mm format\n * @return A Date or null if failed to process the provided strings.\n */\n public static Date fromSlDateTime(final String dateString, final String timeString) {\n String dateTime = String.format(\"%s %s\", dateString, timeString);\n Date date = null;\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"dd.MM.yy HH:mm\", Locale.US);\n try {\n date = simpleDateFormat.parse(dateTime);\n } catch (ParseException e) {\n e.printStackTrace();\n }\n return date;\n }\n\n /**\n * Constructs a Date from the provided date and time.\n *\n * @param dateString In the yyyy-MM-dd format\n * @param timeString In the HH:mm format\n * @return A Date or null if failed to process the provided strings.\n */\n public static Date fromDateTime(final String dateString, final String timeString) {\n String dateTime = String.format(\"%s %s\", dateString, timeString);\n Date date = null;\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\", Locale.US);\n try {\n date = simpleDateFormat.parse(dateTime);\n } catch (ParseException e) {\n e.printStackTrace();\n }\n return date;\n }\n\n /**\n * Constructs a Date from the provided date and time.\n *\n * @param dateTimeString In the yyyy-MM-ddTHH:mm format\n * @return A Date or null if failed to process the provided strings.\n */\n public static Date fromDateTime(@Nullable final String dateTimeString) {\n if (TextUtils.isEmpty(dateTimeString)) {\n return null;\n }\n Date date = null;\n try {\n date = DATE_TIME_FORMAT.parse(dateTimeString);\n } catch (ParseException e) {\n Log.e(TAG, \"Failed to parse date \" + dateTimeString, e);\n }\n return date;\n }\n\n public static String formatDate(Date date) {\n return DATE_TIME_FORMAT.format(date);\n }\n\n /**\n * Return given duration in a human-friendly format. For example, \"4\n * minutes\" or \"1 second\". Returns only largest meaningful unit of time,\n * from seconds up to hours.\n * <p/>\n * From android.text.format.DateUtils\n */\n public static CharSequence formatDuration(final Resources res, final long millis) {\n if (millis >= HOUR_IN_MILLIS) {\n final int hours = (int) ((millis + 1800000) / HOUR_IN_MILLIS);\n return res.getQuantityString(R.plurals.duration_hours, hours, hours);\n } else if (millis >= MINUTE_IN_MILLIS) {\n final int minutes = (int) ((millis + 30000) / MINUTE_IN_MILLIS);\n return res.getQuantityString(R.plurals.duration_minutes, minutes, minutes);\n } else {\n final int seconds = (int) ((millis + 500) / SECOND_IN_MILLIS);\n return res.getQuantityString(R.plurals.duration_seconds, seconds, seconds);\n }\n }\n\n public static CharSequence formatShortDuration(final Resources res, final long millis) {\n if (millis >= HOUR_IN_MILLIS) {\n final int hours = (int) ((millis + 1800000) / HOUR_IN_MILLIS);\n return res.getQuantityString(R.plurals.duration_short_hours, hours, hours);\n } else if (millis >= MINUTE_IN_MILLIS) {\n final int minutes = (int) ((millis + 30000) / MINUTE_IN_MILLIS);\n return res.getQuantityString(R.plurals.duration_short_minutes, minutes, minutes);\n } else {\n final int seconds = (int) ((millis + 500) / SECOND_IN_MILLIS);\n return res.getQuantityString(R.plurals.duration_seconds, seconds, seconds);\n }\n }\n\n /**\n * Format duration without rounding. Seconds are still rounded though.\n *\n * @param resources a resource\n * @param millis duration in millis\n * @return A string representing the duration\n */\n public static CharSequence formatDetailedDuration(@NonNull final Resources resources, long millis) {\n int days = 0, hours = 0, minutes = 0;\n if (millis > 0) {\n days = (int) TimeUnit.MILLISECONDS.toDays(millis);\n millis -= TimeUnit.DAYS.toMillis(days);\n hours = (int) TimeUnit.MILLISECONDS.toHours(millis);\n millis -= TimeUnit.HOURS.toMillis(hours);\n minutes = (int) TimeUnit.MILLISECONDS.toMinutes(millis);\n }\n if (days > 0) {\n return resources.getQuantityString(R.plurals.duration_days, days, days);\n }\n if (hours > 0) {\n if (minutes == 0) {\n return resources.getQuantityString(R.plurals.duration_short_hours, hours, hours);\n }\n return resources.getString(R.string.duration_short_hours_minutes, hours, minutes);\n }\n return resources.getQuantityString(R.plurals.duration_short_minutes, minutes, minutes);\n }\n\n /**\n * Formats the passed display time to something translated and human readable.\n *\n * @param displayTime The display time, can be null, Nu, HH:MM or in the M min.\n * @param context A contect\n * @return\n */\n public static CharSequence formatDisplayTime(@Nullable String displayTime,\n @NonNull Context context) {\n // time str can be \"Nu\", \"2 min\" or in the \"12:00\" format, and possible some unknown\n // ones as well.\n\n // Maybe we should use some memoization func for this.\n\n // Catch when we should show \"Now\"\n if (TextUtils.isEmpty(displayTime)\n || TextUtils.equals(displayTime, \"0 min\")\n || TextUtils.equals(displayTime, \"Nu\")) {\n return context.getString(R.string.now);\n }\n // Catch \"2 min\"\n if (displayTime.contains(\"min\")) {\n String minutes = displayTime.replace(\" min\", \"\");\n // Try to convert minutes to millis.\n try {\n long minutesConverted = Long.valueOf(minutes);\n return formatShortDuration(context.getResources(), minutesConverted * 60000);\n } catch (NumberFormatException e) {\n return displayTime;\n }\n }\n // Catch the \"HH:MM\" format.\n try {\n Date date = HOUR_MINUTE_FORMAT.parse(displayTime);\n return DateFormat.getTimeFormat(context).format(date);\n } catch (ParseException e) {\n return displayTime;\n }\n }\n\n public static CharSequence routeToTimeDisplay(Context context, Route route) {\n java.text.DateFormat format = android.text.format.DateFormat.getTimeFormat(context);\n BidiFormatter bidiFormatter = BidiFormatter.getInstance(RtlUtils.isRtl(Locale.getDefault()));\n\n Pair<Date, RealTimeState> departsAt = route.departsAt(true);\n Pair<Date, RealTimeState> arrivesAt = route.arrivesAt(true);\n\n String departsAtStr = format.format(departsAt.first);\n String arrivesAtStr = format.format(arrivesAt.first);\n CharSequence displayTime;\n if (!DateUtils.isToday(departsAt.first.getTime())) {\n displayTime = String.format(\"%s %s – %s\",\n bidiFormatter.unicodeWrap(DateUtils.getRelativeTimeSpanString(\n departsAt.first.getTime(), System.currentTimeMillis(),\n DateUtils.DAY_IN_MILLIS).toString()),\n bidiFormatter.unicodeWrap(departsAtStr),\n bidiFormatter.unicodeWrap(arrivesAtStr));\n } else {\n displayTime = String.format(\"%s – %s\",\n bidiFormatter.unicodeWrap(departsAtStr),\n bidiFormatter.unicodeWrap(arrivesAtStr));\n }\n\n ForegroundColorSpan spanDepartsAt = new ForegroundColorSpan(ContextCompat.getColor(\n context, ViewHelper.getTextColorByRealtimeState(departsAt.second)));\n Pattern patternDepartsAt = Pattern.compile(departsAtStr);\n displayTime = SpanUtils.createSpannable(displayTime, patternDepartsAt, spanDepartsAt);\n\n ForegroundColorSpan spanArrivessAt = new ForegroundColorSpan(ContextCompat.getColor(\n context, ViewHelper.getTextColorByRealtimeState(arrivesAt.second)));\n Pattern patternArrivesAt = Pattern.compile(arrivesAtStr);\n displayTime = SpanUtils.createSpannable(displayTime, patternArrivesAt, spanArrivessAt);\n\n return displayTime;\n }\n\n /**\n * Get the delay between a scheduled and expected time.\n * <p/>\n * If running ahead of schedule a negative delay is returned.\n *\n * @param scheduledDateTime The scheduled time\n * @param expectedDateTime The expected time\n * @return Delay in seconds\n */\n public static int getDelay(Date scheduledDateTime, Date expectedDateTime) {\n if (scheduledDateTime == null || expectedDateTime == null) {\n throw new IllegalArgumentException(\"Scheduled and or excepted date must not be null\");\n }\n int delay = (int) (Math.abs(TimeUnit.MILLISECONDS.toSeconds(\n expectedDateTime.getTime() - scheduledDateTime.getTime())));\n if (expectedDateTime.getTime() < scheduledDateTime.getTime()) {\n return -delay;\n }\n return delay;\n }\n\n /**\n * Get the real-time state based on the passed delay.\n * @param delay The current delay\n * @return The real-time state\n */\n public static RealTimeState getRealTimeStateFromDelay(int delay) {\n if (delay > 0) {\n return RealTimeState.BEHIND_SCHEDULE;\n } else if (delay < 0) {\n return RealTimeState.AHEAD_OF_SCHEDULE;\n }\n return RealTimeState.ON_TIME;\n }\n}", "public class LegUtil {\n public static Drawable getTransportDrawable(Context context, Leg leg) {\n int color = ContextCompat.getColor(context, R.color.icon_default);\n Drawable drawable;\n\n switch (leg.getTravelMode()) {\n case \"bus\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_bus_20dp);\n return ViewHelper.tintIcon(drawable, color);\n case \"metro\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_sl_metro);\n return ViewHelper.tintIcon(drawable, color);\n case \"foot\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_walk_20dp);\n return ViewHelper.tintIcon(drawable, ContextCompat.getColor(context, R.color.icon_default));\n case \"train\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_train_20dp);\n return ViewHelper.tintIcon(drawable, color);\n case \"tram\":\n case \"lightTrain\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_light_train_20dp);\n return ViewHelper.tintIcon(drawable, color);\n case \"boat\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_boat_20dp);\n return ViewHelper.tintIcon(drawable, color);\n case \"car\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_car_20dp);\n return ViewHelper.tintIcon(drawable, color);\n case \"bike\":\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_bike_20dp);\n return ViewHelper.tintIcon(drawable, color);\n default:\n // What to use when we don't know..\n drawable = ContextCompat.getDrawable(context, R.drawable.ic_transport_train_20dp);\n }\n return ViewHelper.tintIcon(drawable, color);\n }\n\n @ColorInt\n public static int getColor(Context context, Leg leg) {\n if (leg.getRouteColor() == null) {\n // Add color for foot.\n return ContextCompat.getColor(context, R.color.train);\n }\n return Color.parseColor(leg.getRouteColor());\n }\n\n public static String getRouteName(Leg leg, boolean truncate) {\n String routeName = leg.getRouteName();\n if (!TextUtils.isEmpty(routeName)) {\n routeName = ViewHelper.uppercaseFirst(routeName, Locale.US);\n } else {\n routeName = leg.getRouteShortName();\n }\n if (TextUtils.isEmpty(routeName)) {\n return \"\";\n }\n\n if (truncate && routeName.length() > 30) {\n routeName = String.format(Locale.US, \"%s…\", routeName.trim().substring(0, 29));\n }\n return routeName;\n }\n\n public static List<TravelMode> transportModesToTravelModes(List<String> transportModes) {\n List<TravelMode> travelModes = new ArrayList<>();\n for (String transportMode : transportModes) {\n switch (transportMode) {\n case TransportMode.BOAT:\n case TransportMode.WAX:\n travelModes.add(new TravelMode(TravelMode.BOAT));\n break;\n case TransportMode.TRAIN:\n travelModes.add(new TravelMode(TravelMode.TRAIN));\n break;\n case TransportMode.BUS:\n travelModes.add(new TravelMode(TravelMode.BUS));\n break;\n case TransportMode.TRAM:\n travelModes.add(new TravelMode(TravelMode.TRAM));\n travelModes.add(new TravelMode(TravelMode.LIGHT_TRAIN));\n break;\n case TransportMode.METRO:\n travelModes.add(new TravelMode(TravelMode.METRO));\n break;\n case TransportMode.BIKE_RENTAL:\n travelModes.add(new TravelMode(TravelMode.BIKE_RENTAL));\n break;\n }\n }\n return travelModes;\n }\n\n public static List<String> travelModesToTransportModes(List<TravelMode> travelModes) {\n List<String> transportModes = new ArrayList<>();\n for (TravelMode travelMode : travelModes) {\n switch (travelMode.getMode()) {\n case TravelMode.BOAT:\n transportModes.add(TransportMode.BOAT);\n transportModes.add(TransportMode.WAX);\n break;\n case TravelMode.TRAIN:\n transportModes.add(TransportMode.TRAIN);\n break;\n case TravelMode.BUS:\n transportModes.add(TransportMode.BUS);\n break;\n case TravelMode.TRAM:\n case TravelMode.LIGHT_TRAIN:\n transportModes.add(TransportMode.TRAM);\n break;\n case TravelMode.METRO:\n transportModes.add(TransportMode.METRO);\n break;\n }\n }\n return transportModes;\n }\n}" ]
import retrofit.RetrofitError; import retrofit.client.Response; import androidx.annotation.Nullable; import android.util.Log; import com.markupartist.sthlmtraveling.data.api.ApiService; import com.markupartist.sthlmtraveling.data.api.PlaceQuery; import com.markupartist.sthlmtraveling.data.api.TravelModeQuery; import com.markupartist.sthlmtraveling.data.models.Plan; import com.markupartist.sthlmtraveling.data.models.TravelMode; import com.markupartist.sthlmtraveling.provider.planner.JourneyQuery; import com.markupartist.sthlmtraveling.utils.DateTimeUtil; import com.markupartist.sthlmtraveling.utils.LegUtil; import java.util.List;
/* * Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.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 com.markupartist.sthlmtraveling.provider.routing; /** * */ public class Router { private static final String TAG = "Router"; private final ApiService apiService; public Router(ApiService apiService) { this.apiService = apiService; } public void plan(final JourneyQuery journeyQuery, final Callback callback) { if (!journeyQuery.origin.hasLocation() || !journeyQuery.destination.hasLocation()) { Log.w(TAG, "Origin and or destination is missing location data"); callback.onPlan(null); return; } PlaceQuery from = new PlaceQuery.Builder() .location(journeyQuery.origin.getName(), journeyQuery.origin.getLocation()) .build(); PlaceQuery to = new PlaceQuery.Builder() .location(journeyQuery.destination.getName(), journeyQuery.destination.getLocation()) .build(); PlaceQuery via = null; if (journeyQuery.hasVia() && journeyQuery.via.hasLocation()) { via = new PlaceQuery.Builder() .location(journeyQuery.via.getName(), journeyQuery.via.getLocation()) .build(); } else { Log.i(TAG, "Location data not present on via point"); } apiService.getPlan(from, to, "foot,bike,car", false, via, !journeyQuery.isTimeDeparture, null, null, null, null, new retrofit.Callback<Plan>() { @Override public void success(Plan plan, Response response) { callback.onPlan(plan); } @Override public void failure(RetrofitError error) { Log.w(TAG, "Could not fetch a route for foot, bike and car."); callback.onPlanError(journeyQuery, null); } }); } public void refreshTransit(final JourneyQuery journeyQuery, final Callback callback) { planTransit(journeyQuery, callback, journeyQuery.previousIdent, journeyQuery.previousDir); } public void planTransit(final JourneyQuery journeyQuery, final Callback callback) { planTransit(journeyQuery, callback, null); } public void planTransit(final JourneyQuery journeyQuery, final Callback callback, final @Nullable ScrollDir dir) { String direction = dir != null ? dir.getDirection() : null; journeyQuery.previousDir = direction; journeyQuery.previousIdent = journeyQuery.ident; planTransit(journeyQuery, callback, journeyQuery.ident, direction); } public void planTransit(final JourneyQuery journeyQuery, final Callback callback, final String ident, final @Nullable String dir) { PlaceQuery from = new PlaceQuery.Builder() .place(journeyQuery.origin.asPlace()) .build(); PlaceQuery to = new PlaceQuery.Builder() .place(journeyQuery.destination.asPlace()) .build(); PlaceQuery via = null; if (journeyQuery.hasVia()) { via = new PlaceQuery.Builder() .place(journeyQuery.via.asPlace()) .build(); }
List<TravelMode> travelModes = LegUtil.transportModesToTravelModes(
4
petitparser/java-petitparser
petitparser-xml/src/test/java/org/petitparser/grammar/xml/XmlParserTest.java
[ "public class XmlAttribute extends XmlNode {\n\n private final XmlName name;\n private final String value;\n\n public XmlAttribute(XmlName name, String value) {\n this.name = name;\n this.value = value;\n }\n\n public XmlName getName() {\n return name;\n }\n\n public String getValue() {\n return value;\n }\n\n @Override\n public void writeTo(StringBuilder buffer) {\n name.writeTo(buffer);\n buffer.append(XmlDefinition.EQUALS);\n buffer.append(XmlDefinition.DOUBLE_QUOTE);\n buffer.append(XmlCharacterParser.encodeXmlAttributeValue(value));\n buffer.append(XmlDefinition.DOUBLE_QUOTE);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n XmlAttribute other = (XmlAttribute) obj;\n return Objects.equals(name, other.name) &&\n Objects.equals(value, other.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n}", "public class XmlDocument extends XmlParent {\n\n public XmlDocument(Collection<XmlNode> children) {\n super(children);\n }\n\n @Override\n public XmlDocument getDocument() {\n return this;\n }\n\n public XmlElement getRootElement() {\n for (XmlNode node : getChildren()) {\n if (node instanceof XmlElement) {\n return (XmlElement) node;\n }\n }\n return null;\n }\n}", "public class XmlElement extends XmlParent {\n\n private final XmlName name;\n private final List<XmlAttribute> attributes;\n\n public XmlElement(\n XmlName name, Collection<XmlAttribute> attributes,\n Collection<XmlNode> children) {\n super(children);\n this.name = name;\n this.attributes = new ArrayList<>(attributes);\n for (XmlAttribute attribute : attributes) {\n attribute.setParent(this);\n }\n }\n\n public XmlName getName() {\n return name;\n }\n\n @Override\n public List<XmlAttribute> getAttributes() {\n return attributes;\n }\n\n public String getAttribute(String key) {\n XmlAttribute attribute = getAttributeNode(key);\n return attribute != null ? attribute.getValue() : null;\n }\n\n public XmlAttribute getAttributeNode(String key) {\n for (XmlAttribute attribute : attributes) {\n if (Objects.equals(attribute.getName().getLocal(), key)) {\n return attribute;\n }\n }\n return null;\n }\n\n @Override\n public void writeTo(StringBuilder buffer) {\n buffer.append(XmlDefinition.OPEN_ELEMENT);\n getName().writeTo(buffer);\n for (XmlAttribute attribute : getAttributes()) {\n buffer.append(XmlDefinition.WHITESPACE);\n attribute.writeTo(buffer);\n }\n if (getChildren().isEmpty()) {\n buffer.append(XmlDefinition.WHITESPACE);\n buffer.append(XmlDefinition.CLOSE_END_ELEMENT);\n } else {\n buffer.append(XmlDefinition.CLOSE_ELEMENT);\n super.writeTo(buffer);\n buffer.append(XmlDefinition.OPEN_END_ELEMENT);\n getName().writeTo(buffer);\n buffer.append(XmlDefinition.CLOSE_ELEMENT);\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!super.equals(obj) || getClass() != obj.getClass()) {\n return false;\n }\n XmlElement other = (XmlElement) obj;\n return Objects.equals(name, other.name) &&\n Objects.equals(attributes, other.attributes);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), name, attributes.size());\n }\n}", "public class XmlName implements Cloneable {\n\n private final String prefix;\n private final String local;\n\n public XmlName(String name) {\n int index = name.indexOf(':');\n if (index < 0) {\n this.prefix = null;\n this.local = name;\n } else {\n this.prefix = name.substring(0, index);\n this.local = name.substring(index + 1, name.length());\n }\n }\n\n public String getLocal() {\n return local;\n }\n\n public String getPrefix() {\n return prefix;\n }\n\n public String getQualified() {\n return toXmlString();\n }\n\n @Override\n public String toString() {\n return super.toString() + \" (\" + toXmlString() + \")\";\n }\n\n public String toXmlString() {\n StringBuilder buffer = new StringBuilder();\n writeTo(buffer);\n return buffer.toString();\n }\n\n public void writeTo(StringBuilder buffer) {\n if (prefix != null) {\n buffer.append(prefix).append(':');\n }\n buffer.append(local);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n XmlName other = (XmlName) obj;\n return Objects.equals(prefix, other.prefix) &&\n Objects.equals(local, other.local);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(prefix, local);\n }\n}", "public abstract class XmlNode implements Iterable<XmlNode> {\n\n private XmlNode parent;\n\n /**\n * Answer the parent node of the receiver, or {@code null} if there is none.\n */\n public XmlNode getParent() {\n return parent;\n }\n\n /**\n * Set the parent of the receiver.\n */\n void setParent(XmlNode parent) {\n this.parent = parent;\n }\n\n /**\n * Answer the attribute nodes of the receiver.\n */\n public List<XmlAttribute> getAttributes() {\n return Collections.emptyList();\n }\n\n /**\n * Answer the child nodes of the receiver.\n */\n public List<XmlNode> getChildren() {\n return Collections.emptyList();\n }\n\n /**\n * Answer an iterator over the receiver, all attributes and nested children.\n */\n @Override\n public Iterator<XmlNode> iterator() {\n List<XmlNode> nodes = new ArrayList<>();\n allAllNodesTo(nodes);\n return nodes.iterator();\n }\n\n private void allAllNodesTo(List<XmlNode> nodes) {\n nodes.add(this);\n nodes.addAll(getAttributes());\n for (XmlNode node : getChildren()) {\n node.allAllNodesTo(nodes);\n }\n }\n\n /**\n * Answer the root of the subtree in which this node is found, whether that's\n * a document or another element.\n */\n public XmlNode getRoot() {\n return parent == null ? this : parent.getRoot();\n }\n\n /**\n * Answer the document that contains this node, or {@code null} if the node is\n * not part of a document.\n */\n public XmlDocument getDocument() {\n return parent == null ? null : parent.getDocument();\n }\n\n /**\n * Answer the first child of the receiver or {@code null}.\n */\n public final XmlNode getFirstChild() {\n List<XmlNode> children = getChildren();\n return children.isEmpty() ? null : children.get(0);\n }\n\n /**\n * Answer the last child of the receiver or {@code null}.\n */\n public final XmlNode getLastChild() {\n List<XmlNode> children = getChildren();\n return children.isEmpty() ? null : children.get(children.size() - 1);\n }\n\n /**\n * Answer the next sibling of the receiver or {@code null}.\n */\n public final XmlNode getNextSibling() {\n XmlNode parent = getParent();\n if (parent == null) {\n return null;\n }\n List<XmlNode> children = parent.getChildren();\n for (int i = 0; i < children.size() - 1; i++) {\n if (children.get(i) == this) {\n return children.get(i + 1);\n }\n }\n return null;\n }\n\n /**\n * Answer the previous sibling of the receiver or {@code null}.\n */\n public final XmlNode getPreviousSibling() {\n XmlNode parent = getParent();\n if (parent == null) {\n return null;\n }\n List<XmlNode> children = parent.getChildren();\n for (int i = 1; i < children.size(); i++) {\n if (children.get(i) == this) {\n return children.get(i - 1);\n }\n }\n return null;\n }\n\n /**\n * Answer a print string of the receiver.\n */\n @Override\n public String toString() {\n return super.toString() + \" (\" + toXmlString() + \")\";\n }\n\n /**\n * Answer an XML string of the receiver.\n */\n public String toXmlString() {\n StringBuilder buffer = new StringBuilder();\n writeTo(buffer);\n return buffer.toString();\n }\n\n /**\n * Writes the XML string of the receiver to a {@code buffer}.\n */\n public abstract void writeTo(StringBuilder buffer);\n}", "public abstract class Parser {\n\n /**\n * Primitive method doing the actual parsing.\n *\n * <p>The method is overridden in concrete subclasses to implement the parser\n * specific logic. The methods takes a parse {@code context} and returns the\n * resulting context, which is either a\n * {@link org.petitparser.context.Success}\n * or {@link org.petitparser.context.Failure} context.\n */\n public abstract Result parseOn(Context context);\n\n /**\n * Primitive method doing the actual parsing.\n *\n * <p>This method is an optimized version of {@link #parseOn(Context)} that\n * is getting its speed advantage by avoiding any unnecessary memory\n * allocations.\n *\n * <p>The method is overridden in most concrete subclasses to implement the\n * optimized logic. As an input the method takes a {@code buffer} and the\n * current {@code position} in that buffer. It returns a new (positive)\n * position in case of a successful parse, or `-1` in case of a failure.\n *\n * <p>Subclasses don't necessarily have to override this method, since it is\n * emulated using its slower brother.\n */\n public int fastParseOn(String buffer, int position) {\n Result result = parseOn(new Context(buffer, position));\n return result.isSuccess() ? result.getPosition() : -1;\n }\n\n /**\n * Returns the parse result of the {@code input}.\n */\n public Result parse(String input) {\n return parseOn(new Context(input, 0));\n }\n\n /**\n * Tests if the {@code input} can be successfully parsed.\n */\n public boolean accept(String input) {\n return fastParseOn(input, 0) >= 0;\n }\n\n /**\n * Returns a list of all successful overlapping parses of the {@code input}.\n */\n @SuppressWarnings(\"unchecked\")\n public <T> List<T> matches(String input) {\n List<Object> list = new ArrayList<>();\n and().mapWithSideEffects(list::add).seq(any()).or(any()).star()\n .fastParseOn(input, 0);\n return (List<T>) list;\n }\n\n /**\n * Returns a list of all successful non-overlapping parses of the {@code\n * input}.\n */\n @SuppressWarnings(\"unchecked\")\n public <T> List<T> matchesSkipping(String input) {\n List<Object> list = new ArrayList<>();\n mapWithSideEffects(list::add).or(any()).star().fastParseOn(input, 0);\n return (List<T>) list;\n }\n\n /**\n * Returns new parser that accepts the receiver, if possible. The resulting\n * parser returns the result of the receiver, or {@code null} if not\n * applicable.\n */\n public Parser optional() {\n return optional(null);\n }\n\n /**\n * Returns new parser that accepts the receiver, if possible. The returned\n * value can be provided as {@code otherwise}.\n */\n public Parser optional(Object otherwise) {\n return new OptionalParser(this, otherwise);\n }\n\n /**\n * Returns a parser that accepts the receiver zero or more times. The\n * resulting parser returns a list of the parse results of the receiver.\n *\n * <p>This is a greedy and blind implementation that tries to consume as much\n * input as possible and that does not consider what comes afterwards.\n */\n public Parser star() {\n return repeat(0, RepeatingParser.UNBOUNDED);\n }\n\n /**\n * Returns a parser that parses the receiver zero or more times until it\n * reaches a {@code limit}.\n *\n * <p>This is a greedy non-blind implementation of the {@link Parser#star()}\n * operator. The {@code limit} is not consumed.\n */\n public Parser starGreedy(Parser limit) {\n return repeatGreedy(limit, 0, RepeatingParser.UNBOUNDED);\n }\n\n /**\n * Returns a parser that parses the receiver zero or more times until it\n * reaches a {@code limit}.\n *\n * <p>This is a lazy non-blind implementation of the {@link Parser#star()}\n * operator. The {@code limit} is not consumed.\n */\n public Parser starLazy(Parser limit) {\n return repeatLazy(limit, 0, RepeatingParser.UNBOUNDED);\n }\n\n /**\n * Returns a parser that accepts the receiver one or more times. The resulting\n * parser returns a list of the parse results of the receiver.\n *\n * <p>This is a greedy and blind implementation that tries to consume as much\n * input as possible and that does not consider what comes afterwards.\n */\n public Parser plus() {\n return repeat(1, RepeatingParser.UNBOUNDED);\n }\n\n /**\n * Returns a parser that parses the receiver one or more times until it\n * reaches {@code limit}.\n *\n * <p>This is a greedy non-blind implementation of the {@link Parser#plus()}\n * operator. The {@code limit} is not consumed.\n */\n public Parser plusGreedy(Parser limit) {\n return repeatGreedy(limit, 1, RepeatingParser.UNBOUNDED);\n }\n\n /**\n * Returns a parser that parses the receiver one or more times until it\n * reaches a {@code limit}.\n *\n * <p>This is a lazy non-blind implementation of the {@link Parser#plus()}\n * operator. The {@code limit} is not consumed.\n */\n public Parser plusLazy(Parser limit) {\n return repeatLazy(limit, 1, RepeatingParser.UNBOUNDED);\n }\n\n /**\n * Returns a parser that accepts the receiver between {@code min} and {@code\n * max} times. The resulting parser returns a list of the parse results of the\n * receiver.\n *\n * <p>This is a greedy and blind implementation that tries to consume as much\n * input as possible and that does not consider what comes afterwards.\n */\n public Parser repeat(int min, int max) {\n return new PossessiveRepeatingParser(this, min, max);\n }\n\n /**\n * Returns a parser that parses the receiver at least {@code min} and at most\n * {@code max} times until it reaches a {@code limit}.\n *\n * <p>This is a greedy non-blind implementation of the {@link\n * Parser#repeat(int, int)} operator. The {@code limit} is not consumed.\n */\n public Parser repeatGreedy(Parser limit, int min, int max) {\n return new GreedyRepeatingParser(this, limit, min, max);\n }\n\n /**\n * Returns a parser that parses the receiver at least {@code min} and at most\n * {@code max} times until it reaches a {@code limit}.\n *\n * <p>This is a lazy non-blind implementation of the {@link\n * Parser#repeat(int, int)} operator. The {@code limit} is not consumed.\n */\n public Parser repeatLazy(Parser limit, int min, int max) {\n return new LazyRepeatingParser(this, limit, min, max);\n }\n\n /**\n * Returns a parser that accepts the receiver exactly {@code count} times. The\n * resulting parser eturns a list of the parse results of the receiver.\n */\n public Parser times(int count) {\n return repeat(count, count);\n }\n\n /**\n * Returns a parser that accepts the receiver followed by {@code others}. The\n * resulting parser returns a list of the parse result of the receiver\n * followed by the parse result of {@code others}.\n *\n * <p>Calling this method on an existing sequence code not nest this sequence\n * into a new one, but instead augments the existing sequence with {@code\n * others}.\n */\n public SequenceParser seq(Parser... others) {\n Parser[] parsers = new Parser[1 + others.length];\n parsers[0] = this;\n System.arraycopy(others, 0, parsers, 1, others.length);\n return new SequenceParser(parsers);\n }\n\n /**\n * Returns a parser that accepts the receiver or {@code other}. The resulting\n * parser returns the parse result of the receiver, if the receiver fails it\n * returns the parse result of {@code other} (exclusive ordered choice).\n */\n public ChoiceParser or(Parser... others) {\n Parser[] parsers = new Parser[1 + others.length];\n parsers[0] = this;\n System.arraycopy(others, 0, parsers, 1, others.length);\n return new ChoiceParser(parsers);\n }\n\n /**\n * Returns a parser (logical and-predicate) that succeeds whenever the\n * receiver does, but never consumes input.\n */\n public Parser and() {\n return new AndParser(this);\n }\n\n /**\n * Returns a parser that is called with its current continuation.\n */\n public Parser callCC(ContinuationParser.ContinuationHandler handler) {\n return new ContinuationParser(this, handler);\n }\n\n /**\n * Returns a parser (logical not-predicate) that succeeds whenever the\n * receiver fails, but never consumes input.\n */\n public Parser not() {\n return not(\"unexpected\");\n }\n\n /**\n * Returns a parser (logical not-predicate) that succeeds whenever the\n * receiver fails, but never consumes input.\n */\n public Parser not(String message) {\n return new NotParser(this, message);\n }\n\n /**\n * Returns a parser that consumes any input token (character), but the\n * receiver.\n */\n public Parser neg() {\n return neg(this + \" not expected\");\n }\n\n /**\n * Returns a parser that consumes any input token (character), but the\n * receiver.\n */\n public Parser neg(String message) {\n return not(message).seq(CharacterParser.any()).pick(1);\n }\n\n /**\n * Returns a parser that discards the result of the receiver, and instead\n * returns a sub-string of the consumed range in the buffer being parsed.\n */\n public Parser flatten() {\n return new FlattenParser(this);\n }\n\n /**\n * Returns a parser that discards the result of the receiver, and instead\n * returns a sub-string of the consumed range in the buffer being parsed.\n * Reports the provided {@code message} in case of an error.\n */\n public Parser flatten(String message) {\n return new FlattenParser(this, message);\n }\n\n /**\n * Returns a parser that returns a {@link Token}. The token carries the parsed\n * value of the receiver {@link Token#getValue()}, as well as the consumed\n * input {@link Token#getInput()} from {@link Token#getStart()} to {@link\n * Token#getStop()} of the input being parsed.\n */\n public Parser token() {\n return new TokenParser(this);\n }\n\n /**\n * Returns a parser that consumes whitespace before and after the receiver.\n */\n public Parser trim() {\n return trim(CharacterParser.whitespace());\n }\n\n /**\n * Returns a parser that consumes input on {@code both} sides of the\n * receiver.\n */\n public Parser trim(Parser both) {\n return trim(both, both);\n }\n\n /**\n * Returns a parser that consumes input {@code before} and {@code after} the\n * receiver.\n */\n public Parser trim(Parser before, Parser after) {\n return new TrimmingParser(this, before, after);\n }\n\n /**\n * Returns a parser that succeeds only if the receiver consumes the complete\n * input.\n */\n public Parser end() {\n return end(\"end of input expected\");\n }\n\n /**\n * Returns a parser that succeeds only if the receiver consumes the complete\n * input, otherwise return a failure with the {@code message}.\n */\n public Parser end(String message) {\n return new SequenceParser(this, new EndOfInputParser(message)).pick(0);\n }\n\n /**\n * Returns a parser that points to the receiver, but can be changed to point\n * to something else at a later point in time.\n */\n public SettableParser settable() {\n return SettableParser.with(this);\n }\n\n /**\n * Returns a parser that evaluates a {@code function} as the production action\n * on success of the receiver.\n *\n * @param function production action without side-effects.\n */\n public <A, B> Parser map(Function<A, B> function) {\n return new ActionParser<>(this, function);\n }\n\n /**\n * Returns a parser that evaluates a {@code function} as the production action\n * on success of the receiver.\n *\n * @param function production action with possible side-effects.\n */\n public <A, B> Parser mapWithSideEffects(Function<A, B> function) {\n return new ActionParser<>(this, function, true);\n }\n\n /**\n * Returns a parser that transform a successful parse result by returning the\n * element at {@code index} of a list. A negative index can be used to access\n * the elements from the back of the list.\n */\n public Parser pick(int index) {\n return map(Functions.nthOfList(index));\n }\n\n /**\n * Returns a parser that transforms a successful parse result by returning the\n * permuted elements at {@code indexes} of a list. Negative indexes can be\n * used to access the elements from the back of the list.\n */\n public Parser permute(int... indexes) {\n return this.map(Functions.permutationOfList(indexes));\n }\n\n /**\n * Returns a new parser that parses the receiver one or more times, separated\n * by a {@code separator}.\n */\n public Parser separatedBy(Parser separator) {\n return new SequenceParser(this, new SequenceParser(separator, this).star())\n .map((List<List<List<Object>>> input) -> {\n List<Object> result = new ArrayList<>();\n result.add(input.get(0));\n input.get(1).forEach(result::addAll);\n return result;\n });\n }\n\n /**\n * Returns a new parser that parses the receiver one or more times, separated\n * and possibly ended by a {@code separator}.\"\n */\n public Parser delimitedBy(Parser separator) {\n return separatedBy(separator).seq(separator.optional())\n .map((List<List<Object>> input) -> {\n List<Object> result = new ArrayList<>(input.get(0));\n if (input.get(1) != null) {\n result.add(input.get(1));\n }\n return result;\n });\n }\n\n /**\n * Returns a shallow copy of the receiver.\n */\n public abstract Parser copy();\n\n /**\n * Recursively tests for structural similarity of two parsers.\n *\n * <p>The code can automatically deals with recursive parsers and parsers\n * that refer to other parsers. This code is supposed to be overridden by\n * parsers that add other state.\n */\n public boolean isEqualTo(Parser other) {\n return isEqualTo(other, new HashSet<>());\n }\n\n /**\n * Recursively tests for structural similarity of two parsers.\n */\n protected boolean isEqualTo(Parser other, Set<Parser> seen) {\n if (this.equals(other) || seen.contains(this)) {\n return true;\n }\n seen.add(this);\n return Objects.equals(getClass(), other.getClass()) &&\n hasEqualProperties(other) && hasEqualChildren(other, seen);\n }\n\n /**\n * Compares the properties of two parsers.\n *\n * <p>Override this method in all subclasses that add new state.\n */\n protected boolean hasEqualProperties(Parser other) {\n return true;\n }\n\n /**\n * Compares the children of two parsers.\n *\n * <p>Normally subclasses should not override this method, but instead {@link\n * #getChildren()}.\n */\n protected boolean hasEqualChildren(Parser other, Set<Parser> seen) {\n List<Parser> thisChildren = this.getChildren();\n List<Parser> otherChildren = other.getChildren();\n if (thisChildren.size() != otherChildren.size()) {\n return false;\n }\n for (int i = 0; i < thisChildren.size(); i++) {\n if (!thisChildren.get(i).isEqualTo(otherChildren.get(i), seen)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns a list of directly referring parsers.\n */\n public List<Parser> getChildren() {\n return Collections.emptyList();\n }\n\n /**\n * Replaces the referring parser {@code source} with {@code target}. Does\n * nothing if the parser does not exist.\n */\n public void replace(Parser source, Parser target) {\n // no referring parsers\n }\n\n /**\n * Returns a human readable string identifying this parser.\n */\n public String toString() {\n return getClass().getSimpleName();\n }\n}" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.petitparser.grammar.xml.ast.XmlAttribute; import org.petitparser.grammar.xml.ast.XmlDocument; import org.petitparser.grammar.xml.ast.XmlElement; import org.petitparser.grammar.xml.ast.XmlName; import org.petitparser.grammar.xml.ast.XmlNode; import org.petitparser.parser.Parser; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects;
+ " <xsd:element name=\"USPrice\" type=\"xsd:decimal\"/>\n" + " <xsd:element ref=\"comment\" minOccurs=\"0\"/>\n" + " <xsd:element name=\"shipDate\" type=\"xsd:date\" minOccurs=\"0\"/>\n" + " </xsd:sequence>\n" + " <xsd:attribute name=\"partNum\" type=\"SKU\" use=\"required\"/>\n" + " </xsd:complexType>\n" + " </xsd:element>\n" + " </xsd:sequence>\n" + " </xsd:complexType>\n" + "\n" + " <!-- Stock Keeping Unit, a code for identifying products -->\n" + " <xsd:simpleType name=\"SKU\">\n" + " <xsd:restriction base=\"xsd:string\">\n" + " <xsd:pattern value=\"\\d{3}-[A-Z]{2}\"/>\n" + " </xsd:restriction>\n" + " </xsd:simpleType>\n" + "\n" + "</xsd:schema>"); } @Test public void testAtom() { assertParseInvariant("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<app:service>" + "<app:workspace>" + "<cmisra:repositoryInfo xmlns:ns3=\"http://docs.oasis-open.org/ns/cmis/messaging/200908/\">" + "</cmisra:repositoryInfo>" + "</app:workspace>" + "</app:service>"); } private void assertParseInvariant(String input) { XmlNode tree = parser.parse(input).get(); XmlNode other = parser.parse(tree.toXmlString()).get(); assertEquals(tree.toXmlString(), other.toXmlString()); assertEquals(tree, other); assertInvariants(tree); } private void assertInvariants(XmlNode anXmlNode) { assertEquivalentInvariant(anXmlNode); assertDocumentInvariant(anXmlNode); assertParentInvariant(anXmlNode); assertForwardInvariant(anXmlNode); assertBackwardInvariant(anXmlNode); assertNameInvariant(anXmlNode); assertAttributeInvariant(anXmlNode); } private void assertEquivalentInvariant(XmlNode anXmlNode) { for (XmlNode node : anXmlNode) { assertEquals(node, node); assertEquals(node.hashCode(), node.hashCode()); assertFalse(Objects.equals(node, node.getParent())); for (XmlNode child : node.getChildren()) { assertFalse(Objects.equals(node, child)); } for (XmlNode child : node.getAttributes()) { assertFalse(Objects.equals(node, child)); } } } private void assertDocumentInvariant(XmlNode anXmlNode) { XmlNode root = anXmlNode.getRoot(); for (XmlNode child : anXmlNode) { assertSame(child.getRoot(), root); assertSame(child.getDocument(), root); } XmlDocument document = (XmlDocument) anXmlNode; assertTrue(document.getChildren().contains(document.getRootElement())); } private void assertParentInvariant(XmlNode anXmlNode) { for (XmlNode node : anXmlNode) { if (node instanceof XmlDocument) { assertNull(node.getParent()); } for (XmlNode child : node.getChildren()) { assertSame(node, child.getParent()); } for (XmlNode attribute : node.getAttributes()) { assertSame(node, attribute.getParent()); } } } private void assertForwardInvariant(XmlNode anXmlNode) { for (XmlNode node : anXmlNode) { XmlNode current = node.getFirstChild(); List<XmlNode> children = new ArrayList<>(node.getChildren()); while (current != null) { assertSame(current, children.remove(0)); current = current.getNextSibling(); } assertTrue(children.isEmpty()); } } private void assertBackwardInvariant(XmlNode anXmlNode) { for (XmlNode node : anXmlNode) { XmlNode current = node.getLastChild(); List<XmlNode> children = new ArrayList<>(node.getChildren()); while (current != null) { assertSame(current, children.remove(children.size() - 1)); current = current.getPreviousSibling(); } assertTrue(children.isEmpty()); } } private void assertNameInvariant(XmlNode anXmlNode) { for (XmlNode node : anXmlNode) { if (node instanceof XmlElement) { XmlElement element = (XmlElement) node; assertNameInvariant(element.getName()); } if (node instanceof XmlAttribute) { XmlAttribute attribute = (XmlAttribute) node; assertNameInvariant(attribute.getName()); } } }
private void assertNameInvariant(XmlName anXmlName) {
3
saiba/OpenBMLParser
test/src/saiba/bml/builder/BehaviourBlockBuilderTest.java
[ "public interface BMLBehaviorAttributeExtension\n{\n /**\n * Decodes the attributes in attrMap. Once decoded, they should be removed from attrMap. The easiest way to do this is using\n * bb.getRequiredAttribute, bb.getOptionalAttribute, etc.\n * \n */\n void decodeAttributes(BehaviourBlock bb, HashMap<String, String> attrMap, XMLTokenizer tokenizer);\n \n StringBuilder appendAttributeString(StringBuilder buf, XMLFormatting fmt);\n \n /**\n * Attempts to parse the composition mechanism described by sm\n * @return the composition is successfully parsed, CoreSchedulingMechanism.UNKOWN otherwise\n */\n BMLBlockComposition handleComposition(String sm);\n \n /**\n * Get the set of other blocks this block depends upon (e.g. is appended after, activates)\n */\n Set<String> getOtherBlockDependencies();\n}", "public interface BMLBlockComposition\n{\n String getNameStart();\n}", "@Slf4j\npublic class BehaviourBlock extends BMLElement\n{\n public ArrayList<RequiredBlock> requiredBlocks;\n\n public ArrayList<ConstraintBlock> constraintBlocks;\n\n public ArrayList<Behaviour> behaviours;\n\n @Setter\n @Getter\n private String characterId = null;\n \n private ClassToInstanceMap<BMLBehaviorAttributeExtension> bmlBehaviorAttributeExtensions;\n private boolean strict = true;\n \n public BehaviourBlock(boolean strict, BMLBehaviorAttributeExtension... bmlBehaviorAttributeExtensions)\n {\n this(bmlBehaviorAttributeExtensions);\n this.strict = strict; \n }\n \n public BehaviourBlock(BMLBehaviorAttributeExtension... bmlBehaviorAttributeExtensions)\n {\n this.bmlBehaviorAttributeExtensions = MutableClassToInstanceMap.create();\n for (BMLBehaviorAttributeExtension ext : bmlBehaviorAttributeExtensions)\n {\n this.bmlBehaviorAttributeExtensions.put(ext.getClass(), ext);\n }\n requiredBlocks = new ArrayList<RequiredBlock>();\n constraintBlocks = new ArrayList<ConstraintBlock>();\n behaviours = new ArrayList<Behaviour>();\n }\n\n public void addBMLBehaviorAttributeExtension(BMLBehaviorAttributeExtension ext)\n {\n bmlBehaviorAttributeExtensions.put(ext.getClass(), ext);\n }\n\n public void addAllBMLBehaviorAttributeExtensions(Collection<BMLBehaviorAttributeExtension> exts)\n {\n for (BMLBehaviorAttributeExtension ext: exts)\n {\n addBMLBehaviorAttributeExtension(ext);\n } \n }\n\n \n @Override\n public String getBmlId()\n {\n return id;\n }\n\n private void setSyncPointBMLId(String newId, Collection<SyncPoint> syncs)\n {\n for(SyncPoint s:syncs)\n {\n if(s.getBmlId().equals(id))\n {\n s.setBMLId(newId);\n }\n setBMLId(newId, s.getRef());\n }\n }\n \n private void setBMLId(String newId, SyncRef r)\n {\n if (r != null && r.bbId.equals(id))\n {\n r.bbId = newId;\n }\n }\n\n private void setBMLId(String newId, Collection<Sync> syncs)\n {\n for (Sync sync : syncs)\n {\n if (sync.bmlId.equals(id))\n {\n sync.bmlId = newId;\n }\n setBMLId(newId, sync.ref);\n }\n }\n\n public void setBmlId(String newId)\n {\n for (Behaviour beh : behaviours)\n {\n beh.bmlId = newId;\n setSyncPointBMLId(newId,beh.getSyncPoints());\n }\n for (ConstraintBlock cb : constraintBlocks)\n {\n cb.bmlId = newId;\n for (Synchronize s : cb.synchronizes)\n {\n s.bmlId = newId;\n setBMLId(newId, s.getSyncs());\n }\n for (After a : cb.after)\n {\n a.bmlId = newId;\n setBMLId(newId, a.getRef());\n setBMLId(newId, a.getSyncs());\n }\n for (Before b : cb.before)\n {\n b.bmlId = newId;\n setBMLId(newId, b.getRef());\n setBMLId(newId, b.getSyncs());\n }\n }\n id = newId;\n }\n\n private BMLBlockComposition composition = CoreComposition.UNKNOWN;\n\n public void setComposition(BMLBlockComposition c)\n {\n composition = c;\n }\n\n public BMLBlockComposition getComposition()\n {\n return composition;\n }\n\n public BehaviourBlock(XMLTokenizer tokenizer) throws IOException\n {\n this();\n readXML(tokenizer);\n }\n\n /*\n * The XML Stag for XML encoding\n */\n private static final String XMLTAG = \"bml\";\n\n /**\n * The XML Stag for XML encoding -- use this static method when you want to see if a given\n * String equals the xml tag for this class\n */\n public static String xmlTag()\n {\n return XMLTAG;\n }\n\n /**\n * The XML Stag for XML encoding -- use this method to find out the run-time xml tag of an\n * object\n */\n @Override\n public String getXMLTag()\n {\n return XMLTAG;\n }\n\n @Override\n public StringBuilder appendAttributeString(StringBuilder buf, XMLFormatting fmt)\n {\n appendAttribute(buf, \"id\", id);\n appendAttribute(buf, \"composition\", composition.toString());\n if(characterId!=null)\n {\n appendAttribute(buf,\"characterId\",characterId);\n }\n for(BMLBehaviorAttributeExtension ext:bmlBehaviorAttributeExtensions.values())\n {\n ext.appendAttributeString(buf, fmt);\n }\n return super.appendAttributes(buf);\n }\n\n @Override\n public void decodeAttributes(HashMap<String, String> attrMap, XMLTokenizer tokenizer)\n {\n id = getRequiredAttribute(\"id\", attrMap, tokenizer);\n characterId = getOptionalAttribute(\"characterId\",attrMap, null);\n String sm = getOptionalAttribute(\"composition\", attrMap, \"MERGE\");\n \n \n composition = CoreComposition.parse(sm);\n\n for (BMLBehaviorAttributeExtension ext : bmlBehaviorAttributeExtensions.values())\n {\n ext.decodeAttributes(this, attrMap, tokenizer);\n if (composition == CoreComposition.UNKNOWN)\n {\n composition = ext.handleComposition(sm);\n }\n }\n if(!attrMap.isEmpty())\n {\n throw new XMLScanException(\"Invalid attribute(s) \"+attrMap.keySet()+\" in bml block\");\n } \n }\n\n public Set<String> getOtherBlockDependencies()\n {\n Set<String> deps = new HashSet<String>();\n for (BMLBehaviorAttributeExtension ext : bmlBehaviorAttributeExtensions.values())\n {\n deps.addAll(ext.getOtherBlockDependencies());\n }\n return deps;\n }\n\n public <E extends BMLBehaviorAttributeExtension> E getBMLBehaviorAttributeExtension(Class<E> c)\n {\n return bmlBehaviorAttributeExtensions.getInstance(c);\n }\n\n @Override\n public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt)\n {\n appendXMLStructureList(buf, fmt, requiredBlocks);\n appendXMLStructureList(buf, fmt, constraintBlocks);\n appendXMLStructureList(buf, fmt, behaviours);\n return buf;\n }\n\n @Override\n public void decodeContent(XMLTokenizer tokenizer) throws IOException\n {\n while (tokenizer.atSTag())\n {\n String tag = tokenizer.getTagName();\n if (tag.equals(RequiredBlock.xmlTag()))\n {\n RequiredBlock rb = new RequiredBlock(id, tokenizer);\n requiredBlocks.add(rb);\n behaviours.addAll(rb.behaviours);\n constraintBlocks.addAll(rb.constraintBlocks);\n continue;\n }\n if (tag.equals(ConstraintBlock.xmlTag()))\n {\n constraintBlocks.add(new ConstraintBlock(id, tokenizer));\n continue;\n }\n\n Behaviour b = BehaviourParser.parseBehaviour(id, tokenizer);\n if (b != null)\n {\n if (b.descBehaviour != null)\n {\n behaviours.add(b.descBehaviour);\n }\n else\n {\n behaviours.add(b);\n }\n }\n else\n {\n if(strict)\n {\n throw new XMLScanException(\"Invalid behavior/construct \"+tag+\" in BML block \"+getBmlId());\n }\n String skippedContent = tokenizer.getXMLSection();\n log.info(\"skipped content: {}\", skippedContent);\n }\n }\n } \n\n /**\n * Recursively calls resolveIDs(Scheduler, Breadcrumb) on top level behaviours and on\n * required-blocks.\n */\n public void registerElementsById(BMLParser scheduler)\n {\n // Add this behaviour block.\n scheduler.registerBMLElement(this);\n\n // Register top level behaviours.\n for (Behaviour b : behaviours)\n b.registerElementsById(scheduler);\n }\n\n public void constructConstraints(BMLParser scheduler)\n {\n // Top level behaviours.\n for (Behaviour b : behaviours)\n {\n b.constructConstraints(scheduler);\n }\n\n // Constraint blocks.\n for (ConstraintBlock ci : constraintBlocks)\n {\n ci.constructConstraints(scheduler);\n }\n }\n \n public String toBMLString(XMLNameSpace... xmlNamespaces)\n {\n return toBMLString(ImmutableList.copyOf(xmlNamespaces)); \n }\n \n public String toBMLString(List<XMLNameSpace> xmlNamespaceList)\n {\n StringBuilder buf = new StringBuilder();\n appendXML(buf, new XMLFormatting(), xmlNamespaceList);\n return buf.toString();\n }\n}", "public enum CoreComposition implements BMLBlockComposition\n{\n UNKNOWN\n {\n @Override\n public String getNameStart()\n {\n return \"UNKNOWN\";\n }\n },\n REPLACE\n {\n @Override\n public String getNameStart()\n {\n return \"REPLACE\";\n }\n }, \n MERGE\n {\n @Override\n public String getNameStart()\n {\n return \"MERGE\";\n }\n }, \n APPEND\n {\n @Override\n public String getNameStart()\n {\n return \"APPEND\";\n }\n };\n \n public static CoreComposition parse(String input)\n {\n for(CoreComposition mech: CoreComposition.values())\n {\n if(mech.getNameStart().equals(input))\n {\n return mech;\n }\n }\n return UNKNOWN;\n } \n}", "public enum Mode\n{\n LEFT_HAND, RIGHT_HAND, BOTH_HANDS, UNSPECIFIED\n}", "public enum OffsetDirection\n{ \n NONE, RIGHT, LEFT, UP, DOWN, UPRIGHT, UPLEFT, DOWNLEFT, DOWNRIGHT, POLAR \n}", "public class SpeechBehaviour extends Behaviour\n{\n protected String content;\n\n private ArrayList<Sync> syncs = new ArrayList<Sync>();\n\n /*\n * The XML Stag for XML encoding\n */\n private static final String XMLTAG = \"speech\";\n\n /**\n * The XML Stag for XML encoding -- use this static method when you want to see if a given\n * String equals the xml tag for this class\n */\n public static String xmlTag()\n {\n return XMLTAG;\n }\n\n @Override\n public void addDefaultSyncPoints()\n {\n for (String s : getDefaultSyncPoints())\n {\n addSyncPoint(new SyncPoint(bmlId, id, s));\n }\n }\n\n private static final List<String> DEFAULT_SYNCS = ImmutableList.of(\"start\", \"end\");\n\n public static List<String> getDefaultSyncPoints()\n {\n return DEFAULT_SYNCS;\n }\n\n @Override\n public String getStringParameterValue(String name)\n {\n return super.getStringParameterValue(name);\n }\n\n @Override\n public float getFloatParameterValue(String name)\n {\n return super.getFloatParameterValue(name);\n }\n\n @Override\n public boolean specifiesParameter(String name)\n {\n return super.specifiesParameter(name);\n }\n\n public SpeechBehaviour(String bmlId, XMLTokenizer tokenizer) throws IOException\n {\n super(bmlId);\n readXML(tokenizer);\n }\n\n public SpeechBehaviour(String bmlId, String id, XMLTokenizer tokenizer) throws IOException\n {\n super(bmlId, id);\n readXML(tokenizer);\n }\n\n @Override\n public StringBuilder appendAttributeString(StringBuilder buf)\n {\n return super.appendAttributeString(buf);\n }\n\n @Override\n public void decodeAttributes(HashMap<String, String> attrMap, XMLTokenizer tokenizer)\n {\n super.decodeAttributes(attrMap, tokenizer);\n }\n\n @Override\n public boolean hasContent()\n {\n return true;\n }\n\n @Override\n public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt)\n {\n if (content != null) buf.append(\"<text>\" + content + \"</text>\");\n return super.appendContent(buf, fmt); // Description is registered at Behavior.\n }\n\n @Override\n public void decodeContent(XMLTokenizer tokenizer) throws IOException\n {\n while (!tokenizer.atETag())\n {\n if (tokenizer.atSTag(\"text\"))\n {\n SpeechText text = new SpeechText();\n text.readXML(tokenizer);\n content = text.content;\n syncs = text.syncs;\n for (Sync sync : syncs)\n {\n SyncPoint s = new SyncPoint(bmlId, id, sync.id);\n if (sync.ref != null)\n {\n try\n {\n s.setRefString(sync.ref.toString(bmlId));\n }\n catch (InvalidSyncRefException e)\n {\n throw new XMLScanException(\"\", e);\n }\n }\n addSyncPoint(s);\n }\n }\n else\n {\n super.decodeContent(tokenizer);\n }\n\n ensureDecodeProgress(tokenizer);\n }\n }\n\n /**\n * The XML Stag for XML encoding -- use this method to find out the run-time xml tag of an\n * object\n */\n @Override\n public String getXMLTag()\n {\n return XMLTAG;\n }\n\n class SpeechText extends XMLStructureAdapter\n {\n public String content = \"\";\n\n public ArrayList<Sync> syncs = new ArrayList<Sync>();\n\n @Override\n public void decodeContent(XMLTokenizer tokenizer) throws IOException\n {\n while (!tokenizer.atETag())\n {\n if (tokenizer.atSTag(\"sync\"))\n {\n Sync s = new Sync(bmlId);\n s.readXML(tokenizer);\n content = content + s.toString();\n syncs.add(s);\n }\n else if (tokenizer.atCDSect())\n {\n content = content + tokenizer.takeCDSect();\n }\n else if (tokenizer.atCharData())\n {\n content = content + tokenizer.takeCharData();\n }\n\n ensureDecodeProgress(tokenizer);\n }\n }\n\n /**\n * The XML Stag for XML encoding -- use this method to find out the run-time xml tag of an\n * object\n */\n @Override\n public String getXMLTag()\n {\n return \"text\";\n }\n\n public static final String BMLNAMESPACE = \"http://www.bml-initiative.org/bml/bml-1.0\";\n\n @Override\n public String getNamespace()\n {\n return BMLNAMESPACE;\n }\n }\n\n /**\n * @return the content\n */\n public String getContent()\n {\n return content;\n }\n\n}", "public static enum Side\n{\n LEFT, RIGHT, BOTH;\n}", "public class BMLParser\n{\n private List<BehaviourBlock> bbs;\n\n private HashMap<String, BMLElement> BMLElementsById;\n\n private List<Constraint> constraints;\n private List<AfterConstraint> afterConstraints = new ArrayList<AfterConstraint>();\n private List<Constraint> requiredConstraints = new ArrayList<Constraint>();\n private List<AfterConstraint> requiredAfterConstraints = new ArrayList<AfterConstraint>();\n\n public List<AfterConstraint> getRequiredAfterConstraints()\n {\n return requiredAfterConstraints;\n }\n\n public List<Constraint> getRequiredConstraints()\n {\n return requiredConstraints;\n }\n\n private static Logger logger = LoggerFactory.getLogger(BMLParser.class.getName());\n\n private final ImmutableSet<Class<? extends BMLBehaviorAttributeExtension>> behaviorAttributeExtensions;\n\n public BMLParser(ImmutableSet<Class<? extends BMLBehaviorAttributeExtension>> behaviorAttributeExtensions)\n {\n this.behaviorAttributeExtensions = behaviorAttributeExtensions;\n bbs = new ArrayList<BehaviourBlock>();\n BMLElementsById = new HashMap<String, BMLElement>();\n constraints = new ArrayList<Constraint>();\n }\n\n public BMLParser()\n {\n this(new ImmutableSet.Builder<Class<? extends BMLBehaviorAttributeExtension>>().build());\n }\n\n /**\n * Create a new behaviour block with the registered BMLBehaviorAttributeExtensions\n */\n public BehaviourBlock createBehaviourBlock() throws InstantiationException, IllegalAccessException\n {\n List<BMLBehaviorAttributeExtension> attrList = new ArrayList<BMLBehaviorAttributeExtension>();\n for (Class<? extends BMLBehaviorAttributeExtension> bbClass : behaviorAttributeExtensions)\n {\n attrList.add(bbClass.newInstance());\n }\n return new BehaviourBlock(attrList.toArray(new BMLBehaviorAttributeExtension[attrList.size()]));\n }\n\n /** clear all behaviors from the scheduler */\n public void clear()\n {\n bbs.clear();\n BMLElementsById.clear();\n constraints.clear();\n }\n\n private BehaviourBlock getBehaviourBlock(String bmlId)\n {\n for (BehaviourBlock bb : getBehaviourBlocks())\n {\n if (bb.getBmlId().equals(bmlId)) return bb;\n }\n return null;\n }\n\n public Behaviour getBehaviour(String bmlId, String behId)\n {\n BehaviourBlock bb = getBehaviourBlock(bmlId);\n if (bb == null) return null;\n for (Behaviour b : bb.behaviours)\n {\n if (b.id != null)\n {\n if (b.id.equals(behId)) return b;\n }\n }\n return null;\n }\n\n private List<Constraint> getSoftConstraints(String bmlId, String behId)\n {\n List<Constraint> constr = new ArrayList<Constraint>();\n for (Constraint c : getConstraints(bmlId, behId))\n {\n if (!c.isHard())\n {\n constr.add(c);\n }\n }\n return constr;\n }\n\n public List<Constraint> getConstraints(String bmlId, String behId)\n {\n List<Constraint> constr = new ArrayList<Constraint>();\n for (Constraint c : getConstraints())\n {\n if (c.containsBehaviour(bmlId, behId))\n {\n constr.add(c);\n }\n }\n return constr;\n }\n\n private List<Behaviour> getBehaviours(Constraint c)\n {\n List<Behaviour> behs = new ArrayList<Behaviour>();\n for (SyncPoint s : c.getTargets())\n {\n if (s.getBehaviourId() != null)\n {\n behs.add(getBehaviour(s.getBmlId(), s.getBehaviourId()));\n }\n }\n return behs;\n }\n\n public List<List<Behaviour>> getUngroundedLoops(String bmlId, String behId)\n {\n List<List<Behaviour>> list = new ArrayList<List<Behaviour>>();\n Behaviour currentBeh = getBehaviour(bmlId, behId);\n List<Constraint> constraints = getSoftConstraints(bmlId, behId);\n for (Constraint c : constraints)\n {\n List<Behaviour> behs = getBehaviours(c);\n behs.remove(currentBeh);\n for (Behaviour beh : behs)\n {\n if (!directGround(beh.getBmlId(), beh.id))\n {\n ArrayList<Constraint> checkedC = new ArrayList<Constraint>();\n checkedC.add(c);\n getUngroundedLoops(currentBeh, beh, new ArrayList<Behaviour>(), checkedC, list);\n }\n }\n }\n List<List<Behaviour>> listNoDuplicates = new ArrayList<List<Behaviour>>();\n {\n for (List<Behaviour> behList : list)\n {\n if (!listNoDuplicates.contains(behList))\n {\n Collections.reverse(behList);\n listNoDuplicates.add(behList);\n }\n }\n }\n return listNoDuplicates;\n }\n\n private void getUngroundedLoops(Behaviour loopBeh, Behaviour currentBeh, List<Behaviour> checkedBehaviours,\n List<Constraint> checkedConstraints, List<List<Behaviour>> pathList)\n {\n List<Constraint> constraints = getSoftConstraints(currentBeh.getBmlId(), currentBeh.id);\n ArrayList<Behaviour> checkedBeh = new ArrayList<Behaviour>(checkedBehaviours);\n checkedBeh.add(currentBeh);\n constraints.removeAll(checkedConstraints);\n for (Constraint c : constraints)\n {\n List<Behaviour> behs = getBehaviours(c);\n behs.removeAll(checkedBeh);\n for (Behaviour beh : behs)\n {\n if (beh == loopBeh)\n {\n pathList.add(checkedBeh);\n }\n else if (!directGround(beh.getBmlId(), beh.id))\n {\n ArrayList<Constraint> checkedC = new ArrayList<Constraint>(checkedConstraints);\n checkedC.add(c);\n getUngroundedLoops(loopBeh, beh, checkedBeh, checkedC, pathList);\n }\n }\n }\n }\n\n public boolean isConnected(String bmlId1, String behId1, String bmlId2, String behId2, Set<Behaviour> checkedBehaviours)\n {\n if (directLink(bmlId1, behId1, bmlId2, behId2)) return true;\n\n Set<Behaviour> linkedBehaviours = new HashSet<Behaviour>();\n for (Constraint c : getConstraints())\n {\n for (SyncPoint s : c.getTargets())\n {\n if (s.getBehaviourId() == null) continue;\n if (s.getBehaviourId().equals(behId1) && s.getBmlId().equals(bmlId1))\n {\n linkedBehaviours.addAll(getBehaviours(c));\n continue;\n }\n }\n }\n linkedBehaviours.removeAll(checkedBehaviours);\n\n for (Behaviour b : linkedBehaviours)\n {\n checkedBehaviours.add(b);\n if (isConnected(b.getBmlId(), b.id, bmlId2, behId2, checkedBehaviours))\n {\n return true;\n }\n }\n return false;\n }\n\n public boolean isGrounded(String bmlId, String behId, Set<Behaviour> checkedBehaviours)\n {\n if (directGround(bmlId, behId)) return true;\n\n Set<Behaviour> linkedBehaviours = new HashSet<Behaviour>();\n for (Constraint c : getConstraints())\n {\n for (SyncPoint s : c.getTargets())\n {\n if (s.getBehaviourId() == null) continue;\n if (s.getBehaviourId().equals(behId) && s.getBmlId().equals(bmlId))\n {\n linkedBehaviours.addAll(getBehaviours(c));\n continue;\n }\n }\n }\n linkedBehaviours.removeAll(checkedBehaviours);\n\n for (Behaviour b : linkedBehaviours)\n {\n checkedBehaviours.add(b);\n if (isGrounded(b.getBmlId(), b.id, checkedBehaviours))\n {\n return true;\n }\n }\n return false;\n }\n\n public boolean isConnected(String bmlId1, String behId1, String bmlId2, String behId2)\n {\n return isConnected(bmlId1, behId1, bmlId2, behId2, new HashSet<Behaviour>());\n }\n\n public boolean isGrounded(String bmlId, String behId)\n {\n return isGrounded(bmlId, behId, new HashSet<Behaviour>());\n }\n\n /**\n * Behaviour b1 and b2 are connected with an at constraints\n */\n public boolean directLink(String bmlId1, String behId1, String bmlId2, String behId2)\n {\n for (Constraint c : getConstraints())\n {\n boolean containsB1 = false;\n boolean containsB2 = false;\n for (SyncPoint s : c.getTargets())\n {\n if (s.getBehaviourId() == null) continue;\n if (s.getBehaviourId().equals(behId1) && s.getBmlId().equals(bmlId1)) containsB1 = true;\n if (s.getBehaviourId().equals(behId2) && s.getBmlId().equals(bmlId2)) containsB2 = true;\n }\n if (containsB1 && containsB2) return true;\n }\n return false;\n }\n\n public boolean directGround(String bmlId1, String behId1)\n {\n for (Constraint c : getConstraints())\n {\n boolean isGrounded = false;\n boolean containsB1 = false;\n for (SyncPoint s : c.getTargets())\n {\n if (s.getBehaviourId() == null) isGrounded = true;\n else if (s.getBehaviourId().equals(behId1) && s.getBmlId().equals(bmlId1)) containsB1 = true;\n }\n if (containsB1 && isGrounded) return true;\n }\n return false;\n }\n\n public boolean directAfterGround(String bmlId1, String behId1)\n {\n for (AfterConstraint c : getAfterConstraints())\n {\n if (c.getRef().getBehaviourId() == null)\n {\n for (SyncPoint s : c.getTargets())\n {\n if (s.getBehaviourId().equals(behId1) && s.getBmlId().equals(bmlId1))\n {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n * Adds a behavior block.\n * \n * @param bb\n */\n public void addBehaviourBlock(BehaviourBlock bb)\n {\n bb.registerElementsById(this);\n constructConstraints(bb);\n bbs.add(bb);\n\n logger.debug(\"List of constraints: \");\n for (Constraint constraint : constraints)\n {\n logger.debug(\"\\t {}\", constraint);\n }\n }\n\n /**\n * This method constructs constraints synchronization points. The source SyncPoint are directly\n * known to each Behavior, while the target SyncPoint are constructed from the literal\n * references in them.\n * \n * @param bb\n */\n private void constructConstraints(BehaviourBlock bb)\n {\n bb.constructConstraints(this);\n unifyConstraints(); \n }\n\n private void unifyConstraints()\n {\n ArrayList<Constraint> cNewList = new ArrayList<Constraint>();\n\n double relOffset = 0;\n\n // merge constraints that share the same behavior sync with different offsets\n for (Constraint cOld : constraints)\n {\n boolean merged = false;\n Constraint cMerge = null;\n SyncPoint cSyncOld = null;\n\n // can be merged?\n for (SyncPoint syncOld : cOld.getTargets())\n {\n for (Constraint cNew : cNewList)\n {\n for (SyncPoint syncNew : cNew.getTargets())\n {\n if (syncOld.equalsPoint(syncNew))\n {\n // merge cOld into cNew\n relOffset = syncNew.getOffset() - syncOld.getOffset();\n merged = true;\n cMerge = cNew;\n cSyncOld = syncOld;\n break;\n }\n }\n if (merged) break;\n }\n }\n\n if (merged)\n {\n for (SyncPoint syncOld : cOld.getTargets())\n {\n if (syncOld != cSyncOld)\n {\n SyncPoint sNew = new SyncPoint(syncOld);\n sNew.offset += relOffset;\n cMerge.addTarget(sNew);\n sNew.setConstraint(cMerge);\n }\n }\n }\n if (!merged)\n {\n cNewList.add(cOld);\n }\n }\n constraints = cNewList;\n }\n\n public void constructConstraints(Behaviour behaviour)\n {\n // For each of the SyncPoints with a reference, construct the foreign SyncPoint\n ImmutableList<SyncPoint> syncPoints = ImmutableList.copyOf(behaviour.getSyncPoints());\n for (SyncPoint syncPoint : syncPoints)\n {\n String ref = syncPoint.getRefString();\n if (ref == null || ref.isEmpty()) continue; // Empty SyncPoint reference. No constraint needed.\n SyncPoint foreignSyncPoint;\n try\n {\n foreignSyncPoint = syncPoint.getForeignSyncPoint(this);\n constructConstraint(syncPoint, foreignSyncPoint, false);\n }\n catch (MissingSyncPointException e)\n {\n System.err.println(e.getMessage());\n }\n }\n }\n\n public void constructConstraints(Before before)\n {\n SyncRef rightRef = before.getRef();\n double rightOffset = rightRef.offset; \n for (Sync sync : before.getSyncs())\n {\n SyncPoint syncRef = new SyncPoint(sync.getBmlId(), sync.ref);\n double refOffset = syncRef.getRef().offset;\n syncRef.getRef().offset = 0;\n \n rightRef.offset = rightOffset-refOffset;\n SyncPoint syncRight = new SyncPoint(sync.getBmlId(), rightRef);\n SyncPoint right = syncRight.getForeignSyncPoint(this); \n \n SyncPoint ref = syncRef.getForeignSyncPoint(this);\n constructAfterConstraint(ref, right, before.isRequired());\n }\n }\n\n public void constructConstraints(After after)\n {\n double refOffset = after.getRef().offset;\n SyncPoint syncRef = new SyncPoint(after.getBmlId(), after.getRef());\n syncRef.getRef().offset = 0;\n SyncPoint ref = syncRef.getForeignSyncPoint(this);\n\n for (Sync sync : after.getSyncs())\n {\n syncRef = new SyncPoint(sync.getBmlId(), sync.ref);\n syncRef.getRef().offset -= refOffset;\n SyncPoint right = syncRef.getForeignSyncPoint(this);\n constructAfterConstraint(ref, right, after.isRequired());\n }\n }\n\n public void constructConstraints(Synchronize synchronize)\n {\n SyncPoint left = null;\n for (Sync sync : synchronize.getSyncs())\n {\n SyncPoint syncRef = new SyncPoint(synchronize.bmlId, sync.ref);\n SyncPoint right = syncRef.getForeignSyncPoint(this);\n if (left == null)\n {\n left = right;\n }\n else\n {\n constructConstraint(left, right, synchronize.isRequired());\n }\n }\n }\n\n public void constructAfterConstraint(SyncPoint ref, SyncPoint target, List<AfterConstraint> constraints)\n {\n AfterConstraint constraint;\n if (constraints.contains(ref.getAfterConstraint()))\n {\n constraint = ref.getAfterConstraint();\n }\n else\n {\n constraint = new AfterConstraint(ref);\n ref.setAsRefForAfterConstraint(constraint);\n constraints.add(constraint);\n }\n constraint.addTarget(target);\n }\n\n public void constructAfterConstraint(SyncPoint ref, SyncPoint target, boolean required)\n {\n constructAfterConstraint(ref, target, afterConstraints);\n if (required)\n {\n constructAfterConstraint(ref, target, requiredAfterConstraints);\n }\n }\n\n public void constructConstraint(SyncPoint left, SyncPoint right, boolean required)\n {\n constructConstraint(left, right, constraints);\n if (required)\n {\n constructConstraint(left, right, requiredConstraints);\n }\n }\n\n private void constructConstraint(SyncPoint left, SyncPoint right, List<Constraint> constraints)\n {\n Constraint constraint;\n\n if (constraints.contains(right.getConstraint()) && constraints.contains(left.getConstraint()))\n {\n // Both are in a constraint. Merge them.\n Constraint masterConstraint = left.getConstraint();\n Constraint slaveConstraint = right.getConstraint();\n ArrayList<SyncPoint> targets = slaveConstraint.getTargets();\n for (SyncPoint target : targets)\n {\n target.setConstraint(masterConstraint);\n masterConstraint.addTarget(target);\n }\n constraints.remove(slaveConstraint);\n }\n else if (constraints.contains(right.getConstraint()))\n {\n constraint = right.getConstraint();\n constraint.addTarget(left);\n left.setConstraint(constraint);\n }\n else if (constraints.contains(left.getConstraint()))\n {\n constraint = left.getConstraint();\n constraint.addTarget(right);\n right.setConstraint(constraint);\n }\n else\n {\n constraint = new Constraint(left, right);\n left.setConstraint(constraint);\n right.setConstraint(constraint);\n constraints.add(constraint);\n }\n }\n\n public void registerBMLElement(BMLElement element)\n {\n if (element.id == null) return;\n\n String fullId = element.getBmlId() + \":\" + element.id;\n\n logger.debug(\"Registering {} ({}) \", element.getClass().toString(), fullId);\n\n if (BMLElementsById.containsKey(fullId))\n {\n logger.warn(\"fullId {} not unique\", fullId);\n }\n else\n {\n BMLElementsById.put(fullId, element);\n }\n }\n\n public BMLElement getBMLElementById(String id)\n {\n return BMLElementsById.get(id);\n }\n\n /**\n * @return the constraints\n */\n public List<Constraint> getConstraints()\n {\n return constraints;\n }\n\n public List<AfterConstraint> getAfterConstraints()\n {\n return afterConstraints;\n }\n\n /**\n * Herwin: a bit of a hack, gets the behaviors in order of XML processing, to be used for\n * SmartBody reference scheduler\n */\n public List<Behaviour> getBehaviours()\n {\n ArrayList<Behaviour> behs = new ArrayList<Behaviour>();\n for (BehaviourBlock bb : bbs)\n {\n behs.addAll(bb.behaviours);\n }\n return behs;\n }\n\n /**\n * @return the bbs\n */\n public List<BehaviourBlock> getBehaviourBlocks()\n {\n return bbs;\n }\n\n private Set<String> getLinkDependencies(String bmlId)\n {\n Set<String> dependencies = new HashSet<String>();\n\n for (Constraint c : getConstraints())\n {\n Set<String> ldeps = new HashSet<String>();\n for (SyncPoint sp : c.getTargets())\n {\n ldeps.add(sp.getBmlId());\n }\n if (ldeps.contains(bmlId))\n {\n dependencies.addAll(ldeps);\n }\n }\n dependencies.remove(bmlId);\n return dependencies;\n }\n\n private Set<String> getLinkAfterDependencies(String bmlId)\n {\n Set<String> dependencies = new HashSet<String>();\n for (AfterConstraint c : getAfterConstraints())\n {\n Set<String> ldeps = new HashSet<String>();\n for (SyncPoint sp : c.getTargets())\n {\n ldeps.add(sp.getBmlId());\n }\n ldeps.add(c.getRef().getBmlId());\n if (ldeps.contains(bmlId))\n {\n dependencies.addAll(ldeps);\n }\n }\n\n dependencies.remove(bmlId);\n return dependencies;\n }\n\n private Set<String> getBlockDependencies(String bmlId)\n {\n for (BehaviourBlock bb : getBehaviourBlocks())\n {\n if (bb.getBmlId().equals(bmlId))\n {\n return bb.getOtherBlockDependencies();\n }\n }\n return ImmutableSet.of();\n }\n\n private Set<String> getBehaviourDependencies(String bmlId)\n {\n Set<String> dependencies = new HashSet<String>();\n for (Behaviour b : getBehaviours())\n {\n if (b.getBmlId().equals(bmlId))\n {\n dependencies.addAll(b.getOtherBlockDependencies());\n }\n }\n return dependencies;\n }\n\n /**\n * Get the BML blocks bmlId depends upon\n */\n public Set<String> getDependencies(String bmlId)\n {\n Set<String> dependencies = new HashSet<String>();\n dependencies.addAll(getLinkDependencies(bmlId));\n dependencies.addAll(getLinkAfterDependencies(bmlId));\n dependencies.addAll(getBlockDependencies(bmlId));\n dependencies.addAll(getBehaviourDependencies(bmlId));\n return dependencies;\n }\n}" ]
import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import hmi.xml.XMLFormatting; import hmi.xml.XMLStructureAdapter; import hmi.xml.XMLTokenizer; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import lombok.Getter; import lombok.Setter; import org.junit.Test; import saiba.bml.core.BMLBehaviorAttributeExtension; import saiba.bml.core.BMLBlockComposition; import saiba.bml.core.BehaviourBlock; import saiba.bml.core.CoreComposition; import saiba.bml.core.Mode; import saiba.bml.core.OffsetDirection; import saiba.bml.core.SpeechBehaviour; import saiba.bml.core.ext.FaceFacsBehaviour.Side; import saiba.bml.parser.BMLParser;
package saiba.bml.builder; /** * Unit tests for the BehaviourBlockBuilder * @author hvanwelbergen * */ public class BehaviourBlockBuilderTest { private static final double PARAM_PRECISION = 0.001; private BehaviourBlockBuilder builder = new BehaviourBlockBuilder(); @Test public void buildEmptyBlock() { BehaviourBlock bb = builder.build(); assertNotNull(bb.id); assertEquals(CoreComposition.MERGE, bb.getComposition()); } @Test public void checkDefaultCompositionOutput() { BehaviourBlock bbOut = builder.build(); StringBuilder buf = new StringBuilder(); bbOut.appendXML(buf); BehaviourBlock bbIn = new BehaviourBlock(); bbIn.readXML(buf.toString());
BMLParser parser = new BMLParser();
8
jachness/blockcalls
app/src/androidTest/java/com/jachness/blockcalls/services/ContactCheckerTest.java
[ "public abstract class AndroidTest {\n private Context targetContext;\n private AllComponentTest component;\n private AppPreferences appPreferences;\n private Context context;\n\n protected void setUp() throws Exception {\n targetContext = InstrumentationRegistry.getTargetContext();\n context = InstrumentationRegistry.getContext();\n component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))\n .appModule(new AppModule(targetContext))\n .dAOModule(new DAOModule(targetContext)).build();\n appPreferences = new AppPreferences(targetContext);\n }\n\n protected Context getTargetContext() {\n return targetContext;\n }\n\n protected AllComponentTest getComponent() {\n return component;\n }\n\n protected AppPreferences getAppPreferences() {\n return appPreferences;\n }\n\n public Context getContext() {\n return context;\n }\n}", "public class ContactDAO {\n private final Context context;\n\n public ContactDAO(Context context) {\n this.context = context;\n }\n\n @DebugLog\n public String[] findContact(String number) {\n Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri\n .encode(number));\n Cursor cursor = context.getContentResolver().query(uri,\n new String[]{ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup\n .DISPLAY_NAME},\n null, null, null);\n\n try {\n String contact[] = null;\n if (cursor != null && cursor.moveToNext()) {\n int displayNameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup\n .DISPLAY_NAME);\n int numberIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.NUMBER);\n contact = new String[]{cursor.getString(numberIndex), cursor.getString\n (displayNameIndex)};\n }\n return contact;\n } finally {\n Util.close(cursor);\n }\n }\n}", "public class PhoneNumberException extends Exception {\n\n public PhoneNumberException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public class TooShortNumberException extends Exception {\n public static final int MINIMUM_LENGTH = 3;\n\n public TooShortNumberException(String message) {\n super(message);\n }\n}", "@SuppressWarnings(\"SameParameterValue\")\npublic class AppPreferences {\n\n public static final String ALLOW_ONLY_CONTACTS = \"allow_only_contacts_key\";\n public static final String BLOCKING_ENABLED = \"blocking_enabled\";\n public static final String LESSON_1 = \"lesson_1\";\n public static final String DEFAULT_QCK = \"\";\n private static final String PROTECTED_APPS_MESSAGE = \"protected_apps_message\";\n private static final String BLOCK_PRIVATE_NUMBERS = \"block_private_numbers_key\";\n private static final String ENABLE_BLACK_LIST = \"enable_black_list_key\";\n private static final String FIRST_TIME = \"first_time_key\";\n private static final String FIRST_TIME_PHONE_PERM = \"first_time_phone_perm_key\";\n private static final String ENABLE_LOG = \"enable_log_key\";\n private static final String NOTIFICATION_BLOCKED_CALL = \"notification_blocked_call\";\n private static final String QUICK = \"quick\";\n private static final boolean DEFAULT_FIR = true;\n private static final boolean DEFAULT_BUN = false;\n private static final boolean DEFAULT_AOC = false;\n private static final boolean DEFAULT_EBL = true;\n private static final boolean DEFAULT_EL = true;\n private static final boolean DEFAULT_BE = true;\n private static final boolean DEFAULT_NBC = true;\n private static final boolean DEFAULT_FTPP = true;\n private static final boolean DEFAULT_L1 = false;\n private static final boolean DEFAULT_PAM = true;\n private final Context context;\n\n public AppPreferences(Context context) {\n this.context = context;\n }\n\n public boolean isAllowOnlyContacts() {\n return get(ALLOW_ONLY_CONTACTS, DEFAULT_AOC);\n }\n\n public void setAllowOnlyContacts(boolean allowOnlyContacts) {\n set(ALLOW_ONLY_CONTACTS, allowOnlyContacts);\n }\n\n public boolean isBlockPrivateNumbers() {\n return get(BLOCK_PRIVATE_NUMBERS, DEFAULT_BUN);\n }\n\n public void setBlockPrivateNumbers(boolean blockPrivateNumbers) {\n set(BLOCK_PRIVATE_NUMBERS, blockPrivateNumbers);\n }\n\n public boolean isEnableBlackList() {\n return get(ENABLE_BLACK_LIST, DEFAULT_EBL);\n }\n\n public void setEnableBlackList(boolean enableBlackList) {\n set(ENABLE_BLACK_LIST, enableBlackList);\n }\n\n public boolean isFirstTime() {\n return get(FIRST_TIME, DEFAULT_FIR);\n }\n\n public void setFirstTime(boolean firstTime) {\n set(FIRST_TIME, firstTime);\n }\n\n public boolean isEnableLog() {\n return get(ENABLE_LOG, DEFAULT_EL);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public void setEnableLog(boolean enableLog) {\n set(ENABLE_LOG, enableLog);\n }\n\n public boolean isBlockingEnable() {\n return get(BLOCKING_ENABLED, DEFAULT_BE);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public void setBlockingEnable(boolean enable) {\n set(BLOCKING_ENABLED, enable);\n }\n\n public boolean isNotificationBlockedCall() {\n return get(NOTIFICATION_BLOCKED_CALL, DEFAULT_NBC);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public void setNotificationBlockedCall(boolean enable) {\n set(NOTIFICATION_BLOCKED_CALL, enable);\n }\n\n public boolean isFirstTimePhonePerm() {\n return get(FIRST_TIME_PHONE_PERM, DEFAULT_FTPP);\n }\n\n public void setFirstTimePhonePerm(boolean enable) {\n set(FIRST_TIME_PHONE_PERM, enable);\n }\n\n public boolean isLesson1() {\n return get(LESSON_1, DEFAULT_L1);\n }\n\n public void setLesson1(boolean enable) {\n set(LESSON_1, enable);\n }\n\n public String getQuick() {\n return get(QUICK, DEFAULT_QCK);\n }\n\n public void setQuick(String number) {\n set(QUICK, number);\n }\n\n public boolean isShowProtectedAppsMessage() {\n return get(PROTECTED_APPS_MESSAGE, DEFAULT_PAM);\n }\n\n public void setShowProtectedAppsMessage(boolean show) {\n set(PROTECTED_APPS_MESSAGE, show);\n }\n\n\n @DebugLog\n private void set(String key, boolean value) {\n PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value)\n .apply();\n }\n\n @DebugLog\n private void set(String key, String value) {\n PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value)\n .apply();\n }\n\n @DebugLog\n private boolean get(String key, boolean defaultValue) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defaultValue);\n }\n\n @DebugLog\n private String get(String key, String defaultValue) {\n return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defaultValue);\n }\n\n @SuppressLint(\"CommitPrefEdits\")\n public void deleteAll() {\n PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit();\n }\n\n public void setAllDefaults() {\n this.setBlockPrivateNumbers(DEFAULT_BUN);\n this.setAllowOnlyContacts(DEFAULT_AOC);\n this.setEnableBlackList(DEFAULT_EBL);\n this.setEnableLog(DEFAULT_EL);\n this.setBlockingEnable(DEFAULT_BE);\n this.setNotificationBlockedCall(DEFAULT_NBC);\n }\n}", "public enum BlockOrigin {\n PRIVATE, CONTACTS, BLACK_LIST\n}" ]
import android.content.ContentProviderOperation; import android.content.Context; import android.content.OperationApplicationException; import android.os.RemoteException; import android.provider.ContactsContract; import android.support.test.InstrumentationRegistry; import android.support.test.filters.SmallTest; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import com.google.i18n.phonenumbers.NumberParseException; import com.jachness.blockcalls.AndroidTest; import com.jachness.blockcalls.db.dao.ContactDAO; import com.jachness.blockcalls.exceptions.PhoneNumberException; import com.jachness.blockcalls.exceptions.TooShortNumberException; import com.jachness.blockcalls.stuff.AppPreferences; import com.jachness.blockcalls.stuff.BlockOrigin; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; import javax.inject.Inject;
package com.jachness.blockcalls.services; @RunWith(AndroidJUnit4.class) @SmallTest public class ContactCheckerTest extends AndroidTest { private static final String TAG = ContactCheckerTest.class.getSimpleName(); @Inject ContactChecker checker; @Inject
ContactDAO contactDAO;
1
domax/gwt-dynamic-plugins
gwt-dynamic-main/gwt-dynamic-host/src/main/java/org/gwt/dynamic/host/client/features/ModuleInfoFeatureConsumer.java
[ "public static native String toStringJSO(JavaScriptObject jso) /*-{\n\treturn JSON.stringify(jso);\n}-*/;", "public interface FeatureCommonConst {\n\n\tString MODULE_HOST = \"gwt-dynamic-host\";\n\t\n\tString FEATURE_MODULE_READY = \"moduleReady\";\n\tString FEATURE_BUSY = \"busy\";\n\tString FEATURE_NAVIGATOR_ITEM = \"navigatorItem\";\n\tString FEATURE_CONTENT = \"moduleContent\";\n}", "public abstract class FeatureConsumer<A, R> extends AbstractFeature<A, R> {\n\n\tprivate static final Logger LOG = Logger.getLogger(FeatureConsumer.class.getName());\n\t\n\t@Override\n\tpublic void call(A arguments, AsyncCallback<R> callback) {\n\t\tString moduleName = getModuleName();\n\t\tString type = getType();\n\t\tLOG.fine(\"FeatureConsumer.call: moduleName=\" + moduleName + \"; type=\" + type + \"; arguments=\" + arguments);\n\t\tif (isRegistered())\n\t\t\tdoCall(moduleName, type, arguments, new ConsumerCallback<R>(callback));\n\t\telse if (callback != null) callback.onFailure(\n\t\t\t\tnew RuntimeException(\"feature not supported: moduleName=\" + moduleName + \"; type=\" + type));\n\t}\n\n\tprivate native void doCall(String moduleName, String featureName, A arguments, ConsumerCallback<R> callback) /*-{\n\t\tvar f = $wnd.__features[moduleName][featureName];\n\t\tf.callFunction.call(f.context, arguments,\n\t\t\tfunction (error) {\n\t\t\t\tcallback.@org.gwt.dynamic.common.client.features.ConsumerCallback::onFailure(Ljava/lang/String;).call(callback, error);\n\t\t\t},\n\t\t\tfunction (result) {\n\t\t\t\tcallback.@org.gwt.dynamic.common.client.features.ConsumerCallback::onSuccess(Ljava/lang/Object;).call(callback, result);\n\t\t\t});\n\t}-*/;\t\n}", "public class ModuleInfo extends JavaScriptObject {\n\n\tpublic static final ModuleInfo create() {\n\t\treturn JavaScriptObject.createObject().cast();\n\t}\n\t\n\tpublic static final ModuleInfo create(String name, String caption, String description) {\n\t\tModuleInfo result = create();\n\t\tresult.setName(name);\n\t\tresult.setCaption(caption);\n\t\tresult.setDescription(description);\n\t\treturn result;\n\t}\n\t\n\tprotected ModuleInfo() {}\n\t\n\tpublic final native String getName() /*-{\n\t\treturn this.name;\n\t}-*/;\n\t\n\tpublic final native void setName(String name) /*-{\n\t\tthis.name = name;\n\t}-*/; \n\n\tpublic final native String getCaption() /*-{\n\t\treturn this.caption;\n\t}-*/;\n\t\n\tpublic final native void setCaption(String caption) /*-{\n\t\tthis.caption = caption;\n\t}-*/; \n\n\tpublic final native String getDescription() /*-{\n\t\treturn this.description;\n\t}-*/;\n\t\n\tpublic final native void setDescription(String description) /*-{\n\t\tthis.description = description;\n\t}-*/; \n}", "public abstract class BatchRunner {\n\n\tprivate static final Logger LOG = Logger.getLogger(BatchRunner.class.getName());\n\n\t/**\n\t * Defines the command processing modes that {@link BatchRunner} supports.\n\t */\n\tpublic enum Mode {\n\n\t\t/**\n\t\t * Batch runner will try to launch all commands in queue at once, in parallel if possible.\n\t\t */\n\t\tPARALLEL,\n\n\t\t/**\n\t\t * Batch runner will try to launch commands in order they placed in queue. Commands are processed sequentially -\n\t\t * next command will wait while previous one will be finished.\n\t\t */\n\t\tSEQUENTIAL\n\t}\n\t\n\t/**\n\t * Defines {@link BatchRunner}'s command that should be invoked in parallel.\n\t */\n\tpublic static interface Command extends AsyncCallback<Void> {\n\t\t\n\t\t/**\n\t\t * Starts any kind of asynchronous code that should be defined in this method.\n\t\t * \n\t\t * @param callback\n\t\t * A resulting callback that custom async code should use to inform runner about success and failure.\n\t\t */\n\t\tvoid run(AsyncCallback<Void> callback);\n\t}\n\n\tabstract public static class CommandSimple implements Command {\n\n\t\t@Override\n\t\tpublic void onSuccess(Void result) {\n\t\t\tLOG.info(\"BatchRunner.CommandSimple.onSuccess\");\n\t\t}\n\n\t\t@Override\n\t\tpublic void onFailure(Throwable caught) {\n\t\t\tLOG.severe(\"BatchRunner.CommandSimple.onFailure: \" + caught.getMessage());\n\t\t}\n\t}\n\t\n\tprivate class CommandAsyncCallback implements AsyncCallback<Void>, ScheduledCommand {\n\n\t\tprivate Command command;\n\t\t\n\t\tCommandAsyncCallback(Command command) {\n\t\t\tthis.command = command;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void onFailure(Throwable caught) {\n\t\t\tif (!commands.contains(command)) return; \n\t\t\tcommands.remove(command);\n\t\t\terrors.add(caught);\n\t\t\tcommand.onFailure(caught);\n\t\t\tonCommandFinish(command);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onSuccess(Void result) {\n\t\t\tif (!commands.contains(command)) return;\n\t\t\tcommands.remove(command);\n\t\t\tcommand.onSuccess(result);\n\t\t\tonCommandFinish(command);\n\t\t}\n\n\t\t@Override\n\t\tpublic void execute() {\n\t\t\tif (commands.contains(command)) command.run(this);\n\t\t}\n\t}\n\t\n\tprivate final List<Command> commands = new ArrayList<Command>();\n\tprivate final List<Throwable> errors = new ArrayList<Throwable>();\n\tprivate boolean running;\n\tprivate int startSize;\n\tprivate final Mode mode;\n\n\t/**\n\t * Creates batch runner with default mode {@link Mode#PARALLEL}.\n\t */\n\tpublic BatchRunner() {\n\t\tthis(null);\n\t}\n\n\tpublic BatchRunner(Mode mode) {\n\t\tthis.mode = mode == null ? Mode.PARALLEL : mode;\n\t\tLOG.info(\"BatchRunner: mode=\" + mode);\n\t}\n\t\n\t/**\n\t * Pushes new async command(s) into runner. If runner is already started then command is run instantly, otherwise it\n\t * just inserted into queue and waits for {@link BatchRunner#run()} invocation.\n\t */\n\tpublic BatchRunner add(Command... command) {\n\t\tLOG.info(\"BatchRunner.add\");\n\t\tif (!Utils.isEmpty(command))\n\t\t\tfor (Command cmd : command) {\n\t\t\t\tcommands.add(cmd);\n\t\t\t\tif (running) {\n\t\t\t\t\t++startSize;\n\t\t\t\t\tif (Mode.PARALLEL.equals(mode))\n\t\t\t\t\t\tScheduler.get().scheduleDeferred(new CommandAsyncCallback(cmd));\n\t\t\t\t}\n\t\t\t}\n\t\telse LOG.warning(\"BatchRunner.add: attempt to add an empty command set\");\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Starts commands in queue. Does nothing if process is running.\n\t */\n\tpublic void run() {\n\t\tLOG.info(\"BatchRunner.run: running=\" + running);\n\t\tif (running) return;\n\t\terrors.clear();\n\t\tif (commands.isEmpty()) {\n\t\t\tonFinish();\n\t\t\treturn;\n\t\t}\n\t\trunning = true;\n\t\tstartSize = commands.size();\n\t\tswitch (mode) {\n\t\t\tcase PARALLEL:\n\t\t\t\tfor (Command command : commands)\n\t\t\t\t\tScheduler.get().scheduleDeferred(new CommandAsyncCallback(command));\n\t\t\t\tbreak;\n\t\t\tcase SEQUENTIAL:\n\t\t\t\tScheduler.get().scheduleDeferred(new CommandAsyncCallback(commands.get(0)));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n\t * Aborts waiting for command's responses. In fact, asynchronous code, once was invoked, cannot be canceled in regular\n\t * way. So, this runner simply ignores all responses from commands that are still active.\n\t * <p>\n\t * Does nothing if process is stopped.\n\t */\n\tpublic void abort() {\n\t\tLOG.info(\"BatchRunner.abort: running=\" + running);\n\t\tif (!running) return;\n\t\trunning = false;\n\t\tcommands.clear();\n\t\tonFinish();\n\t}\n\t\n\t/**\n\t * Returns current progress as a number from 0.0 to 1.0.\n\t */\n\tpublic double getProgress() {\n\t\tLOG.info(\"BatchRunner.getProgress: running=\" + running + \"; startSize=\" + startSize + \"; size=\" + commands.size());\n\t\tif (!running || startSize == 0) return 0d;\n\t\treturn ((double) startSize - commands.size()) / startSize;\n\t}\n\t\n\t/**\n\t * Is invoked when runner completes processing all commands in queue.\n\t */\n\tpublic abstract void onFinish();\n\t\n\t/**\n\t * @return {@code true} in case if any of commands in queue fails. {@code false} otherwise.\n\t */\n\tpublic boolean hasErrors() {\n\t\treturn errors.size() > 0;\n\t}\n\t\n\t/**\n\t * Gets list of {@link Throwable}s that occurred during commands running.\n\t * \n\t * @return List of command exceptions\n\t */\n\tpublic List<Throwable> getErrors() {\n\t\treturn errors;\n\t}\n\t\n\tprivate void onCommandFinish(Command command) {\n\t\tLOG.info(\"BatchRunner.onCommandFinish\");\n\t\tif (!running) return;\n\t\tif (commands.isEmpty()) {\n\t\t\trunning = false;\n\t\t\tonFinish();\n\t\t} else if (Mode.SEQUENTIAL.equals(mode))\n\t\t\tScheduler.get().scheduleDeferred(new CommandAsyncCallback(commands.get(0)));\n\t}\n}", "abstract public static class CommandSimple implements Command {\n\n\t@Override\n\tpublic void onSuccess(Void result) {\n\t\tLOG.info(\"BatchRunner.CommandSimple.onSuccess\");\n\t}\n\n\t@Override\n\tpublic void onFailure(Throwable caught) {\n\t\tLOG.severe(\"BatchRunner.CommandSimple.onFailure: \" + caught.getMessage());\n\t}\n}", "public class ModuleBean {\n\n\tprivate String name;\n\tprivate String url;\n\n\tpublic ModuleBean() {}\n\n\tpublic ModuleBean(String name, String url) {\n\t\tthis.name = name;\n\t\tthis.url = url;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getUrl() {\n\t\treturn url;\n\t}\n\n\tpublic void setUrl(String url) {\n\t\tthis.url = url;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((url == null) ? 0 : url.hashCode());\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) return true;\n\t\tif (obj == null) return false;\n\t\tif (getClass() != obj.getClass()) return false;\n\t\tModuleBean other = (ModuleBean) obj;\n\t\tif (url == null) {\n\t\t\tif (other.url != null) return false;\n\t\t} else if (!url.equals(other.url)) return false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null) return false;\n\t\t} else if (!name.equals(other.name)) return false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder(\"ModuleBean\")\n\t\t\t\t.append(\" {name=\").append(name)\n\t\t\t\t.append(\", url=\").append(url)\n\t\t\t\t.append(\"}\").toString();\n\t}\n}" ]
import static org.gwt.dynamic.common.client.util.JsUtils.toStringJSO; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.gwt.dynamic.common.client.features.FeatureCommonConst; import org.gwt.dynamic.common.client.features.FeatureConsumer; import org.gwt.dynamic.common.client.jso.ModuleInfo; import org.gwt.dynamic.common.client.util.BatchRunner; import org.gwt.dynamic.common.client.util.BatchRunner.CommandSimple; import org.gwt.dynamic.host.shared.ModuleBean; import com.google.gwt.user.client.rpc.AsyncCallback;
/* * Copyright 2014 Maxim Dominichenko * * Licensed under The MIT License (MIT) (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * https://github.com/domax/gwt-dynamic-plugins/blob/master/LICENSE * * 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.gwt.dynamic.host.client.features; public class ModuleInfoFeatureConsumer extends FeatureConsumer<Void, ModuleInfo> implements FeatureCommonConst { private static final Logger LOG = Logger.getLogger(ModuleInfoFeatureConsumer.class.getName()); private final List<ModuleBean> modules; private final List<ModuleInfo> navigatorItems = new ArrayList<ModuleInfo>(); private String moduleName;
private class ItemCommand extends CommandSimple {
5
SergioDim3nsions/RealmContactsForAndroid
presentation/src/main/java/sergio/vasco/androidforexample/presentation/sections/main/MainPresenter.java
[ "public interface Bus {\n void post(Object object);\n void postInmediate(Object object);\n void register(Object object);\n void unregister(Object object);\n}", "public interface InteractorInvoker {\n void execute(Interactor interactor);\n void execute(Interactor interactor, InteractorPriority priority);\n}", "public class GetContactsFromDataBaseInteractor implements Interactor {\n\n private Bus bus;\n private GetContactsEvent event;\n private ContactsRepository contactsRepository;\n\n public GetContactsFromDataBaseInteractor(Bus bus, ContactsRepository contactsRepository) {\n this.bus = bus;\n this.contactsRepository = contactsRepository;\n this.event = new GetContactsEvent();\n }\n\n @Override public void execute() throws Throwable {\n List<Contact> contactList = contactsRepository.getContacts();\n event.setContactList(contactList);\n bus.post(event);\n }\n}", "public class InsertContactsIntoDataBaseInteractor implements Interactor {\n\n private Contact contact;\n private ContactsRepository contactsRepository;\n private Bus bus;\n\n public InsertContactsIntoDataBaseInteractor(Bus bus,ContactsRepository contactsRepository) {\n this.bus = bus;\n this.contactsRepository = contactsRepository;\n }\n\n @Override public void execute() throws Throwable {\n contactsRepository.insertContact(contact);\n }\n\n public void setContact(Contact contact) {\n this.contact = contact;\n }\n}", "public class GetContactsEvent extends BaseEvent {\n private List<Contact> contactList;\n\n public List<Contact> getContactList() {\n return contactList;\n }\n\n public void setContactList(List<Contact> contactList) {\n this.contactList = contactList;\n }\n}", "public class Contact {\n\n private int idContact;\n private String firstName;\n private String lastName;\n private int phone;\n private String email;\n\n public int getIdContact() {\n return idContact;\n }\n\n public void setIdContact(int idContact) {\n this.idContact = idContact;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public int getPhone() {\n return phone;\n }\n\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n}", "public abstract class Presenter {\n public abstract void onResume();\n public abstract void onPause();\n}", "public class PresentationContactMapper {\n\n public Contact presentationContactToContact(PresentationContact presentationContact){\n Contact contact = new Contact();\n contact.setIdContact(presentationContact.getIdContact());\n contact.setFirstName(presentationContact.getFirstName());\n contact.setLastName(presentationContact.getLastName());\n contact.setEmail(presentationContact.getEmail());\n contact.setPhone(presentationContact.getPhone());\n return contact;\n }\n\n public PresentationContact contactToPresentationContact(Contact contact){\n PresentationContact presentationContact = new PresentationContact();\n presentationContact.setIdContact(contact.getIdContact());\n presentationContact.setFirstName(contact.getFirstName());\n presentationContact.setLastName(contact.getLastName());\n presentationContact.setEmail(contact.getEmail());\n presentationContact.setPhone(contact.getPhone());\n return presentationContact;\n }\n\n public List<PresentationContact> ContactsListToPresentationContactList(List<Contact> contactList){\n List<PresentationContact> presentationContactList = new ArrayList<>();\n\n for (Contact contact : contactList) {\n PresentationContact presentationContact = contactToPresentationContact(contact);\n presentationContactList.add(presentationContact);\n }\n return presentationContactList;\n }\n}", "public class PresentationContact {\n\n private int idContact;\n private String firstName;\n private String lastName;\n private int phone;\n private String email;\n\n public int getIdContact() {\n return idContact;\n }\n\n public void setIdContact(int idContact) {\n this.idContact = idContact;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public int getPhone() {\n return phone;\n }\n\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n}" ]
import java.util.List; import sergio.vasco.androidforexample.domain.abstractions.Bus; import sergio.vasco.androidforexample.domain.interactors.InteractorInvoker; import sergio.vasco.androidforexample.domain.interactors.main.GetContactsFromDataBaseInteractor; import sergio.vasco.androidforexample.domain.interactors.main.InsertContactsIntoDataBaseInteractor; import sergio.vasco.androidforexample.domain.interactors.main.events.GetContactsEvent; import sergio.vasco.androidforexample.domain.model.Contact; import sergio.vasco.androidforexample.presentation.Presenter; import sergio.vasco.androidforexample.presentation.mappers.PresentationContactMapper; import sergio.vasco.androidforexample.presentation.model.PresentationContact;
package sergio.vasco.androidforexample.presentation.sections.main; /** * Name: Sergio Vasco * Date: 14/1/16. */ public class MainPresenter extends Presenter { private MainView view; private Bus bus; private InteractorInvoker interactorInvoker; private InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor; private GetContactsFromDataBaseInteractor getContactsFromDataBaseInteractor; private PresentationContactMapper presentationContactMapper; public MainPresenter(MainView view, Bus bus, InteractorInvoker interactorInvoker, InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor, GetContactsFromDataBaseInteractor getContactsFromDataBaseInteractor, PresentationContactMapper presentationContactMapper) { this.view = view; this.bus = bus; this.interactorInvoker = interactorInvoker; this.insertContactsIntoDataBaseInteractor = insertContactsIntoDataBaseInteractor; this.getContactsFromDataBaseInteractor = getContactsFromDataBaseInteractor; this.presentationContactMapper = presentationContactMapper; } public void insertContactIntoDataBase(PresentationContact presentationContact) {
Contact contact = presentationContactMapper.presentationContactToContact(presentationContact);
5
sheimi/SGit
src/main/java/me/sheimi/sgit/activities/delegate/RepoOperationDelegate.java
[ "public class FsUtils {\n\n public static final SimpleDateFormat TIMESTAMP_FORMATTER = new SimpleDateFormat(\n \"yyyyMMdd_HHmmss\", Locale.getDefault());\n public static final String TEMP_DIR = \"temp\";\n private static final String LOGTAG = FsUtils.class.getSimpleName();\n\n private FsUtils() {\n }\n\n public static File createTempFile(String subfix) throws IOException {\n File dir = getExternalDir(TEMP_DIR);\n String fileName = TIMESTAMP_FORMATTER.format(new Date());\n File file = File.createTempFile(fileName, subfix, dir);\n file.deleteOnExit();\n return file;\n }\n\n /**\n * Get a File representing a dir within the external shared location where files can be stored specific to this app\n * creating the dir if it doesn't already exist\n *\n * @param dirname\n * @return\n */\n public static File getExternalDir(String dirname) {\n return getExternalDir(dirname, true);\n }\n\n /**\n *\n * @param dirname\n * @return\n */\n public static File getInternalDir(String dirname) { return getExternalDir(dirname, true, false); }\n\n /**\n * Get a File representing a dir within the external shared location where files can be stored specific to this app\n *\n * @param dirname\n * @param isCreate create the dir if it does not already exist\n * @return\n */\n public static File getExternalDir(String dirname, boolean isCreate) { return getExternalDir(dirname, isCreate, true); }\n\n /**\n *\n * Get a File representing a dir within the location where files can be stored specific to this app\n *\n * @param dirname name of the dir to return\n * @param isCreate create the dir if it does not already exist\n * @param isExternal if true, will use external *shared* storage\n * @return\n */\n public static File getExternalDir(String dirname, boolean isCreate, boolean isExternal) {\n File mDir = new File(getAppDir(isExternal), dirname);\n if (!mDir.exists() && isCreate) {\n mDir.mkdir();\n }\n return mDir;\n }\n\n /**\n * Get a File representing the location where files can be stored specific to this app\n *\n * @param isExternal if true, will use external *shared* storage\n * @return\n */\n public static File getAppDir(boolean isExternal) {\n SheimiFragmentActivity activeActivity = BasicFunctions.getActiveActivity();\n if (isExternal) {\n return activeActivity.getExternalFilesDir(null);\n } else {\n return activeActivity.getFilesDir();\n }\n }\n\n /**\n * Returns the root directory on device storage in which local repos ar to be stored\n *\n * @param context\n * @param name\n * @return null if the custom repo location user preference is *not* set\n */\n public static File getRepoDir(Context context, String repoName) {\n SharedPreferences sharedPreference = context.getSharedPreferences(\n context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);\n\n String repoRootDir = sharedPreference.getString(context.getString(R.string.pref_key_repo_root_location), \"\");\n if (repoRootDir != null && !repoRootDir.isEmpty()) {\n return new File(repoRootDir, repoName);\n } else {\n return null;\n }\n }\n\n public static String getMimeType(String url) {\n String type = null;\n String extension = MimeTypeMap.getFileExtensionFromUrl(url\n .toLowerCase(Locale.getDefault()));\n if (extension != null) {\n MimeTypeMap mime = MimeTypeMap.getSingleton();\n type = mime.getMimeTypeFromExtension(extension);\n }\n if (type == null) {\n type = \"text/plain\";\n }\n return type;\n }\n\n public static String getMimeType(File file) {\n return getMimeType(Uri.fromFile(file).toString());\n }\n\n public static void openFile(File file) {\n openFile(file, null);\n }\n\n public static void openFile(File file, String mimeType) {\n Intent intent = new Intent();\n intent.setAction(android.content.Intent.ACTION_VIEW);\n Uri uri = Uri.fromFile(file);\n if (mimeType == null) {\n mimeType = getMimeType(uri.toString());\n }\n intent.setDataAndType(uri, mimeType);\n try {\n BasicFunctions.getActiveActivity().startActivity(\n Intent.createChooser(\n intent,\n BasicFunctions.getActiveActivity().getString(\n R.string.label_choose_app_to_open)));\n } catch (ActivityNotFoundException e) {\n BasicFunctions.showException(e, R.string.error_no_open_app);\n } catch (Throwable e) {\n BasicFunctions.showException(e, R.string.error_can_not_open_file);\n }\n }\n\n public static void deleteFile(File file) {\n File to = new File(file.getAbsolutePath() + System.currentTimeMillis());\n file.renameTo(to);\n deleteFileInner(to);\n }\n\n private static void deleteFileInner(File file) {\n if (!file.isDirectory()) {\n file.delete();\n return;\n }\n try {\n FileUtils.deleteDirectory(file);\n } catch (IOException e) {\n //TODO \n e.printStackTrace();\n }\n }\n\n public static void copyFile(File from, File to) {\n try {\n FileUtils.copyFile(from, to);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void copyDirectory(File from, File to) {\n if (!from.exists())\n return;\n try {\n FileUtils.copyDirectory(from, to);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static boolean renameDirectory(File dir, String name) {\n String newDirPath = dir.getParent() + File.separator + name;\n File newDirFile = new File(newDirPath);\n\n return dir.renameTo(newDirFile);\n }\n\n public static String getRelativePath(File file, File base) {\n return base.toURI().relativize(file.toURI()).getPath();\n }\n\n public static File joinPath(File dir, String relative_path) {\n return new File(dir.getAbsolutePath() + File.separator + relative_path);\n }\n\n}", "public class RepoDetailActivity extends SheimiFragmentActivity {\n\n private ActionBar mActionBar;\n\n private FilesFragment mFilesFragment;\n private CommitsFragment mCommitsFragment;\n private StatusFragment mStatusFragment;\n\n private RelativeLayout mRightDrawer;\n private ListView mRepoOperationList;\n private DrawerLayout mDrawerLayout;\n private RepoOperationsAdapter mDrawerAdapter;\n private TabItemPagerAdapter mTabItemPagerAdapter;\n private ViewPager mViewPager;\n private Button mCommitNameButton;\n private ImageView mCommitType;\n private MenuItem mSearchItem;\n\n private Repo mRepo;\n\n private View mPullProgressContainer;\n private ProgressBar mPullProgressBar;\n private TextView mPullMsg;\n private TextView mPullLeftHint;\n private TextView mPullRightHint;\n\n private RepoOperationDelegate mRepoDelegate;\n\n private static final int FILES_FRAGMENT_INDEX = 0;\n private static final int COMMITS_FRAGMENT_INDEX = 1;\n private static final int STATUS_FRAGMENT_INDEX = 2;\n private static final int BRANCH_CHOOSE_ACTIVITY = 0;\n private int mSelectedTab;\n\n @Override\n protected void onActivityResult (int requestCode, int resultCode, Intent data) {\n\tswitch (requestCode) {\n\tcase BRANCH_CHOOSE_ACTIVITY:\n\t String branchName = mRepo.getBranchName();\n\t if (branchName == null) {\n\t\tshowToastMessage(R.string.error_something_wrong);\n\t\treturn;\n\t }\n\t reset(branchName);\n\t break;\n\t}\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n mRepo = (Repo) getIntent().getSerializableExtra(Repo.TAG);\n // aweful hack! workaround for null repo when returning from BranchChooser, but going to\n // shortly refactor passing in serialised repo, so not worth doing more to fix for now\n if (mRepo == null) {\n finish();\n return;\n }\n repoInit();\n setTitle(mRepo.getDiaplayName());\n setContentView(R.layout.activity_repo_detail);\n setupActionBar();\n createFragments();\n setupViewPager();\n setupPullProgressView();\n setupDrawer();\n mCommitNameButton = (Button) findViewById(R.id.commitName);\n mCommitType = (ImageView) findViewById(R.id.commitType);\n mCommitNameButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n\t\tIntent intent = new Intent(RepoDetailActivity.this, BranchChooserActivity.class);\n\t\tintent.putExtra(Repo.TAG, mRepo);\n\t\tstartActivityForResult(intent, BRANCH_CHOOSE_ACTIVITY);\n }\n });\n String branchName = mRepo.getBranchName();\n if (branchName == null) {\n showToastMessage(R.string.error_something_wrong);\n return;\n }\n resetCommitButtonName(branchName);\n }\n\n public RepoOperationDelegate getRepoDelegate() {\n if (mRepoDelegate == null) {\n mRepoDelegate = new RepoOperationDelegate(mRepo, this);\n }\n return mRepoDelegate;\n }\n\n private void setupViewPager() {\n mViewPager = (ViewPager) findViewById(R.id.pager);\n mTabItemPagerAdapter = new TabItemPagerAdapter(getFragmentManager());\n mViewPager.setAdapter(mTabItemPagerAdapter);\n mViewPager.setOnPageChangeListener(mTabItemPagerAdapter);\n }\n\n private void setupDrawer() {\n mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);\n mRightDrawer = (RelativeLayout) findViewById(R.id.right_drawer);\n mRepoOperationList = (ListView) findViewById(R.id.repoOperationList);\n mDrawerAdapter = new RepoOperationsAdapter(this);\n mRepoOperationList.setAdapter(mDrawerAdapter);\n mRepoOperationList.setOnItemClickListener(mDrawerAdapter);\n }\n\n private void setupPullProgressView() {\n mPullProgressContainer = findViewById(R.id.pullProgressContainer);\n mPullProgressContainer.setVisibility(View.GONE);\n mPullProgressBar = (ProgressBar) mPullProgressContainer\n .findViewById(R.id.pullProgress);\n mPullMsg = (TextView) mPullProgressContainer.findViewById(R.id.pullMsg);\n mPullLeftHint = (TextView) mPullProgressContainer\n .findViewById(R.id.leftHint);\n mPullRightHint = (TextView) mPullProgressContainer\n .findViewById(R.id.rightHint);\n }\n\n private void setupActionBar() {\n mActionBar = getActionBar();\n mActionBar.setDisplayShowTitleEnabled(true);\n mActionBar.setDisplayHomeAsUpEnabled(true);\n }\n\n private void createFragments() {\n mFilesFragment = FilesFragment.newInstance(mRepo);\n mCommitsFragment = CommitsFragment.newInstance(mRepo, null);\n mStatusFragment = StatusFragment.newInstance(mRepo);\n }\n\n private void resetCommitButtonName(String commitName) {\n int commitType = Repo.getCommitType(commitName);\n switch (commitType) {\n case Repo.COMMIT_TYPE_REMOTE:\n // change the display name to local branch\n commitName = Repo.convertRemoteName(commitName);\n case Repo.COMMIT_TYPE_HEAD:\n mCommitType.setVisibility(View.VISIBLE);\n mCommitType.setImageResource(R.drawable.ic_branch_w);\n break;\n case Repo.COMMIT_TYPE_TAG:\n mCommitType.setVisibility(View.VISIBLE);\n mCommitType.setImageResource(R.drawable.ic_tag_w);\n break;\n case Repo.COMMIT_TYPE_TEMP:\n mCommitType.setVisibility(View.GONE);\n break;\n }\n String displayName = Repo.getCommitDisplayName(commitName);\n mCommitNameButton.setText(displayName);\n }\n\n public void reset(String commitName) {\n resetCommitButtonName(commitName);\n reset();\n }\n\n public void reset() {\n mFilesFragment.reset();\n mCommitsFragment.reset();\n mStatusFragment.reset();\n }\n\n public void setFilesFragment(FilesFragment filesFragment) {\n mFilesFragment = filesFragment;\n }\n\n public FilesFragment getFilesFragment() {\n return mFilesFragment;\n }\n\n public void setCommitsFragment(CommitsFragment commitsFragment) {\n mCommitsFragment = commitsFragment;\n }\n\n public void setStatusFragment(StatusFragment statusFragment) {\n mStatusFragment = statusFragment;\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.repo_detail, menu);\n mSearchItem = menu.findItem(R.id.action_search);\n mSearchItem.setOnActionExpandListener(mTabItemPagerAdapter);\n mSearchItem.setVisible(mSelectedTab == COMMITS_FRAGMENT_INDEX);\n SearchView searchView = (SearchView) mSearchItem.getActionView();\n if (searchView != null) {\n searchView.setIconifiedByDefault(true);\n searchView.setOnQueryTextListener(mTabItemPagerAdapter);\n }\n return true;\n }\n\n @Override\n public boolean onKeyUp(int keyCode, KeyEvent event) {\n if (keyCode == KeyEvent.KEYCODE_BACK) {\n int position = mViewPager.getCurrentItem();\n OnBackClickListener onBackClickListener = mTabItemPagerAdapter\n .getItem(position).getOnBackClickListener();\n if (onBackClickListener != null) {\n if (onBackClickListener.onClick())\n return true;\n }\n finish();\n return true;\n }\n return false;\n }\n\n public void error() {\n finish();\n showToastMessage(R.string.error_unknown);\n }\n\n public class ProgressCallback implements AsyncTaskCallback {\n\n private int mInitMsg;\n\n public ProgressCallback(int initMsg) {\n mInitMsg = initMsg;\n }\n\n @Override\n public void onPreExecute() {\n mPullMsg.setText(mInitMsg);\n Animation anim = AnimationUtils.loadAnimation(\n RepoDetailActivity.this, R.anim.fade_in);\n mPullProgressContainer.setAnimation(anim);\n mPullProgressContainer.setVisibility(View.VISIBLE);\n mPullLeftHint.setText(R.string.progress_left_init);\n mPullRightHint.setText(R.string.progress_right_init);\n }\n\n @Override\n public void onProgressUpdate(String... progress) {\n mPullMsg.setText(progress[0]);\n mPullLeftHint.setText(progress[1]);\n mPullRightHint.setText(progress[2]);\n mPullProgressBar.setProgress(Integer.parseInt(progress[3]));\n }\n\n @Override\n public void onPostExecute(Boolean isSuccess) {\n Animation anim = AnimationUtils.loadAnimation(\n RepoDetailActivity.this, R.anim.fade_out);\n mPullProgressContainer.setAnimation(anim);\n mPullProgressContainer.setVisibility(View.GONE);\n reset();\n }\n\n @Override\n public boolean doInBackground(Void... params) {\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n return false;\n }\n return true;\n }\n\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 case R.id.action_toggle_drawer:\n if (mDrawerLayout.isDrawerOpen(mRightDrawer)) {\n mDrawerLayout.closeDrawer(mRightDrawer);\n } else {\n mDrawerLayout.openDrawer(mRightDrawer);\n }\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n public void closeOperationDrawer() {\n mDrawerLayout.closeDrawer(mRightDrawer);\n }\n\n public void enterDiffActionMode() {\n mViewPager.setCurrentItem(COMMITS_FRAGMENT_INDEX);\n mCommitsFragment.enterDiffActionMode();\n }\n\n private void repoInit() {\n mRepo.updateLatestCommitInfo();\n mRepo.getRemotes();\n }\n\n class TabItemPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, SearchView.OnQueryTextListener, MenuItem.OnActionExpandListener {\n\n private final int[] PAGE_TITLE = { R.string.tab_files_label,\n R.string.tab_commits_label, R.string.tab_status_label };\n\n public TabItemPagerAdapter(FragmentManager fm) {\n super(fm);\n }\n\n @Override\n public BaseFragment getItem(int position) {\n switch (position) {\n case FILES_FRAGMENT_INDEX:\n return mFilesFragment;\n case COMMITS_FRAGMENT_INDEX:\n return mCommitsFragment;\n case STATUS_FRAGMENT_INDEX:\n mStatusFragment.reset();\n return mStatusFragment;\n }\n return mFilesFragment;\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n return getString(PAGE_TITLE[position]);\n }\n\n @Override\n public int getCount() {\n return PAGE_TITLE.length;\n }\n\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\n }\n\n @Override\n public void onPageSelected(int position) {\n mSelectedTab = position;\n if (mSearchItem != null) {\n mSearchItem.setVisible(position == COMMITS_FRAGMENT_INDEX);\n }\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n\n }\n\n @Override\n public boolean onQueryTextSubmit(String query) {\n switch (mViewPager.getCurrentItem()) {\n case COMMITS_FRAGMENT_INDEX:\n mCommitsFragment.setFilter(query);\n break;\n }\n return true;\n }\n\n @Override\n public boolean onQueryTextChange(String query) {\n switch (mViewPager.getCurrentItem()) {\n case COMMITS_FRAGMENT_INDEX:\n mCommitsFragment.setFilter(query);\n break;\n }\n return true;\n }\n\n @Override\n public boolean onMenuItemActionExpand(MenuItem menuItem) {\n return true;\n }\n\n @Override\n public boolean onMenuItemActionCollapse(MenuItem menuItem) {\n switch (mViewPager.getCurrentItem()) {\n case COMMITS_FRAGMENT_INDEX:\n mCommitsFragment.setFilter(null);\n break;\n }\n return true;\n }\n\n }\n\n}", "public class CommitAction extends RepoAction {\n\n public CommitAction(Repo repo, RepoDetailActivity activity) {\n super(repo, activity);\n }\n\n @Override\n public void execute() {\n commit();\n mActivity.closeOperationDrawer();\n }\n\n private void commit(String commitMsg, boolean isAmend, boolean stageAll, String authorName,\n String authorEmail) {\n CommitChangesTask commitTask = new CommitChangesTask(mRepo, commitMsg,\n isAmend, stageAll, authorName, authorEmail, new AsyncTaskPostCallback() {\n\n @Override\n public void onPostExecute(Boolean isSuccess) {\n mActivity.reset();\n }\n });\n commitTask.executeTask();\n }\n\n private class Author implements Comparable<Author> {\n private String mName;\n private String mEmail;\n private ArrayList<String> mKeywords;\n private final String SPLIT_KEYWORDS = \" |\\\\.|-|_|@\";\n\n Author (String username, String email) {\n mName = username;\n mEmail = email;\n mKeywords = new ArrayList<String> ();\n Collections.addAll(mKeywords, mName.toLowerCase().split(SPLIT_KEYWORDS));\n Collections.addAll(mKeywords, mEmail.toLowerCase().split(SPLIT_KEYWORDS));\n }\n\n Author(PersonIdent personIdent) {\n this(personIdent.getName(), personIdent.getEmailAddress());\n }\n\n public String getEmail() {\n return mEmail;\n }\n\n public String getName() {\n return mName;\n }\n\n public String displayString() {\n return mName + \" <\" + mEmail + \">\";\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof Author)) {\n return false;\n }\n return mName.equals(((Author) o).mName) && mEmail.equals (((Author) o).mEmail);\n }\n\n @Override\n public int hashCode() {\n return mName.hashCode() + mEmail.hashCode() * 997;\n }\n\n @Override\n public int compareTo(Author another) {\n int c1;\n c1 = mName.compareTo(another.mName);\n if (c1 != 0)\n return c1;\n return mEmail.compareTo(another.mEmail);\n }\n\n public boolean matches(String constraint) {\n constraint = constraint.toLowerCase();\n if (mEmail.toLowerCase().startsWith(constraint)) {\n return true;\n }\n if (mName.toLowerCase().startsWith(constraint)) {\n return true;\n }\n\n for (String constraintKeyword : constraint.split(SPLIT_KEYWORDS)) {\n boolean ok = false;\n for (String keyword : mKeywords) {\n if (keyword.startsWith(constraintKeyword)) {\n ok = true;\n break;\n }\n }\n if (!ok) {\n return false;\n }\n }\n return true;\n }\n }\n\n private class AuthorsAdapter extends BaseAdapter implements Filterable {\n List<Author> arrayList;\n List<Author> mOriginalValues;\n LayoutInflater inflater;\n\n public AuthorsAdapter(Context context, List<Author> arrayList) {\n this.arrayList = arrayList;\n inflater = LayoutInflater.from(context);\n }\n\n @Override\n public int getCount() {\n return arrayList.size();\n }\n\n @Override\n public Object getItem(int position) {\n return arrayList.get(position).displayString();\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n private class ViewHolder {\n TextView textView;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n ViewHolder holder = null;\n\n if (convertView == null) {\n\n holder = new ViewHolder();\n convertView = inflater.inflate(android.R.layout.simple_dropdown_item_1line, null);\n holder.textView = (TextView) convertView;\n convertView.setTag(holder);\n } else {\n holder = (ViewHolder) convertView.getTag();\n }\n holder.textView.setText(arrayList.get(position).displayString());\n return convertView;\n }\n\n @Override\n public Filter getFilter() {\n Filter filter = new Filter() {\n\n @SuppressWarnings(\"unchecked\")\n @Override\n protected void publishResults(CharSequence constraint,FilterResults results) {\n arrayList = (List<Author>) results.values; // has the filtered values\n notifyDataSetChanged(); // notifies the data with new filtered values\n }\n\n @Override\n protected FilterResults performFiltering(CharSequence constraint) {\n FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values\n List<Author> FilteredArrList = new ArrayList<Author>();\n\n if (mOriginalValues == null) {\n mOriginalValues = new ArrayList<Author>(arrayList); // saves the original data in mOriginalValues\n }\n\n if (constraint == null || constraint.length() == 0) {\n results.count = mOriginalValues.size();\n results.values = mOriginalValues;\n } else {\n for (int i = 0; i < mOriginalValues.size(); i++) {\n Author data = mOriginalValues.get(i);\n if (data.matches (constraint.toString())) {\n FilteredArrList.add(data);\n }\n }\n // set the Filtered result to return\n results.count = FilteredArrList.size();\n results.values = FilteredArrList;\n }\n return results;\n }\n };\n return filter;\n }\n }\n\n private void commit() {\n AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);\n LayoutInflater inflater = mActivity.getLayoutInflater();\n View layout = inflater.inflate(R.layout.dialog_commit, null);\n final EditText commitMsg = (EditText) layout\n .findViewById(R.id.commitMsg);\n\t final AutoCompleteTextView commitAuthor = (AutoCompleteTextView) layout\n .findViewById(R.id.commitAuthor);\n final CheckBox isAmend = (CheckBox) layout.findViewById(R.id.isAmend);\n final CheckBox autoStage = (CheckBox) layout\n .findViewById(R.id.autoStage);\n\t HashSet<Author> authors = new HashSet<Author>();\n try {\n Iterable<RevCommit> commits = mRepo.getGit().log().setMaxCount(500).call();\n for (RevCommit commit : commits) {\n authors.add(new Author(commit.getAuthorIdent()));\n }\n } catch (Exception e) {\n }\n String profileUsername = Profile.getUsername(mActivity.getApplicationContext());\n String profileEmail = Profile.getEmail(mActivity.getApplicationContext());\n if (profileUsername != null && !profileUsername.equals(\"\")\n && profileEmail != null && !profileEmail.equals(\"\")) {\n authors.add(new Author(profileUsername, profileEmail));\n }\n ArrayList<Author> authorList = new ArrayList<Author>(authors);\n Collections.sort(authorList);\n\t AuthorsAdapter adapter = new AuthorsAdapter(mActivity, authorList);\n\t commitAuthor.setAdapter(adapter);\n isAmend.setOnCheckedChangeListener(new OnCheckedChangeListener() {\n\n @Override\n public void onCheckedChanged(CompoundButton buttonView,\n boolean isChecked) {\n if (isChecked) {\n commitMsg.setText(mRepo.getLastCommitFullMsg());\n } else {\n commitMsg.setText(\"\");\n }\n }\n });\n final AlertDialog d = builder.setTitle(R.string.dialog_commit_title)\n .setView(layout)\n .setPositiveButton(R.string.dialog_commit_positive_label, null)\n .setNegativeButton(R.string.label_cancel,\n new DummyDialogListener()).create();\n d.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n\n Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);\n b.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View view) {\n String msg = commitMsg.getText().toString();\n String author = commitAuthor.getText().toString().trim();\n String authorName = null, authorEmail = null;\n int ltidx;\n if (msg.trim().equals(\"\")) {\n commitMsg.setError(mActivity.getString(R.string.error_no_commit_msg));\n return;\n }\n if(!author.equals(\"\")) {\n ltidx = author.indexOf('<');\n if (!author.endsWith(\">\") || ltidx == -1) {\n commitAuthor.setError(mActivity.getString(R.string.error_invalid_author));\n return;\n }\n authorName = author.substring(0, ltidx);\n authorEmail = author.substring(ltidx + 1, author.length() - 1);\n }\n\n\n boolean amend = isAmend.isChecked();\n boolean stage = autoStage.isChecked();\n\n commit(msg, amend, stage, authorName, authorEmail);\n\n d.dismiss();\n }\n }\n\n );\n }\n }\n );\n d.show();\n }\n}", "public class ConfigAction extends RepoAction {\n\n\n public ConfigAction(Repo repo, RepoDetailActivity activity) {\n super(repo, activity);\n }\n\n @Override\n public void execute() {\n\n Bundle args = new Bundle();\n args.putSerializable(ConfigRepoDialog.REPO_ARG_KEY, mRepo);\n ConfigRepoDialog configDialog = new ConfigRepoDialog();\n configDialog.setArguments(args);\n configDialog.show(mActivity.getFragmentManager(), \"repo-config-dialog\");\n }\n\n}", "public class FetchAction extends RepoAction {\n public FetchAction(Repo repo, RepoDetailActivity activity) {\n super(repo, activity);\n }\n\n @Override\n public void execute() {\n fetchDialog().show();\n mActivity.closeOperationDrawer();\n }\n\n private void fetch(String[] remotes) {\n final FetchTask fetchTask = new FetchTask(remotes, mRepo, mActivity.new ProgressCallback(R.string.fetch_msg_init));\n fetchTask.executeTask();\n }\n\n private Dialog fetchDialog() {\n AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);\n final String[] originRemotes = mRepo.getRemotes().toArray(new String[0]);\n final ArrayList<String> remotes = new ArrayList<>();\n return builder.setTitle(R.string.dialog_fetch_title)\n .setMultiChoiceItems(originRemotes, null, new DialogInterface.OnMultiChoiceClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int index, boolean isChecked) {\n if (isChecked) {\n remotes.add(originRemotes[index]);\n } else {\n for (int i = 0; i < remotes.size(); ++i) {\n if (remotes.get(i) == originRemotes[index]) {\n remotes.remove(i);\n }\n }\n }\n }\n })\n .setPositiveButton(R.string.dialog_fetch_positive_button, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n fetch(remotes.toArray(new String[0]));\n }\n })\n .setNeutralButton(R.string.dialog_fetch_all_button, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n fetch(originRemotes);\n }\n })\n .setNegativeButton(android.R.string.cancel, new DummyDialogListener())\n .create();\n }\n}", "public class NewBranchAction extends RepoAction {\n public NewBranchAction(Repo mRepo, RepoDetailActivity mActivity) {\n super(mRepo,mActivity);\n }\n\n @Override\n public void execute() {\n mActivity.showEditTextDialog(R.string.dialog_create_branch_title,\n R.string.dialog_create_branch_hint,R.string.label_create,\n new SheimiFragmentActivity.OnEditTextDialogClicked() {\n @Override\n public void onClicked(String branchName) {\n CheckoutTask checkoutTask = new CheckoutTask(mRepo, null, branchName,\n new ActivityResetPostCallback(branchName));\n checkoutTask.executeTask();\n }\n });\n mActivity.closeOperationDrawer();\n }\n\n private class ActivityResetPostCallback implements SheimiAsyncTask.AsyncTaskPostCallback {\n private final String mBranchName;\n public ActivityResetPostCallback(String branchName) {\n mBranchName = branchName;\n }\n @Override\n public void onPostExecute(Boolean isSuccess) {\n mActivity.reset(mBranchName);\n }\n }\n}", "public class RemoveRemoteAction extends RepoAction {\n\n public RemoveRemoteAction(Repo repo, RepoDetailActivity activity) {\n super(repo, activity);\n }\n\n @Override\n public void execute() {\n Set<String> remotes = mRepo.getRemotes();\n if (remotes == null || remotes.isEmpty()) {\n mActivity.showToastMessage(R.string.alert_please_add_a_remote);\n return;\n }\n\n RemoveRemoteDialog dialog = new RemoveRemoteDialog();\n dialog.setArguments(mRepo.getBundle());\n dialog.show(mActivity.getFragmentManager(), \"remove-remote-dialog\");\n mActivity.closeOperationDrawer();\n }\n\n public static void removeRemote(Repo repo, RepoDetailActivity activity, String remote) {\n try {\n repo.removeRemote(remote);\n activity.showToastMessage(R.string.success_remote_removed);\n } catch (IOException e) {\n BasicFunctions.showException(e);\n }\n }\n\n public static class RemoveRemoteDialog extends SheimiDialogFragment {\n private Repo mRepo;\n private RepoDetailActivity mActivity;\n private ListView mRemoteList;\n private ArrayAdapter<String> mAdapter;\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n super.onCreateDialog(savedInstanceState);\n Bundle args = getArguments();\n if (args != null && args.containsKey(Repo.TAG)) {\n mRepo = (Repo) args.getSerializable(Repo.TAG);\n }\n\n mActivity = (RepoDetailActivity) getActivity();\n AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);\n LayoutInflater inflater = mActivity.getLayoutInflater();\n\n View layout = inflater.inflate(R.layout.dialog_remove_remote, null);\n mRemoteList = (ListView) layout.findViewById(R.id.remoteList);\n\n mAdapter = new ArrayAdapter<String>(mActivity,\n android.R.layout.simple_list_item_1);\n Set<String> remotes = mRepo.getRemotes();\n mAdapter.addAll(remotes);\n mRemoteList.setAdapter(mAdapter);\n\n mRemoteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView<?> parent, View view,\n int position, long id) {\n String remote = mAdapter.getItem(position);\n removeRemote(mRepo, mActivity, remote);\n dismiss();\n }\n });\n\n builder.setTitle(R.string.dialog_remove_remote_title)\n .setView(layout)\n .setNegativeButton(R.string.label_cancel, new DummyDialogListener());\n return builder.create();\n }\n }\n\n}", "public class Repo implements Comparable<Repo>, Serializable {\n\n /**\n * Generated serialVersionID\n */\n private static final long serialVersionUID = -4921633809823078219L;\n\n public static final String TAG = Repo.class.getSimpleName();\n\n public static final int COMMIT_TYPE_HEAD = 0;\n public static final int COMMIT_TYPE_TAG = 1;\n public static final int COMMIT_TYPE_TEMP = 2;\n public static final int COMMIT_TYPE_REMOTE = 3;\n public static final int COMMIT_TYPE_UNKNOWN = -1;\n\n private int mID;\n private String mLocalPath;\n private String mRemoteURL;\n private String mUsername;\n private String mPassword;\n private String mRepoStatus;\n private String mLastCommitter;\n private String mLastCommitterEmail;\n private Date mLastCommitDate;\n private String mLastCommitMsg;\n private boolean isDeleted = false;\n\n // lazy load\n private Set<String> mRemotes;\n private Git mGit;\n private StoredConfig mStoredConfig;\n\n public static final String DOT_GIT_DIR = \".git\";\n public static final String EXTERNAL_PREFIX = \"external://\";\n public static final String REPO_DIR = \"repo\";\n\n private static SparseArray<RepoOpTask> mRepoTasks = new SparseArray<RepoOpTask>();\n\n public Repo(Cursor cursor) {\n mID = RepoContract.getRepoID(cursor);\n mRemoteURL = RepoContract.getRemoteURL(cursor);\n mLocalPath = RepoContract.getLocalPath(cursor);\n mUsername = RepoContract.getUsername(cursor);\n mPassword = RepoContract.getPassword(cursor);\n mRepoStatus = RepoContract.getRepoStatus(cursor);\n mLastCommitter = RepoContract.getLatestCommitterName(cursor);\n mLastCommitterEmail = RepoContract.getLatestCommitterEmail(cursor);\n mLastCommitDate = RepoContract.getLatestCommitDate(cursor);\n mLastCommitMsg = RepoContract.getLatestCommitMsg(cursor);\n }\n\n public Bundle getBundle() {\n Bundle bundle = new Bundle();\n bundle.putSerializable(TAG, this);\n return bundle;\n }\n\n public static Repo getRepoById(Context context, long id) {\n Cursor c = RepoDbManager.getRepoById(id);\n c.moveToFirst();\n Repo repo = new Repo(c);\n c.close();\n return repo;\n }\n\n public static List<Repo> getRepoList(Context context, Cursor cursor) {\n List<Repo> repos = new ArrayList<Repo>();\n cursor.moveToFirst();\n while (!cursor.isAfterLast()) {\n repos.add(new Repo(cursor));\n cursor.moveToNext();\n }\n return repos;\n }\n\n public int getID() {\n return mID;\n }\n\n public String getLocalPath() {\n return mLocalPath;\n }\n\n public String getDiaplayName() {\n if (!isExternal())\n return mLocalPath;\n String[] strs = mLocalPath.split(\"/\");\n return strs[strs.length - 1] + \" (external)\";\n }\n\n public static boolean isExternal(String path) {\n return path.startsWith(EXTERNAL_PREFIX);\n }\n\n public boolean isExternal() {\n return isExternal(getLocalPath());\n }\n\n public String getRemoteURL() {\n return mRemoteURL;\n }\n\n public String getRepoStatus() {\n return mRepoStatus;\n }\n\n public String getLastCommitter() {\n return mLastCommitter;\n }\n\n public String getLastCommitterEmail() {\n return mLastCommitterEmail;\n }\n\n public String getLastCommitMsg() {\n return mLastCommitMsg;\n }\n\n public String getLastCommitFullMsg() {\n\tRevCommit commit = getLatestCommit();\n\tif (commit == null) {\n\t return getLastCommitMsg();\n\t}\n\treturn commit.getFullMessage();\n }\n\n public Date getLastCommitDate() {\n return mLastCommitDate;\n }\n\n public String getPassword() {\n return mPassword;\n }\n\n public String getUsername() {\n return mUsername;\n }\n\n public void setUsername(String username) {\n mUsername = username;\n }\n\n public void setPassword(String password) {\n mPassword = password;\n }\n\n public void cancelTask() {\n RepoOpTask task = mRepoTasks.get(getID());\n if (task == null)\n return;\n task.cancelTask();\n removeTask(task);\n }\n\n public boolean addTask(RepoOpTask task) {\n if (mRepoTasks.get(getID()) != null)\n return false;\n mRepoTasks.put(getID(), task);\n return true;\n }\n\n public void removeTask(RepoOpTask task) {\n RepoOpTask runningTask = mRepoTasks.get(getID());\n if (runningTask == null || runningTask != task)\n return;\n mRepoTasks.remove(getID());\n }\n\n public void updateStatus(String status) {\n ContentValues values = new ContentValues();\n mRepoStatus = status;\n values.put(RepoContract.RepoEntry.COLUMN_NAME_REPO_STATUS, status);\n RepoDbManager.updateRepo(mID, values);\n }\n\n public void updateRemote() {\n ContentValues values = new ContentValues();\n values.put(RepoContract.RepoEntry.COLUMN_NAME_REMOTE_URL,\n getRemoteOriginURL());\n RepoDbManager.updateRepo(mID, values);\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws IOException {\n out.writeInt(mID);\n out.writeObject(mRemoteURL);\n out.writeObject(mLocalPath);\n out.writeObject(mUsername);\n out.writeObject(mPassword);\n out.writeObject(mRepoStatus);\n out.writeObject(mLastCommitter);\n out.writeObject(mLastCommitterEmail);\n out.writeObject(mLastCommitDate);\n out.writeObject(mLastCommitMsg);\n }\n\n private void readObject(java.io.ObjectInputStream in) throws IOException,\n ClassNotFoundException {\n mID = in.readInt();\n mRemoteURL = (String) in.readObject();\n mLocalPath = (String) in.readObject();\n mUsername = (String) in.readObject();\n mPassword = (String) in.readObject();\n mRepoStatus = (String) in.readObject();\n mLastCommitter = (String) in.readObject();\n mLastCommitterEmail = (String) in.readObject();\n mLastCommitDate = (Date) in.readObject();\n mLastCommitMsg = (String) in.readObject();\n }\n\n @Override\n public int compareTo(Repo repo) {\n return repo.getID() - getID();\n }\n\n public void deleteRepo() {\n Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n deleteRepoSync();\n }\n });\n thread.start();\n }\n\n public void deleteRepoSync() {\n if (isDeleted)\n return;\n RepoDbManager.deleteRepo(mID);\n if (!isExternal()) {\n File fileToDelete = getDir();\n FsUtils.deleteFile(fileToDelete);\n }\n isDeleted = true;\n }\n\n public boolean renameRepo(String repoName) {\n File directory = getDir();\n if (FsUtils.renameDirectory(directory, repoName)) {\n ContentValues values = new ContentValues();\n mLocalPath = isExternal()\n ? EXTERNAL_PREFIX + directory.getParent() + File.separator + repoName\n : repoName;\n values.put(RepoContract.RepoEntry.COLUMN_NAME_LOCAL_PATH, mLocalPath);\n RepoDbManager.updateRepo(getID(), values);\n\n return true;\n }\n\n return false;\n }\n\n public void updateLatestCommitInfo() {\n RevCommit commit = getLatestCommit();\n ContentValues values = new ContentValues();\n String email = \"\";\n String uname = \"\";\n String commitDateStr = \"\";\n String msg = \"\";\n if (commit != null) {\n PersonIdent committer = commit.getCommitterIdent();\n if (committer != null) {\n email = committer.getEmailAddress() != null ? committer\n .getEmailAddress() : email;\n uname = committer.getName() != null ? committer.getName()\n : uname;\n }\n msg = commit.getShortMessage() != null ? commit.getShortMessage()\n : msg;\n long date = committer.getWhen().getTime();\n commitDateStr = Long.toString(date);\n\n }\n values.put(RepoContract.RepoEntry.COLUMN_NAME_LATEST_COMMIT_DATE,\n commitDateStr);\n values.put(RepoContract.RepoEntry.COLUMN_NAME_LATEST_COMMIT_MSG, msg);\n values.put(RepoContract.RepoEntry.COLUMN_NAME_LATEST_COMMITTER_EMAIL,\n email);\n values.put(RepoContract.RepoEntry.COLUMN_NAME_LATEST_COMMITTER_UNAME,\n uname);\n RepoDbManager.updateRepo(getID(), values);\n }\n\n public String getBranchName() {\n try {\n return getGit().getRepository().getFullBranch();\n } catch (IOException e) {\n BasicFunctions.showException(e);\n } catch (StopTaskException e) {\n }\n return \"\";\n }\n\n public String[] getBranches() {\n try {\n Set<String> branchSet = new HashSet<String>();\n List<String> branchList = new ArrayList<String>();\n List<Ref> localRefs = getGit().branchList().call();\n for (Ref ref : localRefs) {\n branchSet.add(ref.getName());\n branchList.add(ref.getName());\n }\n List<Ref> remoteRefs = getGit().branchList()\n .setListMode(ListBranchCommand.ListMode.REMOTE).call();\n for (Ref ref : remoteRefs) {\n String name = ref.getName();\n String localName = convertRemoteName(name);\n if (branchSet.contains(localName))\n continue;\n branchList.add(name);\n }\n return branchList.toArray(new String[0]);\n } catch (GitAPIException e) {\n BasicFunctions.showException(e);\n } catch (StopTaskException e) {\n }\n return new String[0];\n }\n\n private RevCommit getLatestCommit() {\n try {\n Iterable<RevCommit> commits = getGit().log().setMaxCount(1).call();\n Iterator<RevCommit> it = commits.iterator();\n if (!it.hasNext())\n return null;\n return it.next();\n } catch (GitAPIException e) {\n BasicFunctions.showException(e);\n } catch (StopTaskException e) {\n }\n return null;\n }\n\n public List<Ref> getLocalBranches() {\n try {\n List<Ref> localRefs = getGit().branchList().call();\n return localRefs;\n } catch (GitAPIException e) {\n BasicFunctions.showException(e);\n } catch (StopTaskException e) {\n }\n return new ArrayList<Ref>();\n }\n\n public String[] getTags() {\n try {\n List<Ref> refs = getGit().tagList().call();\n String[] tags = new String[refs.size()];\n // convert refs/tags/[branch] -> heads/[branch]\n for (int i = 0; i < tags.length; ++i) {\n tags[i] = refs.get(i).getName();\n }\n return tags;\n } catch (GitAPIException e) {\n BasicFunctions.showException(e);\n } catch (StopTaskException e) {\n }\n return new String[0];\n }\n\n public String getCurrentDisplayName() {\n return getCommitDisplayName(getBranchName());\n }\n\n public static int getCommitType(String[] splits) {\n if (splits.length == 4)\n return COMMIT_TYPE_REMOTE;\n if (splits.length != 3)\n return COMMIT_TYPE_TEMP;\n String type = splits[1];\n if (\"tags\".equals(type))\n return COMMIT_TYPE_TAG;\n return COMMIT_TYPE_HEAD;\n }\n\n /**\n * Returns the type of ref based on the refs full path within .git/\n * @param fullRefName\n * @return\n */\n public static int getCommitType(String fullRefName) {\n if (fullRefName != null && fullRefName.startsWith(Constants.R_REFS)) {\n if (fullRefName.startsWith(Constants.R_HEADS)) {\n return COMMIT_TYPE_HEAD;\n } else if (fullRefName.startsWith(Constants.R_TAGS)) {\n return COMMIT_TYPE_TAG;\n } else if (fullRefName.startsWith(Constants.R_REMOTES)) {\n return COMMIT_TYPE_REMOTE;\n }\n }\n return COMMIT_TYPE_UNKNOWN;\n }\n\n /**\n * Return just the name of the ref, with any prefixes like \"heads\", \"remotes\", \"tags\" etc.\n * @param name\n * @return\n */\n public static String getCommitName(String name) {\n String[] splits = name.split(\"/\");\n int type = getCommitType(splits);\n switch (type) {\n case COMMIT_TYPE_TEMP:\n case COMMIT_TYPE_TAG:\n case COMMIT_TYPE_HEAD:\n return getCommitDisplayName(name);\n case COMMIT_TYPE_REMOTE:\n return splits[3];\n }\n return null;\n }\n\n /**\n *\n * @param ref\n * @return Shortened version of full ref path, suitable for display in UI\n */\n public static String getCommitDisplayName(String ref) {\n if (getCommitType(ref) == COMMIT_TYPE_REMOTE) {\n return (ref != null && ref.length() > Constants.R_REFS.length()) ? ref.substring(Constants.R_REFS.length()) : \"\";\n }\n return Repository.shortenRefName(ref);\n }\n\n /**\n *\n * @param remote\n * @return null if remote is not found to be a remote ref in this repo\n */\n public static String convertRemoteName(String remote) {\n if (getCommitType(remote) != COMMIT_TYPE_REMOTE) {\n return null;\n } else {\n String[] splits = remote.split(\"/\");\n return String.format(\"refs/heads/%s\", splits[3]);\n }\n }\n\n public static File getDir(Context context, String localpath) {\n if (Repo.isExternal(localpath)) {\n return new File(localpath.substring(Repo.EXTERNAL_PREFIX.length()));\n }\n File repoDir = FsUtils.getRepoDir(context, localpath);\n if (repoDir == null) {\n repoDir = FsUtils.getExternalDir(REPO_DIR, true);\n Log.d(\"maks\", \"PRESET repo path:\"+new File(repoDir, localpath).getAbsolutePath());\n return new File(repoDir, localpath);\n } else {\n Log.d(\"maks\", \"CUSTOM repo path:\"+repoDir);\n return repoDir;\n }\n }\n\n public File getDir() {\n return Repo.getDir(SGitApplication.getContext(), getLocalPath());\n }\n\n public Git getGit() throws StopTaskException {\n if (mGit != null)\n return mGit;\n try {\n File repoFile = getDir();\n mGit = Git.open(repoFile);\n return mGit;\n } catch (RepositoryNotFoundException e) {\n BasicFunctions\n .showException(e, R.string.error_repository_not_found);\n throw new StopTaskException();\n } catch (IOException e) {\n BasicFunctions.showException(e);\n throw new StopTaskException();\n }\n }\n\n public StoredConfig getStoredConfig() throws StopTaskException {\n if (mStoredConfig == null) {\n mStoredConfig = getGit().getRepository().getConfig();\n }\n return mStoredConfig;\n }\n\n public String getRemoteOriginURL() {\n try {\n StoredConfig config = getStoredConfig();\n String origin = config.getString(\"remote\", \"origin\", \"url\");\n if (origin != null && !origin.isEmpty())\n return origin;\n Set<String> remoteNames = config.getSubsections(\"remote\");\n if (remoteNames.size() == 0)\n return \"\";\n String url = config.getString(\"remote\", remoteNames.iterator()\n .next(), \"url\");\n return url;\n } catch (StopTaskException e) {\n }\n return \"\";\n }\n\n public Set<String> getRemotes() {\n if (mRemotes != null)\n return mRemotes;\n try {\n StoredConfig config = getStoredConfig();\n Set<String> remotes = config.getSubsections(\"remote\");\n mRemotes = new HashSet<String>(remotes);\n return mRemotes;\n } catch (StopTaskException e) {\n }\n return new HashSet<String>();\n }\n\n public void setRemote(String remote, String url) throws IOException {\n try {\n StoredConfig config = getStoredConfig();\n Set<String> remoteNames = config.getSubsections(\"remote\");\n if (remoteNames.contains(remote)) {\n throw new IOException(String.format(\n \"Remote %s already exists.\", remote));\n }\n config.setString(\"remote\", remote, \"url\", url);\n String fetch = String.format(\"+refs/heads/*:refs/remotes/%s/*\",\n remote);\n config.setString(\"remote\", remote, \"fetch\", fetch);\n config.save();\n mRemotes.add(remote);\n } catch (StopTaskException e) {\n }\n }\n\n public void removeRemote(String remote) throws IOException {\n try {\n StoredConfig config = getStoredConfig();\n Set<String> remoteNames = config.getSubsections(\"remote\");\n if (!remoteNames.contains(remote)) {\n throw new IOException(String.format(\"Remote %s does not exist.\", remote));\n }\n config.unsetSection(\"remote\", remote);\n config.save();\n mRemotes.remove(remote);\n } catch (StopTaskException e) {\n }\n }\n\n}", "public class FetchTask extends RepoOpTask implements SheimiFragmentActivity.OnPasswordEntered {\n\n private final AsyncTaskCallback mCallback;\n private final String[] mRemotes;\n\n public FetchTask(String[] remotes, Repo repo, AsyncTaskCallback callback) {\n super(repo);\n mCallback = callback;\n mRemotes = remotes;\n }\n\n @Override\n protected Boolean doInBackground(Void... params) {\n boolean result = true;\n for (final String remote : mRemotes) {\n result = fetchRepo(remote) & result;\n if (mCallback != null) {\n result = mCallback.doInBackground(params) & result;\n }\n }\n return result;\n }\n\n @Override\n protected void onProgressUpdate(String... progress) {\n super.onProgressUpdate(progress);\n if (mCallback != null) {\n mCallback.onProgressUpdate(progress);\n }\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n if (mCallback != null) {\n mCallback.onPreExecute();\n }\n }\n\n protected void onPostExecute(Boolean isSuccess) {\n super.onPostExecute(isSuccess);\n if (mCallback != null) {\n mCallback.onPostExecute(isSuccess);\n }\n }\n\n @Override\n public void onClicked(String username, String password, boolean savePassword) {\n }\n\n @Override\n public void onCanceled() {\n }\n\n private boolean fetchRepo(String remote) {\n Git git;\n try {\n git = mRepo.getGit();\n } catch (StopTaskException e) {\n return false;\n }\n\n final FetchCommand fetchCommand = git.fetch()\n .setProgressMonitor(new BasicProgressMonitor())\n .setTransportConfigCallback(new SgitTransportCallback())\n .setRemote(remote);\n\n final String username = mRepo.getUsername();\n final String password = mRepo.getPassword();\n if (username != null && password != null && !username.equals(\"\")\n && !password.equals(\"\")) {\n UsernamePasswordCredentialsProvider auth = new UsernamePasswordCredentialsProvider(\n username, password);\n fetchCommand.setCredentialsProvider(auth);\n }\n\n try {\n fetchCommand.call();\n } catch (TransportException e) {\n setException(e);\n handleAuthError(this);\n return false;\n } catch (Exception e) {\n setException(e, R.string.error_pull_failed);\n return false;\n } catch (OutOfMemoryError e) {\n setException(e, R.string.error_out_of_memory);\n return false;\n } catch (Throwable e) {\n setException(e);\n return false;\n }\n mRepo.updateLatestCommitInfo();\n return true;\n }\n}" ]
import java.io.File; import java.io.Serializable; import java.util.ArrayList; import me.sheimi.android.utils.FsUtils; import me.sheimi.sgit.activities.RepoDetailActivity; import me.sheimi.sgit.activities.delegate.actions.AddAllAction; import me.sheimi.sgit.activities.delegate.actions.AddRemoteAction; import me.sheimi.sgit.activities.delegate.actions.CherryPickAction; import me.sheimi.sgit.activities.delegate.actions.CommitAction; import me.sheimi.sgit.activities.delegate.actions.ConfigAction; import me.sheimi.sgit.activities.delegate.actions.DeleteAction; import me.sheimi.sgit.activities.delegate.actions.DiffAction; import me.sheimi.sgit.activities.delegate.actions.FetchAction; import me.sheimi.sgit.activities.delegate.actions.MergeAction; import me.sheimi.sgit.activities.delegate.actions.NewBranchAction; import me.sheimi.sgit.activities.delegate.actions.NewDirAction; import me.sheimi.sgit.activities.delegate.actions.NewFileAction; import me.sheimi.sgit.activities.delegate.actions.PullAction; import me.sheimi.sgit.activities.delegate.actions.PushAction; import me.sheimi.sgit.activities.delegate.actions.RawConfigAction; import me.sheimi.sgit.activities.delegate.actions.RebaseAction; import me.sheimi.sgit.activities.delegate.actions.RemoveRemoteAction; import me.sheimi.sgit.activities.delegate.actions.RepoAction; import me.sheimi.sgit.activities.delegate.actions.ResetAction; import me.sheimi.sgit.database.models.Repo; import me.sheimi.sgit.repo.tasks.SheimiAsyncTask.AsyncTaskPostCallback; import me.sheimi.sgit.repo.tasks.repo.AddToStageTask; import me.sheimi.sgit.repo.tasks.repo.CheckoutFileTask; import me.sheimi.sgit.repo.tasks.repo.CheckoutTask; import me.sheimi.sgit.repo.tasks.repo.DeleteFileFromRepoTask; import me.sheimi.sgit.repo.tasks.repo.FetchTask; import me.sheimi.sgit.repo.tasks.repo.MergeTask; import org.eclipse.jgit.lib.Ref; import static me.sheimi.sgit.repo.tasks.repo.DeleteFileFromRepoTask.*;
package me.sheimi.sgit.activities.delegate; public class RepoOperationDelegate { private Repo mRepo;
private RepoDetailActivity mActivity;
1
schaloner/deadbolt
samples-and-tests/acl/app/controllers/AclDeadboltHandler.java
[ "public interface DeadboltHandler\n{\n /**\n * Invoked immediately before controller or view restrictions are checked. This forms the integration with any\n * authentication actions that may need to occur.\n */\n void beforeRoleCheck();\n\n /**\n * Gets the current {@link RoleHolder}, e.g. the current user.\n *\n * @return the current role holder\n */\n RoleHolder getRoleHolder();\n\n /**\n * Invoked when an access failure is detected on <i>controllerClassName</i>.\n *\n * @param controllerClassName the name of the controller access was denied to\n */\n void onAccessFailure(String controllerClassName);\n\n /**\n * Gets the accessor used to determine restrictions from an external source.\n *\n * @return the accessor for externalised restrictions. May be null.\n */\n ExternalizedRestrictionsAccessor getExternalizedRestrictionsAccessor();\n\n /**\n * Gets the handler used for dealing with resources restricted to specific users/groups.\n *\n * @return the handler for restricted resources. May be null.\n */\n RestrictedResourcesHandler getRestrictedResourcesHandler();\n}", "public interface ExternalizedRestrictionsAccessor\n{\n ExternalizedRestrictions getExternalizedRestrictions(String name);\n}", "public interface RestrictedResourcesHandler\n{\n /**\n * Check the access of someone, typically the current user, for the named resource.\n *\n * <ul>\n * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and\n * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is false, access is denied.</li>\n * <li>If {@link AccessResult#NOT_SPECIFIED} is returned and\n * {@link controllers.deadbolt.RestrictedResource#staticFallback()} is true, any further Restrict or\n * Restrictions annotations are processed. Note that if no Restrict or Restrictions annotations are present,\n * access will be allowed.</li>\n * </ul>\n *\n * @param resourceNames the names of the resource\n * @param resourceParameters additional information on the resource\n * @return {@link AccessResult#ALLOWED} if access is permitted. {@link AccessResult#DENIED} if access is denied.\n * {@link AccessResult#NOT_SPECIFIED} if access is not specified.\n */\n AccessResult checkAccess(List<String> resourceNames,\n Map<String, String> resourceParameters);\n}", "@Entity\npublic class AclUser extends Model implements RoleHolder\n{\n @Required\n public String userName;\n\n public String fullName;\n\n @Required\n @ManyToOne\n public AclApplicationRole role;\n\n @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH})\n public List<AclUser> friends;\n\n @ManyToMany(cascade = CascadeType.ALL)\n public List<Photo> photos;\n\n @ManyToMany(cascade = CascadeType.ALL)\n public List<StatusUpdate> statusUpdates;\n\n @OneToOne(cascade = CascadeType.ALL)\n public AccessControlPreference accessControlPreference;\n\n public AclUser(String userName,\n String fullName,\n AclApplicationRole role)\n {\n this.userName = userName;\n this.fullName = fullName;\n this.role = role;\n this.accessControlPreference = new AccessControlPreference();\n }\n\n public static AclUser getByUserName(String userName)\n {\n return find(\"byUserName\", userName).first();\n }\n\n public List<? extends Role> getRoles()\n {\n return Arrays.asList(role);\n }\n\n public void addPhoto(Photo photo)\n {\n if (photos == null)\n {\n photos = new ArrayList<Photo>();\n }\n photos.add(photo);\n }\n\n public void addStatusUpdate(StatusUpdate statusUpdate)\n {\n if (statusUpdates == null)\n {\n statusUpdates = new ArrayList<StatusUpdate>();\n }\n statusUpdates.add(statusUpdate);\n }\n\n public void addFriend(AclUser friend)\n {\n if (friends == null)\n {\n friends = new ArrayList<AclUser>();\n }\n friends.add(friend);\n }\n\n public boolean isFriend(AclUser user)\n {\n return friends != null && friends.contains(user);\n }\n\n @Override\n public String toString()\n {\n return this.userName;\n }\n}", "public interface ExternalizedRestrictions\n{\n /**\n * Gets all the {@link ExternalizedRestriction}s associated with a target.\n *\n * @return\n */\n List<ExternalizedRestriction> getExternalisedRestrictions();\n}", "public interface RoleHolder\n{\n /**\n * A list of {@link Role}s held by the role holder.\n *\n * @return a list of roles\n */\n List<? extends Role> getRoles();\n}" ]
import controllers.deadbolt.DeadboltHandler; import controllers.deadbolt.ExternalizedRestrictionsAccessor; import controllers.deadbolt.RestrictedResourcesHandler; import model.AclUser; import models.deadbolt.ExternalizedRestrictions; import models.deadbolt.RoleHolder; import play.mvc.Controller;
/* * Copyright 2010-2011 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AclDeadboltHandler extends Controller implements DeadboltHandler {
private static final RestrictedResourcesHandler RESTRICTED_RESOURCES_HANDLER = new AclRestrictedResourcesHandler();
2
dariober/ASCIIGenome
src/test/java/tracks/TrackNarrowPeakTest.java
[ "public class Config {\n\t\n\t// C O N S T R U C T O R \n\t\n\tprivate static final Map<ConfigKey, String> config= new HashMap<ConfigKey, String>();\n\n\tpublic Config(String source) throws IOException, InvalidConfigException {\n\t\t\n\t\tnew Xterm256();\n\t\t\n\t\tString RawConfigFile= Config.getConfigFileAsString(source).replaceAll(\"\\t\", \" \").toLowerCase();\n\t\t\n\t\t// This will give one string per line\n\t\tList<String> raw= Splitter.on(\"\\n\").omitEmptyStrings().trimResults().splitToList(RawConfigFile);\n\n\t\t//List<String> config= new ArrayList<String>();\n\t\tfor(String x : raw){\n\t\t\tx= x.replaceAll(\"#.*\", \"\").trim();\n\t\t\tif( ! x.isEmpty()){\n\t\t\t\tList<String> keyValuePair= Splitter.on(\" \").omitEmptyStrings().trimResults().splitToList(x);\n\t\t\t\tif(ConfigKey.getValues().contains(keyValuePair.get(0))){\n\t\t\t\t\tconfig.put(ConfigKey.valueOf(keyValuePair.get(0)), keyValuePair.get(1));\n\t\t\t\t} else {\n\t\t\t\t\tSystem.err.println(\"Unrecognized configuration key: \" + keyValuePair.get(0));\n\t\t\t\t\t// throw new RuntimeException();\n\t\t\t\t\tthrow new InvalidConfigException();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Check all fields have been populated\n\t\tfor(ConfigKey key : ConfigKey.values()){\n\t\t\tif( ! config.containsKey(key)){\n\t\t\t\tSystem.err.println(\"Missing configuration key: \" + key);\n\t\t\t\tthrow new InvalidConfigException();\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tcolorNameToInt();\n\t\t} catch (InvalidColourException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t// M E T H O D S\n\tpublic static String help(){\n\t\tList<String> help= new ArrayList<String>();\n\t\tfor(ConfigKey key : ConfigKey.values()){\n\t\t\thelp.add(key + \"\\t\" + Config.get(key) + \"\\t#\\t\" + key.getDescription());\n\t\t}\n\t\tList<String> table = Utils.tabulateList(help, -1);\n\t\treturn Joiner.on(\"\\n\").join(table);\n\t}\n\t\n\tprivate static String getConfigFileAsString(String source) throws IOException, InvalidConfigException{\n\t\t\n\t\tString rawConfigFile= \"\";\n\n\t\t// Is source null or empty string?\n\t\tif(source == null || source.isEmpty()){\n\t\t\t// See if default config file exists\n\t\t\tFile def= new File(System.getProperty(\"user.home\"), \".asciigenome_config\");\n\t\t\tif(def.isFile()){\n\t\t\t\trawConfigFile= FileUtils.readFileToString(def, \"UTF-8\");\n\t\t\t} else {\n\t\t\t\t// If not, read from resource\n\t\t\t\tInputStream res= Config.class.getResourceAsStream(\"/config/black_on_white.conf\");\n\t\t\t\trawConfigFile= IOUtils.toString(res, \"UTF-8\");\n\t\t\t}\n\t\t\treturn rawConfigFile;\n\t\t}\n\n\t\tsource= Utils.tildeToHomeDir(source);\n\t\t\n\t\t// Is source a local file? E.g. /path/to/my.conf\n\t\tif((new File(source)).isFile()){\n\t\t\trawConfigFile= FileUtils.readFileToString(new File(source), \"UTF-8\");\n\t\t\treturn rawConfigFile;\n\t\t}\n\t\t\n\t\t// Is source a tag matching a configuration file in resources? E.g. \"black_on_white\"\n\t\ttry{\n\t\t\tInputStream res= Config.class.getResourceAsStream(\"/config/\" + source + \".conf\");\n\t\t\trawConfigFile= IOUtils.toString(res, \"UTF-8\");\n\t\t\treturn rawConfigFile;\n\t\t} catch(Exception e){\n\t\t\t// \n\t\t}\t\t\n\t\tthrow new InvalidConfigException();\n\t\t\n\t} \n\t\n\t/** We convert the color names to the corresponding int. This is because looking up\n\t * by int is much faster than by name. \n\t * @throws InvalidColourException \n\t * */\n\tprivate static void colorNameToInt() throws InvalidColourException{\n\t\tfor(ConfigKey key : config.keySet()){\n\t\t\tif(ConfigKey.colorKeys().contains(key)){\n\t\t\t\tint colorInt = Xterm256.colorNameToXterm256(config.get(key));\n\t\t\t\tconfig.put(key, Integer.toString(colorInt));\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/** Get xterm256 color corresponding to this configuration key\n\t * */\n\tpublic static int get256Color(ConfigKey key) throws InvalidColourException{\n\t\tnew Xterm256();\n\t\treturn Xterm256.colorNameToXterm256(config.get(key));\n\t}\n\n\t/** Get value associated to this configuration key \n\t * */\n\tpublic static String get(ConfigKey key) {\n\t\treturn config.get(key);\n\t}\t\t\n\n\tpublic static void set(ConfigKey key, String value) throws InvalidColourException{\n\t\tif(ConfigKey.booleanKeys().contains(key)){\n\t\t\tboolean bool= Utils.asBoolean(value);\n\t\t\tconfig.put(key, Boolean.toString(bool));\n\t\t} \n\t\telse if(ConfigKey.integerKeys().contains(key)){\n\t\t\tInteger.valueOf(value);\n\t\t\tconfig.put(key, value);\n\t\t}\n\t\telse {\n\t\t\tconfig.put(key, value);\n\t\t\tcolorNameToInt();\n\t\t}\n\t}\n\t\n//\t/**Return the key-value map of configuration parameters\n//\t * */\n//\tpublic static Map<ConfigKey, String> getConfigMap(){\n//\t\treturn config;\n//\t}\n}", "public class InvalidColourException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class InvalidConfigException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n}", "public class InvalidGenomicCoordsException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class InvalidRecordException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class GenomicCoords implements Cloneable {\n\t\n\tpublic static final String SPACER= \"-\"; // Background character as spacer\n\tpublic static final String TICKED= \"*\"; // Char to use to mark region\n\t\n\tprivate String chrom;\n\tprivate Integer from;\n\tprivate Integer to;\n\tprivate SAMSequenceDictionary samSeqDict; // Can be null\n\t/** Size of the screen window \n\t * Only user getUserWindowSize() to access it after init at constructor.\n\t */\n\tprivate String fastaFile= null;\n\tprivate String samSeqDictSource= null; // Source of the sequence dictionary. Can be path to file of fasta, bam, genome. Or genome tag e.g. hg19. \n\tprivate byte[] refSeq= null;\n\tpublic boolean isSingleBaseResolution= false;\n\tprivate int terminalWidth;\n\tprivate List<Double> mapping;\n\t\n\t/* Constructors */\n\tpublic GenomicCoords(String region, int terminalWidth, SAMSequenceDictionary samSeqDict, String fastaFile, boolean verbose) throws InvalidGenomicCoordsException, IOException{\n\t\t\n\t\tthis.setTerminalWidth(terminalWidth);\n\t\t\n\t\tGenomicCoords xgc= parseStringToGenomicCoords(region);\n\n\t\tthis.chrom= xgc.getChrom();\n\t\tthis.from= xgc.getFrom();\n\t\tthis.to= xgc.getTo();\n\t\t\n\t\tif(from == null){ \n\t\t\tfrom= 1; \n\t\t}\n\t\t\n\t\tif(to == null){ \n\t\t\tto= from + this.getTerminalWidth() - 1;\n\t\t}\n\t\t\n\t\t// Check valid input\n\t\tif(chrom == null || (to != null && from == null) || (from > to) || from < 1 || to < 1){\n\t\t\tSystem.err.println(\"Got: \" + chrom + \":\" + from + \"-\" + to);\n\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\tthrow e;\n\t\t}\n\t\tif(samSeqDict != null && samSeqDict.size() > 0){ // If dict is present, check against it\n\t\t\tif(samSeqDict.getSequence(chrom) == null){\n\t\t\t\tif(verbose){\n\t\t\t\t\tSystem.err.println(\"\\nCannot find chromosome '\" + chrom + \"' in sequence dictionary.\");\n\t\t\t\t}\n\t\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.samSeqDict= samSeqDict;\n\t\tif(this.samSeqDict != null && this.samSeqDict.size() > 0){\n\t\t\tcorrectCoordsAgainstSeqDict(samSeqDict);\n\t\t}\n\t\tif(fastaFile != null){\n\t\t\tthis.setSamSeqDictFromFasta(fastaFile);\n\t\t\tthis.setFastaFile(fastaFile);\n\t\t}\n\t\t\n\t\tthis.update();\n\t}\n\t\n\tpublic GenomicCoords(String region, int terminalWidth, SAMSequenceDictionary samSeqDict, String fastaFile) throws InvalidGenomicCoordsException, IOException{\n\t\tthis(region, terminalWidth, samSeqDict, fastaFile, true);\n\t}\n\t\n\tGenomicCoords(int terminalWidth) throws InvalidGenomicCoordsException, IOException{ \n\t\tthis.terminalWidth= terminalWidth;\n\t};\n\n\t/**Update a bunch of fields when coordinates change*/\n\tprivate void update() throws InvalidGenomicCoordsException, IOException {\n\t\t// this.setTerminalWindowSize();\n\t\tthis.setSingleBaseResolution(); // True if one text character corresponds to 1 bp\n\t\tthis.setRefSeq();\n\t\tthis.mapping= this.seqFromToLenOut(this.getTerminalWidth());\n\t}\n\t\n\t/* Methods */\n\t\n\t/** Set genome dictionary and fasta file ref if available. See \n\t * GenomicCoords.getSamSeqDictFromAnyFile() for available inputs.\n\t * @param includeGenomeFile: Should the input data be treated as a genome file?\n\t * Set to true only if the input can be a genome file. Other files (bed, vcf, gff) \n\t * look like valid genome file and this can result in wring dictionary. \n\t * */\n\tpublic void setGenome(List<String> input, boolean includeGenomeFile) throws IOException {\n\t\t\n\t\tList<String> cleanList= new ArrayList<String>(); \n\t\tfor(String x : input){\n\t\t\tif(x != null && ! x.trim().isEmpty()){\n\t\t\t\tcleanList.add(Utils.tildeToHomeDir(x));\n\t\t\t}\n\t\t}\t\t\n\t\tif(cleanList.size() == 0){\n\t\t\treturn;\n\t\t}\t\t\n\n\t\t// Set Dictionary\n\t\tthis.setSamSeqDictFromAnySource(cleanList, includeGenomeFile);\n\t\t// Try to set fasta sequence\n\t\tfor(String x : cleanList){\n\t\t\tboolean done= true;\n\t\t\ttry{\n\t\t\t\tif(new File(x + \".fai\").exists()){\n\t\t\t\t\tthis.setFastaFile(x);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new FileNotFoundException();\n\t\t\t\t}\n\t\t\t} catch(FileNotFoundException e){\n\t\t\t\ttry {\n\t\t\t\t\tnew Faidx(new File(x));\n\t\t\t\t\t(new File(x + \".fai\")).deleteOnExit();\n\t\t\t\t\tthis.setFastaFile(x);\n\t\t\t\t} catch (Exception e1) {\n\t\t\t\t\tdone= false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(done){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void setRefSeq() throws IOException, InvalidGenomicCoordsException{\n\t\tif(this.fastaFile == null || ! this.isSingleBaseResolution){\n\t\t\tthis.refSeq= null;\n\t\t\treturn;\n\t\t}\n\t\tthis.refSeq= this.getSequenceFromFasta();\n\t}\n\t\n\tpublic byte[] getRefSeq() throws IOException, InvalidGenomicCoordsException {\n\t\tif(this.refSeq == null){\n\t\t\tthis.setRefSeq();\n\t\t}\n\t\treturn this.refSeq;\n\t}\n\t\n\t\n\tpublic byte[] getSequenceFromFasta() throws IOException{\n\t\tIndexedFastaSequenceFile faSeqFile = null;\n\t\ttry {\n\t\t\tfaSeqFile = new IndexedFastaSequenceFile(new File(this.fastaFile));\n\t\t\ttry{\n\t\t\t\tbyte[] seq= faSeqFile.getSubsequenceAt(this.chrom, this.from, this.to).getBases();\n\t\t\t\tfaSeqFile.close();\n\t\t\t\treturn seq;\n\t\t\t} catch (NullPointerException e){\n\t\t\t\tSystem.err.println(\"Cannot fetch sequence \" + this.chrom + \":\" + this.from + \"-\" + this.to +\n\t\t\t\t\t\t\" for fasta file \" + this.fastaFile);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tfaSeqFile.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\t\n\t}\n\t\n\t/**\n\t * Parse string to return coordinates. This method simply populates the fields chrom, from, to by \n\t * parsing the input string. \n\t * This object can't be used as such as there is no check for valid input. It should be used only by the constructor.\n\t * @return\n\t * @throws InvalidGenomicCoordsException \n\t * @throws IOException \n\t */\n\tprivate GenomicCoords parseStringToGenomicCoords(String x) throws InvalidGenomicCoordsException, IOException{\n\n\t\tInteger from= 1; // Default start/end coords.\n\t\tInteger to= this.getTerminalWidth();\n\t\t\n\t\tGenomicCoords xgc= new GenomicCoords(this.getTerminalWidth());\n\t\t\n\t\tif(x == null || x.isEmpty()){\n\t\t\tx= \"Undefined_contig\";\n\t\t}\n\t\t\n\t\tx= x.trim();\n\t\t\n\t\tString[] region= new String[3];\n\t\tif(x.contains(\" \")) {\n\t\t\t// Format chrom[ from [to]]\n\t\t\tregion= this.parseStringSpaceSep(x);\n\t\t} else {\n\t\t\t// Format chrom[:from[-to]]\n\t\t\tregion= this.parseStringColonSep(x);\n\t\t} \n\t\txgc.chrom= region[0];\n\t\t\n\t\tif(region[1] == null && region[2] == null) {\n\t\t\t// Only chrom present. It will not handle well chrom names containing ':'\n\t\t\txgc.from= from;\n\t\t\txgc.to= to;\n\t\t\tif(xgc.samSeqDict != null && xgc.to > samSeqDict.getSequence(xgc.chrom).getSequenceLength()){\n\t\t\t\txgc.to= samSeqDict.getSequence(xgc.chrom).getSequenceLength(); \n\t\t\t}\n\t\t} \n\t\telse if(region[2] == null) {\n\t\t\t// Only chrom and start given\n\t\t\txgc.from= Integer.parseInt(region[1]);\n\t\t\txgc.to= xgc.from + this.getTerminalWidth() - 1;\n\t\t} \n\t\telse {\n\t\t\t// chrom, start and end given\n\t\t\txgc.from= Integer.parseInt(region[1]);\n\t\t\txgc.to= Integer.parseInt(region[2]);\n\t\t}\n\t\treturn xgc;\n\n\t}\n\t\n\tprivate String[] parseStringSpaceSep(String x) throws InvalidGenomicCoordsException {\n\t\tString[] region= new String[3];\n\t\tList<String> reg = new ArrayList<String>();\n\t\tList<String> xreg= Splitter.on(\" \").omitEmptyStrings().trimResults().splitToList(x);\n\t\treg.add(xreg.get(0));\n\t\tfor(int i= 1; i < xreg.size(); i++) {\n\t\t\tif(xreg.get(i).equals(\"-\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tList<String> pos= Splitter.on(\"-\").omitEmptyStrings().trimResults().splitToList(xreg.get(i));\n\t\t\tfor(String p : pos) {\n\t\t\t\treg.add(p.replaceAll(\",\", \"\"));\n\t\t\t}\n\t\t}\n\n\t\tregion[0]= reg.get(0);\n\t\tif(reg.size() == 1) {\n\t\t\treturn region;\n\t\t}\n\t\tif(reg.size() == 2) {\n\t\t\tregion[1]= reg.get(1);\n\t\t} \n\t\telse if(reg.size() > 2) {\n\t\t\tregion[1]= reg.get(1);\n\t\t\tregion[2]= reg.get(reg.size()-1);\n\t\t} else {\n\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\tSystem.err.println(\"\\nUnexpected format for region \" + x + \"\\n\");\n\t\t\te.printStackTrace();\n\t\t\tthrow e;\n\t\t}\n\t\treturn region;\n\t}\n\n\tprivate String[] parseStringColonSep(String x) throws InvalidGenomicCoordsException {\n\n\t\tString[] region= new String[3];\n\t\t\n\t\tint nsep= StringUtils.countMatches(x, \":\");\n\t\tif(nsep == 0){\n\t\t\tregion[0]= x;\n\t\t} else {\n\t\t\tregion[0]= StringUtils.substringBeforeLast(x, \":\").trim();\n\t\t\t\n\t\t\t// Strip chromosome name, remove commas from integers.\n\t\t\tString fromTo= StringUtils.substringAfterLast(x, \":\").replaceAll(\",\", \"\").trim();\n\t\t\tnsep= StringUtils.countMatches(fromTo, \"-\");\n\t\t\tif(nsep == 0){ // Only start position given\n\t\t\t\tregion[1]= StringUtils.substringBefore(fromTo, \"-\").trim();\n\t\t\t} else if(nsep == 1){ // From and To positions given.\n\t\t\t\tregion[1]= StringUtils.substringBefore(fromTo, \"-\").trim();\n\t\t\t\tregion[2]= StringUtils.substringAfter(fromTo, \"-\").trim();\n\t\t\t} else {\n\t\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\t\tSystem.err.println(\"\\nUnexpected format for region \" + x + \"\\n\");\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\treturn region;\n\t}\n\t\n\tpublic void correctCoordsAgainstSeqDict(SAMSequenceDictionary samSeqDict) throws InvalidGenomicCoordsException, IOException{\n\n\t\tif(samSeqDict == null || samSeqDict.size() == 0){\n\t\t\t// Just check start pos\n\t\t\tif (this.from <=0 ){\n\t\t\t\tthis.from= 1;\n\t\t\t}\t\t\t\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(this.chrom == null){ // Nothing to do\n\t\t\treturn;\n\t\t}\n\t\tif(samSeqDict.getSequence(this.chrom) == null){ // Not found: Nullify everything\n\t\t\tthis.chrom= null;\n\t\t\tthis.from= null;\n\t\t\tthis.to= null;\n\t\t\treturn;\n\t\t} \n\t\t// Reset min coords\n\t\tif( this.from != null && this.from < 1) {\n\t\t\tthis.from= 1;\n\t\t}\n\t\t// Reset max coords\n\t\tif( this.from != null && this.from > samSeqDict.getSequence(this.chrom).getSequenceLength() ) {\n\t\t\tthis.from= samSeqDict.getSequence(this.chrom).getSequenceLength() - this.getGenomicWindowSize() + 1;\n\t\t\tif(this.from <= 0){\n\t\t\t\tthis.from= 1;\n\t\t\t}\n\t\t\tthis.to= this.from + this.getGenomicWindowSize() - 1;\n\t\t\tif(this.to > samSeqDict.getSequence(this.chrom).getSequenceLength()){\n\t\t\t\tthis.to= samSeqDict.getSequence(this.chrom).getSequenceLength();\n\t\t\t}\n\t\t}\n\t\tif( this.to != null && this.to > samSeqDict.getSequence(this.chrom).getSequenceLength() ) {\t\t\t\n\t\t\tthis.to= samSeqDict.getSequence(this.chrom).getSequenceLength();\n\t\t}\n\t}\n\t\n\tpublic String toString(){\n\t\tint range= this.to - this.from + 1;\n\t\treturn this.chrom + \":\" + this.from + \"-\" + this.to + \"; \" + NumberFormat.getNumberInstance(Locale.UK).format(range) + \" bp\";\n\t}\n\t\n\t/** Return current position in the form chrom:start-end */\n\tpublic String toStringRegion(){\n\t\treturn this.getChrom() + \":\" + this.getFrom() + \"-\" + this.getTo();\n\t}\n\n\t/** Get midpoint of genomic interval \n\t * */\n\tprivate int getMidpoint(){\n\t\tint range= this.to - this.from + 1;\n\t\tif(range % 2 == 1){\n\t\t\trange--;\n\t\t}\n\t\tint midpoint= range / 2 + this.from;\n\t\treturn midpoint;\n\t}\n\t\n\t/**\n\t * Rescale coords to extend them as in zooming-in/-out\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\tpublic void zoomOut() throws IOException, InvalidGenomicCoordsException{\n\t\t// If window size is 1 you need to extend it otherwise zoom will have no effect!\n\t\tif((this.to - this.from) == 0){\n\t\t\tif((this.from - 1) > 0){\n\t\t\t\t// Try to extend left by 1 bp:\n\t\t\t\tthis.from -= 1;\n\t\t\t} else {\n\t\t\t\t// Else extend right\n\t\t\t\tthis.to += 1; // But what if you have a chrom of 1bp?!\n\t\t\t}\n\t\t}\n\t\t\n\t\tint zoom= 1;\n\t\t// * Get size of window (to - from + 1)\n\t\tint range= this.to - this.from + 1;\n\t\tif(range % 2 == 1){\n\t\t\trange--;\n\t\t}\n\t\tint midpoint= this.getMidpoint();\n\n\t\t// Extend midpoint right\t\t\n\t\tlong zoomTo= midpoint + ((long)range * (long)zoom);\n\t\t\n\t\tif(zoomTo >= Integer.MAX_VALUE){\n\t\t\tSystem.err.println(\"Invalid 'to' coordinate to fetch \" + zoomTo + \" (integer overflow?)\");\n\t\t\tzoomTo= Integer.MAX_VALUE;\n\t\t}\n\t\tthis.to= (int)zoomTo;\n\t\t\n\t\t// * Extend midpoint left by window size x2 and check coords\n\t\tthis.from= midpoint - (range * zoom);\n\t\tthis.from= (this.from <= 0) ? 1 : this.from; \n\t\tif(this.samSeqDict != null && this.samSeqDict.size() > 0){\n\t\t\tif(this.samSeqDict.getSequence(this.chrom).getSequenceLength() > 0){\n\t\t\t\tthis.to= (this.to > this.samSeqDict.getSequence(this.chrom).getSequenceLength()) ? \n\t\t\t\t\t\tthis.samSeqDict.getSequence(this.chrom).getSequenceLength() : this.to;\n\t\t\t}\n\t\t}\n\t\tthis.update();\n\t}\n\n\t/**\n\t * Zoom into range. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\tpublic void zoomIn() throws IOException, InvalidGenomicCoordsException{\n\t\tfloat zoom= (float) (1/4.0);\n\t\t// * Get size of window (to - from + 1)\n\t\tint range= this.to - this.from + 1;\n\t\tif(range % 2 == 1){\n\t\t\trange--;\n\t\t}\n\t\t// * Get midpoint of range\n\t\tint midpoint= this.getMidpoint();\n\t\tint extendBy= (int) Math.rint(range * zoom);\n\t\tint newFrom= midpoint - extendBy;\n\t\tint newTo= midpoint + extendBy;\n\t\tif((newTo - newFrom + 1) < this.getUserWindowSize()){ // Reset new coords to be at least windowSize in span\n\t\t\tint diff= this.getUserWindowSize() - (newTo - newFrom + 1);\n\t\t\tif(diff % 2 == 0){\n\t\t\t\tnewFrom -= diff/2;\n\t\t\t\tnewTo += diff/2;\n\t\t\t} else {\n\t\t\t\tnewFrom -= diff/2+1;\n\t\t\t\tnewTo += diff/2;\n\t\t\t}\n\t\t\t// Check new coords are no larger then starting values\n\t\t\tnewFrom= (newFrom < this.from) ? this.from : newFrom;\n\t\t\tnewTo= (newTo > this.to) ? this.to : newTo;\n\t\t}\n\t\tthis.from= newFrom;\n\t\tthis.to= newTo;\n\t\tif(this.from > this.to){ // Not sure this can happen.\n\t\t\tthis.to= this.from;\n\t\t}\n\t\tthis.update();\n\t}\n\t\n\t/** Move coordinates to the left hand side of the current window\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic void left() throws InvalidGenomicCoordsException, IOException{\n\t\tint w= this.getUserWindowSize();\n\t\tthis.to= this.getMidpoint();\n\t\tif((this.to - this.from) < w){\n\t\t\tthis.to += (w - (this.to - this.from) - 1); \n\t\t}\n\t\tthis.update();\n\t}\n\t\n\t/** Move coordinates to the right hand side of the current window\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic void right() throws InvalidGenomicCoordsException, IOException{\n\t\tint w= this.getUserWindowSize();\n\t\tthis.from= this.getMidpoint();\n\t\tif((this.to - this.from) < w){\n\t\t\tthis.from -= (w - (this.to - this.from) - 1); \n\t\t}\n\t\tthis.update();\n\t}\n\t\n\t/**\n\t * Same as R seq(from to, length.out). See also func in Utils\n\t * @return\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\t//private List<Double> seqFromToLenOut() throws InvalidGenomicCoordsException, IOException {\n\t//\treturn seqFromToLenOut(this.getUserWindowSize());\n\t//}\n\t\n\t/**\n\t * Same as R seq(from to, length.out). See also func in Utils\n\t * @return\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\tprivate List<Double> seqFromToLenOut(int size) throws InvalidGenomicCoordsException, IOException {\n\t\t\n\t\tif(this.getFrom() == null || this.getTo() == null){\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tList<Double> mapping= new ArrayList<Double>();\n\t\t\n\t\tif(this.from < 1 || this.from > this.to){\n\t\t\tSystem.err.println(\"Invalid genome coordinates: from \" + this.from + \" to \" + this.to);\n\t\t\ttry {\n\t\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t\t} catch (InvalidGenomicCoordsException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t}\n\t\tint span= this.to - this.from + 1;\n\t\t// If the genomic span is less then screen size, reduce screen size to.\n\t\t// If genomic span == screenSize then you have a mapping one to one.\n\t\tif(span <= size){ \n\t\t\tfor(int i= this.from; i <= this.to; i++){\n\t\t\t\tmapping.add((double)i);\n\t\t\t}\n\t\t\treturn mapping;\n\t\t}\n\t\t\n\t\tdouble step= ((double)span - 1)/(size - 1);\n\t\tmapping.add((double)this.from);\n\t\tfor(int i= 1; i < size; i++){\n\t\t\tmapping.add((double)mapping.get(i-1)+step);\n\t\t}\n\t\t\n\t\t// First check last point is close enough to expectation. If so, replace last point with\n\t\t// exact desired.\n\t\tdouble diffTo= Math.abs(mapping.get(mapping.size() - 1) - this.to);\n\t\tif(diffTo > ((float)this.to * 0.001)){\n\t\t\tSystem.err.println(\"Error generating sequence:\");\n\t\t\tSystem.err.println(\"Last point: \" + mapping.get(mapping.size() - 1));\n\t\t\tSystem.err.println(\"To diff: \" + diffTo);\n\t\t\tSystem.err.println(\"Step: \" + step);\n\t\t} else {\n\t\t\tmapping.set(mapping.size()-1, (double)this.to);\n\t\t}\n\t\t\n\t\tdouble diffFrom= Math.abs(mapping.get(0) - this.from);\t\t\n\t\tif(diffFrom > 0.01 || mapping.size() != size){\n\t\t\tSystem.err.println(\"Error generating sequence:\");\n\t\t\tSystem.err.println(\"Expected size: \" + size + \"; Effective: \" + mapping.size());\n\t\t\tSystem.err.println(\"From diff: \" + diffFrom);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\treturn mapping;\n\t}\t\n\t\n\t/**Take of care you are working with double precision here. Do not use this method to \n\t * for exact calculations. \n\t * */\n\tpublic double getBpPerScreenColumn() throws InvalidGenomicCoordsException, IOException{\n\t\tList<Double> mapping = seqFromToLenOut(this.getUserWindowSize());\n\t\tdouble bpPerScreenColumn= (to - from + 1) / (double)mapping.size();\n\t\treturn bpPerScreenColumn;\n\t}\n\t\n\t/**\n\t * Produce a string representation of the current position on the chromosome\n\t * @param nDist: Distance between labels \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * @throws InvalidColourException \n\t * */\n\tpublic String getChromIdeogram(int nDist, boolean noFormat) throws InvalidGenomicCoordsException, IOException, InvalidColourException {\n\t\t\n\t\tif(this.samSeqDict == null || this.samSeqDict.size() == 0){\n\t\t\treturn null;\n\t\t}\n\t\tList<Double> positionMap = null;\n\t\ttry{\n\t\t\tpositionMap = Utils.seqFromToLenOut(1, this.samSeqDict.getSequence(this.chrom).getSequenceLength(), \n\t\t\t\t\tthis.getUserWindowSize());\n\t\t} catch (NullPointerException e){\n\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t}\n\t\t// This code taken from printableRuler() above.\n\t\tString numberLine= \"\";\n \tint prevLen= 0;\n \tint j= 0;\n\t\twhile(j < positionMap.size()){\n\t\t\tint num= (int)Math.rint(Utils.roundToSignificantFigures(positionMap.get(j), 2));\n\t\t\tString posMark= Utils.parseIntToMetricSuffix(num); // String.valueOf(num);\n\t\t\tif(j == 0){\n\t\t\t\tnumberLine= posMark;\n\t\t\t\tj += posMark.length();\n\t\t\t} else if((numberLine.length() - prevLen) >= nDist){\n\t\t\t\tprevLen= numberLine.length();\n\t\t\t\tnumberLine= numberLine + posMark;\n\t\t\t\tj += posMark.length();\n\t\t\t} else {\n\t\t\t\tnumberLine= numberLine + SPACER;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t\tList<String> map= new ArrayList<String>();\n\t\tfor(int i= 0; i < numberLine.length(); i++){\n\t\t\tmap.add(numberLine.charAt(i) +\"\");\n\t\t}\n\t\t\n\t\t// ------------------\n\t\t\n\t\tint fromTextPos= Utils.getIndexOfclosestValue(this.from, positionMap);\n\t\tint toTextPos= Utils.getIndexOfclosestValue(this.to, positionMap);\n\n\t\tboolean isFirst= true;\n\t\tint lastTick= -1;\n\t\tfor(int i= fromTextPos; i <= toTextPos; i++){\n\t\t\tif(isFirst || map.get(i).equals(SPACER)){\n\t\t\t\tmap.set(i, TICKED);\n\t\t\t\tisFirst= false;\n\t\t\t}\n\t\t\tlastTick= i;\n\t\t}\n\t\tmap.set(lastTick, TICKED);\n\t\tString ideogram= StringUtils.join(map, \"\");\n\t\tif(ideogram.length() > this.getUserWindowSize()){\n\t\t\tideogram= ideogram.substring(0, this.getUserWindowSize());\n\t\t}\n\t\tif(!noFormat){\n\t\t\tideogram= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \";38;5;\" + Config.get256Color(ConfigKey.chrom_ideogram) + \"m\" + ideogram;\n\t\t}\n\t\treturn ideogram;\n\t}\n\t\n\t/** For debugging only \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic String toStringVerbose(int windowSize) throws InvalidGenomicCoordsException, IOException{\n\t\tList<Double> mapping = seqFromToLenOut(this.getUserWindowSize());\n\t\tString str= \"Genome coords: \" + from + \"-\" + to \n\t\t\t\t+ \"; screen width: \" + mapping.size()\n\t\t\t\t+ \"; scale: \" + this.getBpPerScreenColumn() + \" bp/column\" \n\t\t\t\t+ \"; Mapping: \" + mapping;\n\t\tstr += \"\\n\";\n\t\tstr += this.toString();\n\t\treturn str;\n\t}\n\t\n\tpublic String printableGenomicRuler(int markDist, boolean noFormat) throws InvalidGenomicCoordsException, IOException, InvalidColourException{\n\t\tList<Double> mapping = this.seqFromToLenOut(this.getUserWindowSize());\n\t\tString numberLine= this.printRulerFromList(mapping, markDist, 0);\n\t\tnumberLine= numberLine.replaceFirst(\"^0 \", \"1 \"); // Force to start from 1\n\t\tnumberLine= numberLine.substring(0, this.getUserWindowSize());\n\t\tif(!noFormat){\n\t\t\tnumberLine= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \n\t\t\t\t\t\";38;5;\" + Config.get256Color(ConfigKey.ruler) +\n\t\t\t\t\t\"m\" + numberLine;\n\t\t}\n \treturn numberLine;\n }\n\n\tpublic String printablePercentRuler(int markDist, boolean noFormat) throws InvalidGenomicCoordsException, IOException, InvalidColourException{\n\t\t// List<Double> mapping = Utils.seqFromToLenOut(1, this.getUserWindowSize(), this.getUserWindowSize());\n\t\tList<Double> mapping = Utils.seqFromToLenOut(0, 1, this.getUserWindowSize());\n\t\tString numberLine= this.printRulerFromList(mapping, markDist, 2);\n\t\tnumberLine= numberLine.substring(0, this.getUserWindowSize());\n\t\tif(!noFormat){\n\t\t\tnumberLine= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \n\t\t\t\t\t\";38;5;\" + Config.get256Color(ConfigKey.ruler) +\n\t\t\t\t\t\"m\" + numberLine;\n\t\t}\n \treturn numberLine;\n }\n\t\t\n\tprivate String printRulerFromList(List<Double> marks, int markDist, int digits) throws InvalidGenomicCoordsException, IOException {\n\t\tint prevLen= 0;\n \tint i= 0;\n \t// First round numbers and see if we can round digits\n \tList<String>rMarks= new ArrayList<String>();\n \tmarkLoop:\n \tfor(int sfx : new int[]{1000000, 100000, 10000, 1000, 100, 10, 5, 1}){\n \t\trMarks.clear();\n\t \tfor(Double mark : marks){\n\t \t\tdouble n = Utils.round(mark/sfx, digits) * sfx;\n\t \t\tString str= String.format(\"%.\" + digits + \"f\", n);\n\t \t\tstr= str.replaceAll(\"^0\\\\.00\", \"0\"); // Strip leading zero if any.\n\t \t\tstr= str.replaceAll(\"^0\\\\.\", \".\"); \n\t \t\tstr= str.replaceAll(\"\\\\.00$\", \"\"); // Change x.00 to x. E.g. 1.00 -> 1\n\t \t\trMarks.add(str);\n\t \t}\n\t \tSet<String> uniq= new HashSet<String>(rMarks);\n\t \tif(uniq.size() == marks.size()){\n\t \t\t// No duplicates after rounding\n\t \t\tbreak markLoop;\n\t \t}\n \t}\n\n \tStringBuilder numberLine= new StringBuilder();\n\t\twhile(i < rMarks.size()){\n\t\t\tString label= rMarks.get(i);\n\t\t\t\n\t\t\tif(label.length() >= markDist){\n\t\t\t\t// Increase markDist if the number is bigger than the space itself\n\t\t\t\tmarkDist= label.length() + 1;\n\t\t\t}\n\t\t\tif(i == 0){\n\t\t\t\tnumberLine.append(label);\n\t\t\t\ti += label.length();\n\t\t\t} else if((numberLine.length() - prevLen) >= markDist){\n\t\t\t\tprevLen= numberLine.length();\n\t\t\t\tnumberLine.append(label);\n\t\t\t\ti += label.length();\n\t\t\t} else {\n\t\t\t\tnumberLine.append(\" \");\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn numberLine.toString();\n\t}\n\t\n\t/** Ref sequence usable for print on screen. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * @throws InvalidColourException */\n\tpublic String printableRefSeq(boolean noFormat) throws IOException, InvalidGenomicCoordsException, InvalidColourException{\n\n\t\tbyte[] refSeq= this.getRefSeq();\n\t\tif(refSeq == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tif(noFormat){\n\t\t\treturn new String(refSeq) + \"\\n\";\n\t\t} else {\n\t\t\tString faSeqStr= \"\";\n\t\t\tfor(byte c : refSeq){\n\t\t\t\t// For colour scheme see http://www.umass.edu/molvis/tutorials/dna/atgc.htm\n\t\t\t\tchar base= (char) c;\n\t\t\t\tString prefix= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \";38;5;\";\n\t\t\t\tif(base == 'A' || base == 'a'){\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_a) + \"m\" + base;\n\t\t\t\t} else if(base == 'C' || base == 'c') {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_c) + \"m\" + base;\n\t\t\t\t} else if(base == 'G' || base == 'g') {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_g) + \"m\" + base;\n\t\t\t\t} else if(base == 'T' || base == 't') {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_t) + \"m\" + base;\n\t\t\t\t} else {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_other) + \"m\" + base;\n\t\t\t\t} \n\t\t\t}\n\t\t\treturn faSeqStr + \"\\n\";\n\t\t}\n\t}\n\n\t/**\n\t * Get a SAMSequenceDictionary by querying the input files, if there is any bam, or from the indexed fasta file or from genome files.\n\t * @param testfiles List of input files\n\t * @param fasta Reference sequence\n\t * @param genome \n\t * @return\n\t * @throws IOException \n\t */\n\tprivate boolean setSamSeqDictFromAnySource(List<String> testfiles, boolean includeGenomeFile) throws IOException{\n\n\t\tboolean isSet= false;\n\t\tfor(String testfile : testfiles){ // Get sequence dict from bam, if any\t\t\t\t\n\t\t\ttry{\n\t\t\t\tisSet= this.setSamSeqDictFromBam(testfile);\n\t\t\t\tif(isSet){\n\t\t\t\t\treturn isSet;\n\t\t\t\t}\n\t\t\t} catch(Exception e){\n\t\t\t\t//\n\t\t\t}\n\t\t\ttry{\n\t\t\t\tisSet= this.setSamSeqDictFromFasta(testfile);\n\t\t\t\tif(isSet){\n\t\t\t\t\treturn isSet;\n\t\t\t\t}\n\t\t\t} catch(Exception e){\n\t\t\t\t//\n\t\t\t}\n\t\t\tif(includeGenomeFile){\n\t\t\t\ttry{\n\t\t\t\t\tisSet= this.setSamSeqDictFromGenomeFile(testfile);\n\t\t\t\t\tif(isSet){\n\t\t\t\t\t\treturn isSet;\n\t\t\t\t\t}\n\t\t\t\t} catch(Exception e){\n\t\t\t\t\t//\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// If we still haven't found a sequence dict, try looking for a VCF file.\n\t\tfor(String testfile : testfiles){ \n\t\t\ttry{\n\t\t\t\tisSet= this.setSamSeqDictFromVCF(testfile);\n\t\t\t\tif(isSet){\n\t\t\t\t\treturn isSet;\n\t\t\t\t}\n\t\t\t} catch(Exception e){\n\t\t\t\t//\n\t\t\t}\n\t\t}\n\t\treturn isSet;\n\t}\n\n\tprivate boolean setSamSeqDictFromVCF(String vcf) throws MalformedURLException {\n\n\t\tSAMSequenceDictionary samSeqDict= Utils.getVCFHeader(vcf).getSequenceDictionary();\n\t\tif(samSeqDict != null){\n\t\t\tthis.setSamSeqDictSource(new File(vcf).getAbsolutePath());\n\t\t\tthis.setSamSeqDict(samSeqDict);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\n\t}\n\n\t\n\tprivate boolean setSamSeqDictFromFasta(String fasta) throws IOException{\n\t\t\n\t\t// IndexedFastaSequenceFile fa= null;\n\t\t\n\t\ttry{\n\t\t\tif(new File(fasta + \".fai\").exists() && ! new File(fasta + \".fai\").isDirectory()){\n\t\t\t\t//\n\t\t\t} else {\n\t\t\t\tthrow new FileNotFoundException(); \n\t\t\t}\n\t\t\t// fa= new IndexedFastaSequenceFile(new File(fasta));\n\t\t} catch(FileNotFoundException e){\n\t\t\ttry {\n\t\t\t\tnew Faidx(new File(fasta));\n\t\t\t\t(new File(fasta + \".fai\")).deleteOnExit();\n\t\t\t} catch (Exception e1) {\n\t\t\t\t//\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\tBufferedReader br= new BufferedReader(new FileReader(new File(fasta + \".fai\")));\n\t\tSAMSequenceDictionary seqDict= new SAMSequenceDictionary(); // null;\n\t\twhile(true){\n\t\t\tString line= br.readLine();\n\t\t\tif(line == null){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tSAMSequenceRecord ssqRec= new SAMSequenceRecord(\n\t\t\t\t\tline.split(\"\\t\")[0], \n\t\t\t\t\tInteger.parseInt(line.split(\"\\t\")[1]));\n\t\t\tseqDict.addSequence(ssqRec);\n\t\t}\n\t\tbr.close();\n//\t\t\tfa.close();\n\t\tthis.setSamSeqDictSource(new File(fasta).getAbsolutePath());\n\t\tthis.setSamSeqDict(seqDict);\n\t\treturn true;\n//\t\t}\n//\t\tfa.close();\n//\t\treturn false;\n\t}\n\t\n\tprivate boolean setSamSeqDictFromBam(String bamfile) {\n\n\t\t/* ------------------------------------------------------ */\n\t\t/* This chunk prepares SamReader from local bam */\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tsamReader= srf.open(new File(bamfile));\n\t\t/* ------------------------------------------------------ */\n\t\t\n\t\tSAMSequenceDictionary seqDict = samReader.getFileHeader().getSequenceDictionary();\n\t\tif(seqDict != null && !seqDict.isEmpty()){\n\t\t\tthis.setSamSeqDictSource(new File(bamfile).getAbsolutePath());\n\t\t\tthis.setSamSeqDict(seqDict);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/** Get SamSequenceDictionary either from local file or from built-in resources.\n\t * If reading from resources, \"genome\" is the tag before '.genome'. E.g. \n\t * 'hg19' will read file hg19.genome \n\t * */\n\tprivate boolean setSamSeqDictFromGenomeFile(String genome) throws IOException {\n\n\t\tSAMSequenceDictionary samSeqDict= new SAMSequenceDictionary();\n\n\t\tBufferedReader reader=null;\n\t\ttry{\n\t\t\t// Attempt to read from resource\n\t\t\tInputStream res= Main.class.getResourceAsStream(\"/genomes/\" + genome + \".genome\");\n\t\t\treader= new BufferedReader(new InputStreamReader(res));\n\t\t} catch (NullPointerException e){\n\t\t\ttry{\n\t\t\t\t// Read from local file\n\t\t\t\treader= new BufferedReader(new FileReader(new File(genome)));\n\t\t\t} catch (FileNotFoundException ex){\n\t\t\t\treturn false; \n\t\t\t}\n\t\t}\n\t\t\n\t\tString line = null;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tif(line.trim().isEmpty() || line.trim().startsWith(\"#\")){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] chromLine= line.split(\"\\t\");\n\t\t\tSAMSequenceRecord sequenceRecord = new SAMSequenceRecord(chromLine[0], Integer.parseInt(chromLine[1]));\n\t\t\tsamSeqDict.addSequence(sequenceRecord);\n\t\t}\n\t\treader.close();\n\t\tthis.setSamSeqDictSource(genome);\n\t\tthis.setSamSeqDict(samSeqDict);\n\t\treturn true;\n\t}\n\n\tpublic boolean equalCoords(GenomicCoords other){\n\t\treturn this.chrom.equals(other.chrom) && this.from.equals(other.from) && this.to.equals(other.to); \n\t}\n\t\n\t/** True if all fileds in this object equla those in the other\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic boolean equalCoordsAndWindowSize(GenomicCoords other) throws InvalidGenomicCoordsException, IOException{\n\t\treturn this.equalCoords(other) && \n\t\t\t\tthis.getUserWindowSize() == other.getUserWindowSize();\n\t}\n\t\n\tpublic Object clone() {\n\t//shallow copy\n\t\ttry {\n\t\t\treturn super.clone();\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic void centerAndExtendGenomicCoords(GenomicCoords gc, int size, double slop) throws InvalidGenomicCoordsException, IOException {\n\t\t\n\t\tif(size <= 0){\n\t\t\tSystem.err.println(\"Invalid feature size. Must be > 0, got \" + size);\n\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t}\n\n\t\tif(slop > 0){\n\t\t\tdouble center= (size/2.0) + gc.getFrom();\n\t\t\tgc.from= (int)Math.rint(center - (size * slop));\n\t\t\tgc.to= (int)Math.rint(center + (size * slop));\n\t\t}\n\t\tif(slop == 0){\n\t\t\t// Decrease gc.from so that the start of the feature is in the middle of the screen\n\t\t\tint newFrom= gc.from - this.getTerminalWidth() / 2;\n\t\t\tnewFrom= newFrom < 1 ? 1 : newFrom;\n\t\t\tint newTo= newFrom + this.getTerminalWidth() - 1;\n\t\t\tgc.from= newFrom;\n\t\t\tgc.to= newTo;\n\t\t}\n\t\tif(((gc.to - gc.from)+1) < gc.getUserWindowSize()){\n\t\t\tint span= (gc.to - gc.from);\n\t\t\tint extendBy= (int)Math.rint((gc.getUserWindowSize() / 2.0) - (span / 2.0));\n\t\t\tgc.from -= extendBy;\n\t\t\tgc.to += extendBy;\n\t\t}\n\t\tgc.correctCoordsAgainstSeqDict(samSeqDict);\n\t\tthis.update();\n\t}\n\n\t/** Reset window size according to current terminal screen. \n\t * If the user reshapes the terminal window size or the font size, \n\t * detect the new size and add it to the history. \n\t * */\n\tprivate int getTerminalWidth() {\n\t\treturn this.terminalWidth;\n\t}\t\n\t\n\t/* Getters and setters */\n\n\tpublic List<Double> getMapping() {\n\t\treturn this.mapping;\n\t}\n\t\n\t/** Map using this.getUserWindowSize() as window size. Consider using \n\t * getMapping(int size) to avoid computing the terminal width for each call. */\n\t//public List<Double> getMapping() throws InvalidGenomicCoordsException, IOException {\n\t//\treturn seqFromToLenOut(this.getUserWindowSize());\n\t//}\t\n\t\n\tpublic String getChrom() {\n\t\treturn chrom;\n\t}\n\n\tpublic Integer getFrom() {\n\t\treturn from;\n\t}\n\n\tpublic Integer getTo() {\n\t\treturn to;\n\t}\n\t\n\t/** Width of the terminal screen window in number of characters. \n\t * Not to be confused with the genomic window size (as in bp) \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic int getUserWindowSize() throws InvalidGenomicCoordsException, IOException{\n\n\t\tint userWindowSize= this.getTerminalWidth();\n\t\tif(userWindowSize > this.getGenomicWindowSize()){\n\t\t\treturn this.getGenomicWindowSize();\n\t\t} else {\n\t\t\treturn userWindowSize;\n\t\t}\n\t}\n\t\n\t/** Size of genomic interval. Can be smaller than windowSize set by user. \n\t * Not to be confused with userWindowSize. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic Integer getGenomicWindowSize() throws InvalidGenomicCoordsException {\n\t\tif(this.getTo() == null || this.getFrom() == null){\n\t\t\treturn null;\n\t\t}\n\t\treturn this.to - this.from + 1;\n\t}\n\n\tpublic SAMSequenceDictionary getSamSeqDict(){\n\t\treturn this.samSeqDict;\n\t}\n\t\n\tpublic void setSamSeqDict(SAMSequenceDictionary samSeqDict){\n\t\tthis.samSeqDict= samSeqDict;\n\t}\n\t\n\tpublic String getFastaFile(){\n\t\treturn this.fastaFile;\n\t}\n\n\tprotected void setFastaFile(String fastaFile) {\n\t\tthis.fastaFile = fastaFile;\n\t}\n\n\tpublic String getSamSeqDictSource() {\n\t\tif(this.getFastaFile() != null){\n\t\t\treturn this.getFastaFile();\n\t\t}\n\t\treturn samSeqDictSource;\n\t}\n\n\tpublic void setSamSeqDictSource(String samSeqDictSource) {\n\t\tthis.samSeqDictSource = samSeqDictSource;\n\t}\n\n\t/** Extend genomic coordinates left and right by given bases. \n\t * refpoint= \"mid\": The new coordinates are given by the midpoint of the current one +/- left and right.\n\t * refpoint= \"window\": The new coordinates are the given by the current window extended left and right. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tprivate void extend(int left, int right, String refpoint) throws InvalidGenomicCoordsException, IOException {\n\t\tint newFrom= 0;\n\t\tint newTo= 0;\n\t\tif(refpoint.equals(\"mid\")){\n\t\t\tint mid= this.getMidpoint();\n\t\t\tnewFrom= mid - left;\n\t\t\tnewTo= mid + right - 1; // -1 so the window size becomes exactly right-left\n\t\t}\n\t\tif(refpoint.equals(\"window\")){\n\t\t\tnewFrom= this.getFrom() - left;\n\t\t\tnewTo= this.getTo() + right;\n\t\t}\n\t\tif(newFrom > newTo){\n\t\t\tint tmp= newFrom;\n\t\t\tnewFrom= newTo;\n\t\t\tnewTo= tmp;\n\t\t}\n\t\tthis.from= newFrom;\n\t\tthis.to= newTo;\n\t\tthis.correctCoordsAgainstSeqDict(this.getSamSeqDict());\n\t\tthis.update();\n\t}\n\t\n\t/** Apply this.extend() after having parsed cmd line args. \n\t * @throws InvalidCommandLineException \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic void cmdInputExtend(List<String> cmdInput) throws InvalidCommandLineException, InvalidGenomicCoordsException, IOException{\n\t\tList<String> args= new ArrayList<String>(cmdInput);\n\t\targs.remove(0); // Remove cmd name\n\t\t\n\t\tString refpoint= \"window\";\n\t\tif(args.contains(\"window\")){\n\t\t\targs.remove(\"window\");\n\t\t}\n\t\tif(args.contains(\"mid\")){\n\t\t\trefpoint= \"mid\";\n\t\t\targs.remove(\"mid\");\n\t\t} \n\t\tif(args.size() == 0){\n\t\t\tthrow new InvalidCommandLineException();\n\t\t}\n\t\tint left= Integer.parseInt(args.get(0));\n\t\tint right= left;\n\t\tif(args.size() > 1){\n\t\t\tright= Integer.parseInt(args.get(1));\n\t\t}\n\t\tthis.extend(left, right, refpoint);\n\t}\n\n\tpublic void setTerminalWidth(int terminalWidth) throws InvalidGenomicCoordsException, IOException {\n\t\tthis.terminalWidth= terminalWidth;\n\t\tthis.update();\n\t}\n\n\tprotected void setSingleBaseResolution() throws InvalidGenomicCoordsException, IOException {\n\t\tif(this.getGenomicWindowSize() == null){\n\t\t\tthis.isSingleBaseResolution= false;\n\t\t\treturn;\n\t\t}\n\t\tif(this.getUserWindowSize() == this.getGenomicWindowSize()){\n\t\t\tthis.isSingleBaseResolution= true;\n\t\t} else {\n\t\t\tthis.isSingleBaseResolution= false;\n\t\t}\t\t\n\t}\n\n}" ]
import static org.junit.Assert.*; import java.io.IOException; import java.sql.SQLException; import org.junit.Before; import org.junit.Test; import coloring.Config; import exceptions.InvalidColourException; import exceptions.InvalidConfigException; import exceptions.InvalidGenomicCoordsException; import exceptions.InvalidRecordException; import samTextViewer.GenomicCoords;
package tracks; public class TrackNarrowPeakTest { @Before public void prepareConfig() throws IOException, InvalidConfigException{ new Config(null); } @Test
public void testCanInitNarrorPeakTrack() throws InvalidGenomicCoordsException, IOException, ClassNotFoundException, InvalidRecordException, SQLException, InvalidColourException {
4
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/tinker/MoviePrinter.java
[ "public final class EuclideanDistance {\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public EuclideanDistance() {\r\n super();\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param p1 The first point.\r\n * @param p2 The second point.\r\n * @return The Euclidean distance.\r\n */\r\n public double distance(double p1, double p2) {\r\n double d = (p1 - p2) * (p1 - p2);\r\n return Math.sqrt(d);\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double distance(double[] point1, double[] point2) throws Exception {\r\n return Math.sqrt(distance2(point1, point2));\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double distance(int[] point1, int[] point2) throws Exception {\r\n return Math.sqrt(Long.valueOf(distance2(point1, point2)).doubleValue());\r\n }\r\n\r\n /**\r\n * Calculates the square of the Euclidean distance between two 1D points represented by real\r\n * values.\r\n * \r\n * @param p1 The first point.\r\n * @param p2 The second point.\r\n * @return The Square of Euclidean distance.\r\n */\r\n public double distance2(double p1, double p2) {\r\n return (p1 - p2) * (p1 - p2);\r\n }\r\n\r\n /**\r\n * Calculates the square of the Euclidean distance between two multidimensional points represented\r\n * by the rational vectors.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double distance2(double[] point1, double[] point2) throws Exception {\r\n if (point1.length == point2.length) {\r\n Double sum = 0D;\r\n for (int i = 0; i < point1.length; i++) {\r\n double tmp = point2[i] - point1[i];\r\n sum = sum + tmp * tmp;\r\n }\r\n return sum;\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * Calculates the square of the Euclidean distance between two multidimensional points represented\r\n * by integer vectors.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public long distance2(int[] point1, int[] point2) throws Exception {\r\n if (point1.length == point2.length) {\r\n long sum = 0;\r\n for (int i = 0; i < point1.length; i++) {\r\n sum = sum + (point2[i] - point1[i]) * (point2[i] - point1[i]);\r\n }\r\n return sum;\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * Calculates Euclidean distance between two multi-dimensional time-series of equal length.\r\n * \r\n * @param series1 The first series.\r\n * @param series2 The second series.\r\n * @return The eclidean distance.\r\n * @throws Exception if error occures.\r\n */\r\n public double seriesDistance(double[][] series1, double[][] series2) throws Exception {\r\n if (series1.length == series2.length) {\r\n Double res = 0D;\r\n for (int i = 0; i < series1.length; i++) {\r\n res = res + distance2(series1[i], series2[i]);\r\n }\r\n return Math.sqrt(res);\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * Calculates the Normalized Euclidean distance between two points.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double normalizedDistance(double[] point1, double[] point2) throws Exception {\r\n return Math.sqrt(distance2(point1, point2)) / point1.length;\r\n }\r\n\r\n /**\r\n * Implements Euclidean distance with early abandoning.\r\n * \r\n * @param series1 the first series.\r\n * @param series2 the second series.\r\n * @param cutoff the cut-off threshold\r\n * @return the distance if it is less than cutoff or Double.NAN if it is above.\r\n * \r\n * @throws Exception if error occurs.\r\n */\r\n public Double earlyAbandonedDistance(double[] series1, double[] series2, double cutoff)\r\n throws Exception {\r\n if (series1.length == series2.length) {\r\n double cutOff2 = cutoff;\r\n if (Double.MAX_VALUE != cutoff) {\r\n cutOff2 = cutoff * cutoff;\r\n }\r\n Double res = 0D;\r\n for (int i = 0; i < series1.length; i++) {\r\n res = res + distance2(series1[i], series2[i]);\r\n if (res > cutOff2) {\r\n return Double.NaN;\r\n }\r\n }\r\n return Math.sqrt(res);\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n}\r", "public enum NumerosityReductionStrategy {\n\n /** No reduction at all - all the words going make it into collection. */\n NONE(0),\n\n /** Exact - the strategy based on the exact string match. */\n EXACT(1),\n\n /** Classic - the Lin's and Keogh's MINDIST based strategy. */\n MINDIST(2);\n\n private final int index;\n\n /**\n * Constructor.\n * \n * @param index The strategy index.\n */\n NumerosityReductionStrategy(int index) {\n this.index = index;\n }\n\n /**\n * Gets the integer index of the instance.\n * \n * @return integer key of the instance.\n */\n public int index() {\n return index;\n }\n\n /**\n * Makes a strategy out of integer. 0 stands for NONE, 1 for EXACT, and 3 for MINDIST.\n * \n * @param value the key value.\n * @return the new Strategy instance.\n */\n public static NumerosityReductionStrategy fromValue(int value) {\n switch (value) {\n case 0:\n return NumerosityReductionStrategy.NONE;\n case 1:\n return NumerosityReductionStrategy.EXACT;\n case 2:\n return NumerosityReductionStrategy.MINDIST;\n default:\n throw new RuntimeException(\"Unknown index:\" + value);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public String toString() {\n switch (this.index) {\n case 0:\n return \"NONE\";\n case 1:\n return \"EXACT\";\n case 2:\n return \"MINDIST\";\n default:\n throw new RuntimeException(\"Unknown index:\" + this.index);\n }\n }\n\n /**\n * Parse the string value into an instance.\n * \n * @param value the string value.\n * @return new instance.\n */\n public static NumerosityReductionStrategy fromString(String value) {\n if (\"none\".equalsIgnoreCase(value)) {\n return NumerosityReductionStrategy.NONE;\n }\n else if (\"exact\".equalsIgnoreCase(value)) {\n return NumerosityReductionStrategy.EXACT;\n }\n else if (\"mindist\".equalsIgnoreCase(value)) {\n return NumerosityReductionStrategy.MINDIST;\n }\n else {\n throw new RuntimeException(\"Unknown index:\" + value);\n }\n }\n}", "public final class SAXProcessor {\r\n\r\n private final TSProcessor tsProcessor;\r\n private final NormalAlphabet na;\r\n private EuclideanDistance ed;\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public SAXProcessor() {\r\n super();\r\n this.tsProcessor = new TSProcessor();\r\n this.na = new NormalAlphabet();\r\n this.ed = new EuclideanDistance();\r\n }\r\n\r\n /**\r\n * Convert the timeseries into SAX string representation.\r\n * \r\n * @param ts the timeseries.\r\n * @param paaSize the PAA size.\r\n * @param cuts the alphabet cuts.\r\n * @param nThreshold the normalization thresholds.\r\n * \r\n * @return The SAX representation for timeseries.\r\n * @throws SAXException if error occurs.\r\n */\r\n public char[] ts2string(double[] ts, int paaSize, double[] cuts, double nThreshold)\r\n throws SAXException {\r\n\r\n if (paaSize == ts.length) {\r\n return tsProcessor.ts2String(tsProcessor.znorm(ts, nThreshold), cuts);\r\n }\r\n else {\r\n // perform PAA conversion\r\n double[] paa = tsProcessor.paa(tsProcessor.znorm(ts, nThreshold), paaSize);\r\n return tsProcessor.ts2String(paa, cuts);\r\n }\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via chunking and Z normalization.\r\n * \r\n * @param ts the input data.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxByChunking(double[] ts, int paaSize, double[] cuts, double nThreshold)\r\n throws SAXException {\r\n\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n // Z normalize it\r\n double[] normalizedTS = tsProcessor.znorm(ts, nThreshold);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(normalizedTS, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n // create the datastructure\r\n for (int i = 0; i < currentString.length; i++) {\r\n char c = currentString[i];\r\n int pos = (int) Math.floor(i * ts.length / currentString.length);\r\n saxFrequencyData.add(String.valueOf(c).toCharArray(), pos);\r\n }\r\n\r\n return saxFrequencyData;\r\n\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via sliding window and Z\r\n * normalization.\r\n * \r\n * @param ts the input data.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * @param strategy the NR strategy.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxViaWindow(double[] ts, int windowSize, int paaSize, double[] cuts,\r\n NumerosityReductionStrategy strategy, double nThreshold) throws SAXException {\r\n\r\n if (windowSize > ts.length) {\r\n throw new SAXException(\r\n \"Unable to saxify via window, window size is greater than the timeseries length...\");\r\n }\r\n\r\n // the resulting data structure init\r\n //\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n // scan across the time series extract sub sequences, and convert them to strings\r\n char[] previousString = null;\r\n\r\n for (int i = 0; i <= ts.length - windowSize; i++) {\r\n\r\n // fix the current subsection\r\n double[] subSection = Arrays.copyOfRange(ts, i, i + windowSize);\r\n\r\n // Z normalize it\r\n subSection = tsProcessor.znorm(subSection, nThreshold);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(subSection, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n if (null != previousString) {\r\n\r\n if (NumerosityReductionStrategy.EXACT.equals(strategy)\r\n && Arrays.equals(previousString, currentString)) {\r\n // NumerosityReduction\r\n continue;\r\n }\r\n else if (NumerosityReductionStrategy.MINDIST.equals(strategy)\r\n && checkMinDistIsZero(previousString, currentString)) {\r\n continue;\r\n }\r\n\r\n }\r\n\r\n previousString = currentString;\r\n\r\n saxFrequencyData.add(currentString, i);\r\n }\r\n\r\n // ArrayList<Integer> keys = saxFrequencyData.getAllIndices();\r\n // for (int i : keys) {\r\n // System.out.println(i + \",\" + String.valueOf(saxFrequencyData.getByIndex(i).getPayload()));\r\n // }\r\n\r\n return saxFrequencyData;\r\n\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via sliding window and Z\r\n * normalization. The difference between this function and ts2saxViaWindow is that in this\r\n * function, Z normalization occurs on entire range, rather than the sliding window.\r\n * \r\n * @param ts the input data.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * @param strategy the NR strategy.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxViaWindowGlobalZNorm(double[] ts, int windowSize, int paaSize,\r\n double[] cuts, NumerosityReductionStrategy strategy, double nThreshold) throws SAXException {\r\n\r\n // the resulting data structure init\r\n //\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n // scan across the time series extract sub sequences, and convert them to strings\r\n char[] previousString = null;\r\n\r\n // normalize the entire range\r\n double[] normalizedData = tsProcessor.znorm(ts, nThreshold);\r\n\r\n for (int i = 0; i <= ts.length - windowSize; i++) {\r\n\r\n // get the current subsection\r\n double[] subSection = Arrays.copyOfRange(normalizedData, i, i + windowSize);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(subSection, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n if (null != previousString) {\r\n\r\n if (NumerosityReductionStrategy.EXACT.equals(strategy)\r\n && Arrays.equals(previousString, currentString)) {\r\n // NumerosityReduction\r\n continue;\r\n }\r\n else if (NumerosityReductionStrategy.MINDIST.equals(strategy)\r\n && checkMinDistIsZero(previousString, currentString)) {\r\n continue;\r\n }\r\n\r\n }\r\n\r\n previousString = currentString;\r\n\r\n saxFrequencyData.add(currentString, i);\r\n }\r\n\r\n return saxFrequencyData;\r\n\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via sliding window and Z\r\n * normalization.\r\n * \r\n * @param ts the input data.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * @param strategy the NR strategy.\r\n * @param skips The list of points which shall be skipped during conversion; this feature is\r\n * particularly important when building a concatenated from pieces time series and junction shall\r\n * not make it into the grammar.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxViaWindowSkipping(double[] ts, int windowSize, int paaSize, double[] cuts,\r\n NumerosityReductionStrategy strategy, double nThreshold, ArrayList<Integer> skips)\r\n throws SAXException {\r\n\r\n // the resulting data structure init\r\n //\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n Collections.sort(skips);\r\n int cSkipIdx = 0;\r\n\r\n // scan across the time series extract sub sequences, and convert them to strings\r\n char[] previousString = null;\r\n boolean skipped = false;\r\n\r\n for (int i = 0; i < ts.length - (windowSize - 1); i++) {\r\n\r\n // skip what need to be skipped\r\n if (cSkipIdx < skips.size() && i == skips.get(cSkipIdx)) {\r\n cSkipIdx = cSkipIdx + 1;\r\n skipped = true;\r\n continue;\r\n }\r\n\r\n // fix the current subsection\r\n double[] subSection = Arrays.copyOfRange(ts, i, i + windowSize);\r\n\r\n // Z normalize it\r\n subSection = tsProcessor.znorm(subSection, nThreshold);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(subSection, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n if (!(skipped) && null != previousString) {\r\n\r\n if (NumerosityReductionStrategy.EXACT.equals(strategy)\r\n && Arrays.equals(previousString, currentString)) {\r\n // NumerosityReduction\r\n continue;\r\n }\r\n else if (NumerosityReductionStrategy.MINDIST.equals(strategy)\r\n && checkMinDistIsZero(previousString, currentString)) {\r\n continue;\r\n }\r\n\r\n }\r\n\r\n previousString = currentString;\r\n if (skipped) {\r\n skipped = false;\r\n }\r\n\r\n saxFrequencyData.add(currentString, i);\r\n }\r\n\r\n return saxFrequencyData;\r\n }\r\n\r\n /**\r\n * Compute the distance between the two chars based on the ASCII symbol codes.\r\n * \r\n * @param a The first char.\r\n * @param b The second char.\r\n * @return The distance.\r\n */\r\n public int charDistance(char a, char b) {\r\n return Math.abs(Character.getNumericValue(a) - Character.getNumericValue(b));\r\n }\r\n\r\n /**\r\n * Compute the distance between the two strings, this function use the numbers associated with\r\n * ASCII codes, i.e. distance between a and b would be 1.\r\n * \r\n * @param a The first string.\r\n * @param b The second string.\r\n * @return The pairwise distance.\r\n * @throws SAXException if length are differ.\r\n */\r\n public int strDistance(char[] a, char[] b) throws SAXException {\r\n if (a.length == b.length) {\r\n int distance = 0;\r\n for (int i = 0; i < a.length; i++) {\r\n int tDist = Math.abs(Character.getNumericValue(a[i]) - Character.getNumericValue(b[i]));\r\n distance += tDist;\r\n }\r\n return distance;\r\n }\r\n else {\r\n throw new SAXException(\"Unable to compute SAX distance, string lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * This function implements SAX MINDIST function which uses alphabet based distance matrix.\r\n * \r\n * @param a The SAX string.\r\n * @param b The SAX string.\r\n * @param distanceMatrix The distance matrix to use.\r\n * @param n the time series length (sliding window length).\r\n * @param w the number of PAA segments.\r\n * @return distance between strings.\r\n * @throws SAXException If error occurs.\r\n */\r\n public double saxMinDist(char[] a, char[] b, double[][] distanceMatrix, int n, int w)\r\n throws SAXException {\r\n if (a.length == b.length) {\r\n double dist = 0.0D;\r\n for (int i = 0; i < a.length; i++) {\r\n if (Character.isLetter(a[i]) && Character.isLetter(b[i])) {\r\n // ... forms have numeric values from 10 through 35\r\n int numA = Character.getNumericValue(a[i]) - 10;\r\n int numB = Character.getNumericValue(b[i]) - 10;\r\n int maxIdx = distanceMatrix[0].length;\r\n if (numA > (maxIdx - 1) || numA < 0 || numB > (maxIdx - 1) || numB < 0) {\r\n throw new SAXException(\r\n \"The character index greater than \" + maxIdx + \" or less than 0!\");\r\n }\r\n double localDist = distanceMatrix[numA][numB];\r\n dist = dist + localDist * localDist;\r\n }\r\n else {\r\n throw new SAXException(\"Non-literal character found!\");\r\n }\r\n }\r\n return Math.sqrt((double) n / (double) w) * Math.sqrt(dist);\r\n }\r\n else {\r\n throw new SAXException(\"Data arrays lengths are not equal!\");\r\n }\r\n }\r\n\r\n /**\r\n * Check for trivial mindist case.\r\n * \r\n * @param a first string.\r\n * @param b second string.\r\n * @return true if mindist between strings is zero.\r\n */\r\n public boolean checkMinDistIsZero(char[] a, char[] b) {\r\n for (int i = 0; i < a.length; i++) {\r\n if (charDistance(a[i], b[i]) > 1) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Computes the distance between approximated values and the real TS.\r\n * \r\n * @param ts the timeseries.\r\n * @param winSize SAX window size.\r\n * @param paaSize SAX PAA size.\r\n * @param normThreshold the normalization threshold.\r\n * @return the distance value.\r\n * @throws Exception if error occurs.\r\n */\r\n public double approximationDistancePAA(double[] ts, int winSize, int paaSize,\r\n double normThreshold) throws Exception {\r\n\r\n double resDistance = 0d;\r\n int windowCounter = 0;\r\n\r\n double pointsPerWindow = (double) winSize / (double) paaSize;\r\n\r\n for (int i = 0; i < ts.length - winSize + 1; i++) {\r\n\r\n double[] subseries = Arrays.copyOfRange(ts, i, i + winSize);\r\n\r\n if (tsProcessor.stDev(subseries) > normThreshold) {\r\n subseries = tsProcessor.znorm(subseries, normThreshold);\r\n }\r\n\r\n double[] paa = tsProcessor.paa(subseries, paaSize);\r\n\r\n windowCounter++;\r\n\r\n // essentially the distance here is the distance between the segment's\r\n // PAA value and the real TS value\r\n //\r\n double subsequenceDistance = 0.;\r\n for (int j = 0; j < subseries.length; j++) {\r\n\r\n int paaIdx = (int) Math.floor(((double) j + 0.5) / (double) pointsPerWindow);\r\n if (paaIdx < 0) {\r\n paaIdx = 0;\r\n }\r\n if (paaIdx > paa.length) {\r\n paaIdx = paa.length - 1;\r\n }\r\n\r\n subsequenceDistance = subsequenceDistance + ed.distance(paa[paaIdx], subseries[j]);\r\n }\r\n\r\n resDistance = resDistance + subsequenceDistance / subseries.length;\r\n }\r\n return resDistance / (double) windowCounter;\r\n }\r\n\r\n /**\r\n * Computes the distance between approximated values and the real TS.\r\n * \r\n * @param ts the timeseries.\r\n * @param winSize SAX window size.\r\n * @param paaSize SAX PAA size.\r\n * @param alphabetSize SAX alphabet size.\r\n * @param normThreshold the normalization threshold.\r\n * @return the distance value.\r\n * @throws Exception if error occurs.\r\n */\r\n public double approximationDistanceAlphabet(double[] ts, int winSize, int paaSize,\r\n int alphabetSize, double normThreshold) throws Exception {\r\n\r\n double resDistance = 0d;\r\n int windowCounter = 0;\r\n\r\n double[] centralLines = na.getCentralCuts(alphabetSize);\r\n double[] cuts = na.getCuts(alphabetSize);\r\n\r\n for (int i = 0; i < ts.length - winSize + 1; i++) {\r\n\r\n double[] subseries = Arrays.copyOfRange(ts, i, i + winSize);\r\n double subsequenceDistance = 0.;\r\n\r\n if (tsProcessor.stDev(subseries) > normThreshold) {\r\n subseries = tsProcessor.znorm(subseries, normThreshold);\r\n }\r\n\r\n double[] paa = tsProcessor.paa(subseries, paaSize);\r\n int[] leterIndexes = tsProcessor.ts2Index(paa, cuts);\r\n\r\n windowCounter++;\r\n\r\n // essentially the distance here is the distance between the segment's\r\n // PAA value and the real TS value\r\n //\r\n for (int j = 0; j < paa.length; j++) {\r\n // compute the alphabet central cut line\r\n int letterIdx = leterIndexes[j];\r\n double cLine = centralLines[letterIdx];\r\n subsequenceDistance = subsequenceDistance + ed.distance(cLine, paa[j]);\r\n }\r\n\r\n resDistance = resDistance + subsequenceDistance / paa.length;\r\n }\r\n\r\n return resDistance / (double) windowCounter;\r\n }\r\n\r\n /**\r\n * Converts a single time-series into map of shingle frequencies.\r\n * \r\n * @param series the time series.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA segments number.\r\n * @param alphabetSize the alphabet size.\r\n * @param strategy the numerosity reduction strategy.\r\n * @param nrThreshold the SAX normalization threshold.\r\n * @param shingleSize the shingle size.\r\n * \r\n * @return map of shingle frequencies.\r\n * @throws SAXException if error occurs.\r\n */\r\n public Map<String, Integer> ts2Shingles(double[] series, int windowSize, int paaSize,\r\n int alphabetSize, NumerosityReductionStrategy strategy, double nrThreshold, int shingleSize)\r\n throws SAXException {\r\n\r\n // build all shingles\r\n String[] alphabet = new String[alphabetSize];\r\n for (int i = 0; i < alphabetSize; i++) {\r\n alphabet[i] = String.valueOf(TSProcessor.ALPHABET[i]);\r\n }\r\n String[] allShingles = getAllPermutations(alphabet, shingleSize);\r\n\r\n // result\r\n HashMap<String, Integer> res = new HashMap<String, Integer>(allShingles.length);\r\n for (String s : allShingles) {\r\n res.put(s, 0);\r\n }\r\n\r\n // discretize\r\n SAXRecords saxData = ts2saxViaWindow(series, windowSize, paaSize, na.getCuts(alphabetSize),\r\n strategy, nrThreshold);\r\n\r\n // fill in the counts\r\n for (SAXRecord sr : saxData) {\r\n String word = String.valueOf(sr.getPayload());\r\n int frequency = sr.getIndexes().size();\r\n for (int i = 0; i <= word.length() - shingleSize; i++) {\r\n String shingle = word.substring(i, i + shingleSize);\r\n res.put(shingle, res.get(shingle) + frequency);\r\n }\r\n }\r\n\r\n return res;\r\n }\r\n\r\n /**\r\n * Get all permutations of the given alphabet of given length.\r\n * \r\n * @param alphabet the alphabet to use.\r\n * @param wordLength the word length.\r\n * @return set of permutation.\r\n */\r\n public static String[] getAllPermutations(String[] alphabet, int wordLength) {\r\n\r\n // initialize our returned list with the number of elements calculated above\r\n String[] allLists = new String[(int) Math.pow(alphabet.length, wordLength)];\r\n\r\n // lists of length 1 are just the original elements\r\n if (wordLength == 1)\r\n return alphabet;\r\n else {\r\n // the recursion--get all lists of length 3, length 2, all the way up to 1\r\n String[] allSublists = getAllPermutations(alphabet, wordLength - 1);\r\n\r\n // append the sublists to each element\r\n int arrayIndex = 0;\r\n\r\n for (int i = 0; i < alphabet.length; i++) {\r\n for (int j = 0; j < allSublists.length; j++) {\r\n // add the newly appended combination to the list\r\n allLists[arrayIndex] = alphabet[i] + allSublists[j];\r\n arrayIndex++;\r\n }\r\n }\r\n\r\n return allLists;\r\n }\r\n }\r\n\r\n /**\r\n * Generic method to convert the milliseconds into the elapsed time string.\r\n * \r\n * @param start Start timestamp.\r\n * @param finish End timestamp.\r\n * @return String representation of the elapsed time.\r\n */\r\n public static String timeToString(long start, long finish) {\r\n\r\n long millis = finish - start;\r\n\r\n if (millis < 0) {\r\n throw new IllegalArgumentException(\"Duration must be greater than zero!\");\r\n }\r\n\r\n long days = TimeUnit.MILLISECONDS.toDays(millis);\r\n millis -= TimeUnit.DAYS.toMillis(days);\r\n long hours = TimeUnit.MILLISECONDS.toHours(millis);\r\n millis -= TimeUnit.HOURS.toMillis(hours);\r\n long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);\r\n millis -= TimeUnit.MINUTES.toMillis(minutes);\r\n long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);\r\n millis -= TimeUnit.SECONDS.toMillis(seconds);\r\n\r\n StringBuilder sb = new StringBuilder(64);\r\n sb.append(days);\r\n sb.append(\"d\");\r\n sb.append(hours);\r\n sb.append(\"h\");\r\n sb.append(minutes);\r\n sb.append(\"m\");\r\n sb.append(seconds);\r\n sb.append(\"s\");\r\n sb.append(millis);\r\n sb.append(\"ms\");\r\n\r\n return sb.toString();\r\n\r\n }\r\n}\r", "public class TSProcessor {\r\n\r\n private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;\r\n\r\n /** The latin alphabet, lower case letters a-z. */\r\n public static final char[] ALPHABET = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\r\n 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };\r\n\r\n // static block - we instantiate the logger\r\n //\r\n private static final Logger LOGGER = LoggerFactory.getLogger(TSProcessor.class);\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public TSProcessor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Reads timeseries from a file. Assumes that file has a single double value on every line.\r\n * Assigned timestamps are the line numbers.\r\n * \r\n * @param filename The file to read from.\r\n * @param columnIdx The column index.\r\n * @param sizeLimit The number of lines to read, 0 == all.\r\n * @return data.\r\n * @throws IOException if error occurs.\r\n * @throws SAXException if error occurs.\r\n */\r\n public static double[] readFileColumn(String filename, int columnIdx, int sizeLimit)\r\n throws IOException, SAXException {\r\n\r\n // make sure the path exists\r\n Path path = Paths.get(filename);\r\n if (!(Files.exists(path))) {\r\n throw new SAXException(\"unable to load data - data source not found.\");\r\n }\r\n\r\n BufferedReader br = new BufferedReader(\r\n new InputStreamReader(new FileInputStream(filename), \"UTF-8\"));\r\n\r\n return readTS(br, columnIdx, sizeLimit);\r\n }\r\n\r\n /**\r\n * Reads timeseries from a file. Assumes that file has a single double value on every line.\r\n * Assigned timestamps are the line numbers.\r\n * \r\n * @param br The reader to use.\r\n * @param columnIdx The column index.\r\n * @param sizeLimit The number of lines to read, 0 == all.\r\n * @return data.\r\n * @throws IOException if error occurs.\r\n * @throws SAXException if error occurs.\r\n */\r\n public static double[] readTS(BufferedReader br, int columnIdx, int sizeLimit)\r\n throws IOException, SAXException {\r\n ArrayList<Double> preRes = new ArrayList<Double>();\r\n int lineCounter = 0;\r\n\r\n String line = null;\r\n while ((line = br.readLine()) != null) {\r\n String[] split = line.trim().split(\"\\\\s+\");\r\n if (split.length < columnIdx) {\r\n String message = \"Unable to read data from column \" + columnIdx;\r\n br.close();\r\n throw new SAXException(message);\r\n }\r\n String str = split[columnIdx];\r\n double num = Double.NaN;\r\n try {\r\n num = Double.valueOf(str);\r\n }\r\n catch (NumberFormatException e) {\r\n LOGGER.info(\"Skipping the row \" + lineCounter + \" with value \\\"\" + str + \"\\\"\");\r\n continue;\r\n }\r\n preRes.add(num);\r\n lineCounter++;\r\n if ((0 != sizeLimit) && (lineCounter >= sizeLimit)) {\r\n break;\r\n }\r\n }\r\n br.close();\r\n double[] res = new double[preRes.size()];\r\n for (int i = 0; i < preRes.size(); i++) {\r\n res[i] = preRes.get(i);\r\n }\r\n return res;\r\n\r\n }\r\n\r\n /**\r\n * Read at least N elements from the one-column file.\r\n * \r\n * @param dataFileName the file name.\r\n * @param loadLimit the load limit.\r\n * @return the read data or empty array if nothing to load.\r\n * @throws SAXException if error occurs.\r\n * @throws IOException if error occurs.\r\n */\r\n public double[] readTS(String dataFileName, int loadLimit) throws SAXException, IOException {\r\n\r\n Path path = Paths.get(dataFileName);\r\n if (!(Files.exists(path))) {\r\n throw new SAXException(\"unable to load data - data source not found.\");\r\n }\r\n\r\n BufferedReader reader = Files.newBufferedReader(path, DEFAULT_CHARSET);\r\n\r\n return readTS(reader, 0, loadLimit);\r\n\r\n }\r\n\r\n /**\r\n * Finds the maximal value in timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The max value.\r\n */\r\n public double max(double[] series) {\r\n double max = Double.MIN_VALUE;\r\n for (int i = 0; i < series.length; i++) {\r\n if (max < series[i]) {\r\n max = series[i];\r\n }\r\n }\r\n return max;\r\n }\r\n\r\n /**\r\n * Finds the minimal value in timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The min value.\r\n */\r\n public double min(double[] series) {\r\n double min = Double.MAX_VALUE;\r\n for (int i = 0; i < series.length; i++) {\r\n if (min > series[i]) {\r\n min = series[i];\r\n }\r\n }\r\n return min;\r\n }\r\n\r\n /**\r\n * Computes the mean value of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The mean value.\r\n */\r\n public double mean(double[] series) {\r\n double res = 0D;\r\n int count = 0;\r\n for (double tp : series) {\r\n res += tp;\r\n count += 1;\r\n\r\n }\r\n if (count > 0) {\r\n return res / ((Integer) count).doubleValue();\r\n }\r\n return Double.NaN;\r\n }\r\n\r\n /**\r\n * Computes the mean value of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The mean value.\r\n */\r\n public double mean(int[] series) {\r\n double res = 0D;\r\n int count = 0;\r\n for (int tp : series) {\r\n res += (double) tp;\r\n count += 1;\r\n\r\n }\r\n if (count > 0) {\r\n return res / ((Integer) count).doubleValue();\r\n }\r\n return Double.NaN;\r\n }\r\n\r\n /**\r\n * Computes the median value of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The median value.\r\n */\r\n public double median(double[] series) {\r\n double[] clonedSeries = series.clone();\r\n Arrays.sort(clonedSeries);\r\n\r\n double median;\r\n if (clonedSeries.length % 2 == 0) {\r\n median = (clonedSeries[clonedSeries.length / 2]\r\n + (double) clonedSeries[clonedSeries.length / 2 - 1]) / 2;\r\n }\r\n else {\r\n median = clonedSeries[clonedSeries.length / 2];\r\n }\r\n return median;\r\n }\r\n\r\n /**\r\n * Compute the variance of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The variance.\r\n */\r\n public double var(double[] series) {\r\n double res = 0D;\r\n double mean = mean(series);\r\n int count = 0;\r\n for (double tp : series) {\r\n res += (tp - mean) * (tp - mean);\r\n count += 1;\r\n }\r\n if (count > 0) {\r\n return res / ((Integer) (count - 1)).doubleValue();\r\n }\r\n return Double.NaN;\r\n }\r\n\r\n /**\r\n * Speed-optimized implementation.\r\n * \r\n * @param series The timeseries.\r\n * @return the standard deviation.\r\n */\r\n public double stDev(double[] series) {\r\n double num0 = 0D;\r\n double sum = 0D;\r\n int count = 0;\r\n for (double tp : series) {\r\n num0 = num0 + tp * tp;\r\n sum = sum + tp;\r\n count += 1;\r\n }\r\n double len = ((Integer) count).doubleValue();\r\n return Math.sqrt((len * num0 - sum * sum) / (len * (len - 1)));\r\n }\r\n\r\n /**\r\n * Z-Normalize routine.\r\n * \r\n * @param series the input timeseries.\r\n * @param normalizationThreshold the zNormalization threshold value.\r\n * @return Z-normalized time-series.\r\n */\r\n public double[] znorm(double[] series, double normalizationThreshold) {\r\n double[] res = new double[series.length];\r\n double sd = stDev(series);\r\n if (sd < normalizationThreshold) {\r\n // return series.clone();\r\n // return array of zeros\r\n return res;\r\n }\r\n double mean = mean(series);\r\n for (int i = 0; i < res.length; i++) {\r\n res[i] = (series[i] - mean) / sd;\r\n }\r\n return res;\r\n }\r\n\r\n /**\r\n * Approximate the timeseries using PAA. If the timeseries has some NaN's they are handled as\r\n * follows: 1) if all values of the piece are NaNs - the piece is approximated as NaN, 2) if there\r\n * are some (more or equal one) values happened to be in the piece - algorithm will handle it as\r\n * usual - getting the mean.\r\n * \r\n * @param ts The timeseries to approximate.\r\n * @param paaSize The desired length of approximated timeseries.\r\n * @return PAA-approximated timeseries.\r\n * @throws SAXException if error occurs.\r\n * \r\n */\r\n public double[] paa(double[] ts, int paaSize) throws SAXException {\r\n // fix the length\r\n int len = ts.length;\r\n if (len < paaSize) {\r\n throw new SAXException(\"PAA size can't be greater than the timeseries size.\");\r\n }\r\n // check for the trivial case\r\n if (len == paaSize) {\r\n return Arrays.copyOf(ts, ts.length);\r\n }\r\n else {\r\n double[] paa = new double[paaSize];\r\n double pointsPerSegment = (double) len / (double) paaSize;\r\n double[] breaks = new double[paaSize + 1];\r\n for (int i = 0; i < paaSize + 1; i++) {\r\n breaks[i] = i * pointsPerSegment;\r\n }\r\n\r\n for (int i = 0; i < paaSize; i++) {\r\n double segStart = breaks[i];\r\n double segEnd = breaks[i + 1];\r\n\r\n double fractionStart = Math.ceil(segStart) - segStart;\r\n double fractionEnd = segEnd - Math.floor(segEnd);\r\n\r\n int fullStart = Double.valueOf(Math.floor(segStart)).intValue();\r\n int fullEnd = Double.valueOf(Math.ceil(segEnd)).intValue();\r\n\r\n double[] segment = Arrays.copyOfRange(ts, fullStart, fullEnd);\r\n\r\n if (fractionStart > 0) {\r\n segment[0] = segment[0] * fractionStart;\r\n }\r\n\r\n if (fractionEnd > 0) {\r\n segment[segment.length - 1] = segment[segment.length - 1] * fractionEnd;\r\n }\r\n\r\n double elementsSum = 0.0;\r\n for (double e : segment) {\r\n elementsSum = elementsSum + e;\r\n }\r\n\r\n paa[i] = elementsSum / pointsPerSegment;\r\n\r\n }\r\n return paa;\r\n }\r\n }\r\n\r\n /**\r\n * Converts the timeseries into string using given cuts intervals. Useful for not-normal\r\n * distribution cuts.\r\n * \r\n * @param vals The timeseries.\r\n * @param cuts The cut intervals.\r\n * @return The timeseries SAX representation.\r\n */\r\n public char[] ts2String(double[] vals, double[] cuts) {\r\n char[] res = new char[vals.length];\r\n for (int i = 0; i < vals.length; i++) {\r\n res[i] = num2char(vals[i], cuts);\r\n }\r\n return res;\r\n }\r\n\r\n /**\r\n * Convert the timeseries into the index using SAX cuts.\r\n * \r\n * @param series The timeseries to convert.\r\n * @param cuts The alphabet cuts.\r\n * @return SAX cuts indices.\r\n * @throws Exception if error occurs.\r\n */\r\n public int[] ts2Index(double[] series, double[] cuts) throws Exception {\r\n int[] res = new int[series.length];\r\n for (int i = 0; i < series.length; i++) {\r\n res[i] = num2index(series[i], cuts);\r\n }\r\n return res;\r\n }\r\n\r\n /**\r\n * Get mapping of a number to char.\r\n * \r\n * @param value the value to map.\r\n * @param cuts the array of intervals.\r\n * @return character corresponding to numeric value.\r\n */\r\n public char num2char(double value, double[] cuts) {\r\n int idx = 0;\r\n if (value >= 0) {\r\n idx = cuts.length;\r\n while ((idx > 0) && (cuts[idx - 1] > value)) {\r\n idx--;\r\n }\r\n }\r\n else {\r\n while ((idx < cuts.length) && (cuts[idx] <= value)) {\r\n idx++;\r\n }\r\n }\r\n return ALPHABET[idx];\r\n }\r\n\r\n /**\r\n * Converts index into char.\r\n * \r\n * @param idx The index value.\r\n * @return The char by index.\r\n */\r\n public char num2char(int idx) {\r\n return ALPHABET[idx];\r\n }\r\n\r\n /**\r\n * Get mapping of number to cut index.\r\n * \r\n * @param value the value to map.\r\n * @param cuts the array of intervals.\r\n * @return character corresponding to numeric value.\r\n */\r\n public int num2index(double value, double[] cuts) {\r\n int count = 0;\r\n while ((count < cuts.length) && (cuts[count] <= value)) {\r\n count++;\r\n }\r\n return count;\r\n }\r\n\r\n /**\r\n * Extract subseries out of series.\r\n * \r\n * @param series The series array.\r\n * @param start the fragment start.\r\n * @param end the fragment end.\r\n * @return The subseries.\r\n * @throws IndexOutOfBoundsException If error occurs.\r\n */\r\n public double[] subseriesByCopy(double[] series, int start, int end)\r\n throws IndexOutOfBoundsException {\r\n if ((start > end) || (start < 0) || (end > series.length)) {\r\n throw new IndexOutOfBoundsException(\"Unable to extract subseries, series length: \"\r\n + series.length + \", start: \" + start + \", end: \" + String.valueOf(end - start));\r\n }\r\n return Arrays.copyOfRange(series, start, end);\r\n }\r\n\r\n /**\r\n * Prettyfies the timeseries for screen output.\r\n * \r\n * @param series the data.\r\n * @param df the number format to use.\r\n * \r\n * @return The timeseries formatted for screen output.\r\n */\r\n public String seriesToString(double[] series, NumberFormat df) {\r\n StringBuffer sb = new StringBuffer();\r\n sb.append('[');\r\n for (double d : series) {\r\n sb.append(df.format(d)).append(',');\r\n }\r\n sb.delete(sb.length() - 2, sb.length() - 1).append(\"]\");\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * Normalizes data in interval 0-1.\r\n * \r\n * @param data the dataset.\r\n * @return normalized dataset.\r\n */\r\n public double[] normOne(double[] data) {\r\n double[] res = new double[data.length];\r\n double max = max(data);\r\n for (int i = 0; i < data.length; i++) {\r\n res[i] = data[i] / max;\r\n }\r\n return res;\r\n }\r\n\r\n}\r", "public class HeatChart {\n\n /**\n * A basic logarithmic scale value of 0.3.\n */\n public static final double SCALE_LOGARITHMIC = 0.3;\n\n /**\n * The linear scale value of 1.0.\n */\n public static final double SCALE_LINEAR = 1.0;\n\n /**\n * A basic exponential scale value of 3.0.\n */\n public static final double SCALE_EXPONENTIAL = 3;\n\n // x, y, z data values.\n private double[][] zValues;\n private Object[] xValues;\n private Object[] yValues;\n\n private boolean xValuesHorizontal;\n private boolean yValuesHorizontal;\n\n // General chart settings.\n private Dimension cellSize;\n private Dimension chartSize;\n private int margin;\n private Color backgroundColour;\n\n // Title settings.\n private String title;\n private Font titleFont;\n private Color titleColour;\n private Dimension titleSize;\n private int titleAscent;\n\n // Axis settings.\n private int axisThickness;\n private Color axisColour;\n private Font axisLabelsFont;\n private Color axisLabelColour;\n private String xAxisLabel;\n private String yAxisLabel;\n private Color axisValuesColour;\n private Font axisValuesFont; // The font size will be considered the maximum font size - it may be\n // smaller if needed to fit in.\n private int xAxisValuesFrequency;\n private int yAxisValuesFrequency;\n private boolean showXAxisValues;\n private boolean showYAxisValues;\n\n // Generated axis properties.\n private int xAxisValuesHeight;\n private int xAxisValuesWidthMax;\n\n private int yAxisValuesHeight;\n private int yAxisValuesAscent;\n private int yAxisValuesWidthMax;\n\n private Dimension xAxisLabelSize;\n private int xAxisLabelDescent;\n\n private Dimension yAxisLabelSize;\n private int yAxisLabelAscent;\n\n // Heat map colour settings.\n private Color highValueColour;\n private Color lowValueColour;\n\n // How many RGB steps there are between the high and low colours.\n // private int colourValueDistance;\n\n private double lowValue;\n private double highValue;\n\n // Key co-ordinate positions.\n private Point heatMapTL;\n private Point heatMapBR;\n private Point heatMapC;\n\n // Heat map dimensions.\n private Dimension heatMapSize;\n\n // Control variable for mapping z-values to colours.\n private double colourScale;\n\n /**\n * Constructs a heatmap for the given z-values against x/y-values that by default will be the\n * values 0 to n-1, where n is the number of columns or rows.\n * \n * @param zValues the z-values, where each element is a row of z-values in the resultant heat\n * chart.\n */\n public HeatChart(double[][] zValues) {\n this(zValues, min(zValues), max(zValues));\n }\n\n /**\n * Constructs a heatmap for the given z-values against x/y-values that by default will be the\n * values 0 to n-1, where n is the number of columns or rows.\n * \n * @param zValues the z-values, where each element is a row of z-values in the resultant heat\n * chart.\n * @param low the minimum possible value, which may or may not appear in the z-values.\n * @param high the maximum possible value, which may or may not appear in the z-values.\n */\n public HeatChart(double[][] zValues, double low, double high) {\n this.zValues = zValues;\n this.lowValue = low;\n this.highValue = high;\n\n // Default x/y-value settings.\n setXValues(0, 1);\n setYValues(0, 1);\n\n // Default chart settings.\n this.cellSize = new Dimension(20, 20);\n // this.margin = 10;\n this.margin = 10;\n this.backgroundColour = Color.WHITE;\n\n // Default title settings.\n this.title = null;\n // this.titleFont = new Font(\"Sans-Serif\", Font.BOLD, 16);\n this.titleFont = new Font(\"Sans-Serif\", Font.BOLD, 12);\n this.titleColour = Color.BLACK;\n\n // Default axis settings.\n this.xAxisLabel = null;\n this.yAxisLabel = null;\n this.axisThickness = 2;\n this.axisColour = Color.BLACK;\n // this.axisLabelsFont = new Font(\"Sans-Serif\", Font.PLAIN, 12);\n this.axisLabelsFont = new Font(\"Sans-Serif\", Font.PLAIN, 10);\n this.axisLabelColour = Color.BLACK;\n this.axisValuesColour = Color.BLACK;\n // this.axisValuesFont = new Font(\"Sans-Serif\", Font.PLAIN, 10);\n this.axisValuesFont = new Font(\"Sans-Serif\", Font.PLAIN, 8);\n this.xAxisValuesFrequency = 1;\n this.xAxisValuesHeight = 0;\n this.xValuesHorizontal = false;\n // this.showXAxisValues = true;\n this.showXAxisValues = false;\n // this.showYAxisValues = true;\n this.showYAxisValues = false;\n this.yAxisValuesFrequency = 1;\n this.yAxisValuesHeight = 0;\n this.yValuesHorizontal = true;\n\n // Default heatmap settings.\n this.highValueColour = Color.BLACK;\n this.lowValueColour = Color.WHITE;\n this.colourScale = SCALE_LINEAR;\n\n // updateColourDistance();\n }\n\n /**\n * Returns the low value. This is the value at which the low value colour will be applied.\n * \n * @return the low value.\n */\n public double getLowValue() {\n return lowValue;\n }\n\n /**\n * Returns the high value. This is the value at which the high value colour will be applied.\n * \n * @return the high value.\n */\n public double getHighValue() {\n return highValue;\n }\n\n /**\n * Returns the 2-dimensional array of z-values currently in use. Each element is a double array\n * which represents one row of the heat map, or all the z-values for one y-value.\n * \n * @return an array of the z-values in current use, that is, those values which will define the\n * colour of each cell in the resultant heat map.\n */\n public double[][] getZValues() {\n return zValues;\n }\n\n /**\n * Replaces the z-values array. See the {@link #setZValues(double[][], double, double)} method for\n * an example of z-values. The smallest and largest values in the array are used as the minimum\n * and maximum values respectively.\n * \n * @param zValues the array to replace the current array with. The number of elements in each\n * inner array must be identical.\n */\n public void setZValues(double[][] zValues) {\n setZValues(zValues, min(zValues), max(zValues));\n }\n\n /**\n * Replaces the z-values array. The number of elements should match the number of y-values, with\n * each element containing a double array with an equal number of elements that matches the number\n * of x-values. Use this method where the minimum and maximum values possible are not contained\n * within the dataset.\n * \n * @param zValues the array to replace the current array with. The number of elements in each\n * inner array must be identical.\n * @param low the minimum possible value, which may or may not appear in the z-values.\n * @param high the maximum possible value, which may or may not appear in the z-values.\n */\n public void setZValues(double[][] zValues, double low, double high) {\n this.zValues = zValues;\n this.lowValue = low;\n this.highValue = high;\n }\n\n /**\n * Sets the x-values which are plotted along the x-axis. The x-values are calculated based upon\n * the indexes of the z-values array:\n * \n * <pre>\n * \n * {@code\n * \n * <pre>\n * x-value = x-offset + (column-index * x-interval)\n * \n </pre>\n \n * \n * } *\n * </pre>\n * \n * <p>\n * The x-interval defines the gap between each x-value and the x-offset is applied to each value\n * to offset them all from zero.\n * \n * <p>\n * Alternatively the x-values can be set more directly with the <code>setXValues(Object[])</code>\n * method.\n * \n * @param xOffset an offset value to be applied to the index of each z-value element.\n * @param xInterval an interval that will separate each x-value item.\n */\n public void setXValues(double xOffset, double xInterval) {\n // Update the x-values according to the offset and interval.\n xValues = new Object[zValues[0].length];\n for (int i = 0; i < zValues[0].length; i++) {\n xValues[i] = xOffset + (i * xInterval);\n }\n }\n\n /**\n * Sets the x-values which are plotted along the x-axis. The given x-values array must be the same\n * length as the z-values array has columns. Each of the x-values elements will be displayed\n * according to their toString representation.\n * \n * @param xValues an array of elements to be displayed as values along the x-axis.\n */\n public void setXValues(Object[] xValues) {\n this.xValues = xValues;\n }\n\n /**\n * Sets the y-values which are plotted along the y-axis. The y-values are calculated based upon\n * the indexes of the z-values array:\n * \n * <pre>\n * \n * {@code\n * \n * <pre>\n * y-value = y-offset + (column-index * y-interval)\n * \n </pre>\n \n * \n * }\n * </pre>\n * \n * <p>\n * The y-interval defines the gap between each y-value and the y-offset is applied to each value\n * to offset them all from zero.\n * \n * <p>\n * Alternatively the y-values can be set more directly with the <code>setYValues(Object[])</code>\n * method.\n * \n * @param yOffset an offset value to be applied to the index of each z-value element.\n * @param yInterval an interval that will separate each y-value item.\n */\n public void setYValues(double yOffset, double yInterval) {\n // Update the y-values according to the offset and interval.\n yValues = new Object[zValues.length];\n for (int i = 0; i < zValues.length; i++) {\n yValues[i] = yOffset + (i * yInterval);\n }\n }\n\n /**\n * Sets the y-values which are plotted along the y-axis. The given y-values array must be the same\n * length as the z-values array has columns. Each of the y-values elements will be displayed\n * according to their toString representation.\n * \n * @param yValues an array of elements to be displayed as values along the y-axis.\n */\n public void setYValues(Object[] yValues) {\n this.yValues = yValues;\n }\n\n /**\n * Returns the x-values which are currently set to display along the x-axis. The array that is\n * returned is either that which was explicitly set with <code>setXValues(Object[])</code> or that\n * was generated from the offset and interval that were given to\n * <code>setXValues(double, double)</code>, in which case the object type of each element will be\n * <code>Double</code>.\n * \n * @return an array of the values that are to be displayed along the x-axis.\n */\n public Object[] getXValues() {\n return xValues;\n }\n\n /**\n * Returns the y-values which are currently set to display along the y-axis. The array that is\n * returned is either that which was explicitly set with <code>setYValues(Object[])</code> or that\n * was generated from the offset and interval that were given to\n * <code>setYValues(double, double)</code>, in which case the object type of each element will be\n * <code>Double</code>.\n * \n * @return an array of the values that are to be displayed along the y-axis.\n */\n public Object[] getYValues() {\n return yValues;\n }\n\n /**\n * Sets whether the text of the values along the x-axis should be drawn horizontally\n * left-to-right, or vertically top-to-bottom.\n * \n * @param xValuesHorizontal true if x-values should be drawn horizontally, false if they should be\n * drawn vertically.\n */\n public void setXValuesHorizontal(boolean xValuesHorizontal) {\n this.xValuesHorizontal = xValuesHorizontal;\n }\n\n /**\n * Returns whether the text of the values along the x-axis are to be drawn horizontally\n * left-to-right, or vertically top-to-bottom.\n * \n * @return true if the x-values will be drawn horizontally, false if they will be drawn\n * vertically.\n */\n public boolean isXValuesHorizontal() {\n return xValuesHorizontal;\n }\n\n /**\n * Sets whether the text of the values along the y-axis should be drawn horizontally\n * left-to-right, or vertically top-to-bottom.\n * \n * @param yValuesHorizontal true if y-values should be drawn horizontally, false if they should be\n * drawn vertically.\n */\n public void setYValuesHorizontal(boolean yValuesHorizontal) {\n this.yValuesHorizontal = yValuesHorizontal;\n }\n\n /**\n * Returns whether the text of the values along the y-axis are to be drawn horizontally\n * left-to-right, or vertically top-to-bottom.\n * \n * @return true if the y-values will be drawn horizontally, false if they will be drawn\n * vertically.\n */\n public boolean isYValuesHorizontal() {\n return yValuesHorizontal;\n }\n\n /**\n * Sets the width of each individual cell that constitutes a value in x,y,z data space. By setting\n * the cell width, any previously set chart width will be overwritten with a value calculated\n * based upon this value and the number of cells in there are along the x-axis.\n * \n * @param cellWidth the new width to use for each individual data cell.\n * @deprecated As of release 0.6, replaced by {@link #setCellSize(Dimension)}\n */\n @Deprecated\n public void setCellWidth(int cellWidth) {\n setCellSize(new Dimension(cellWidth, cellSize.height));\n }\n\n /**\n * Returns the width of each individual data cell that constitutes a value in the x,y,z space.\n * \n * @return the width of each cell.\n * @deprecated As of release 0.6, replaced by {@link #getCellSize}\n */\n @Deprecated\n public int getCellWidth() {\n return cellSize.width;\n }\n\n /**\n * Sets the height of each individual cell that constitutes a value in x,y,z data space. By\n * setting the cell height, any previously set chart height will be overwritten with a value\n * calculated based upon this value and the number of cells in there are along the y-axis.\n * \n * @param cellHeight the new height to use for each individual data cell.\n * @deprecated As of release 0.6, replaced by {@link #setCellSize(Dimension)}\n */\n @Deprecated\n public void setCellHeight(int cellHeight) {\n setCellSize(new Dimension(cellSize.width, cellHeight));\n }\n\n /**\n * Returns the height of each individual data cell that constitutes a value in the x,y,z space.\n * \n * @return the height of each cell.\n * @deprecated As of release 0.6, replaced by {@link #getCellSize()}\n */\n @Deprecated\n public int getCellHeight() {\n return cellSize.height;\n }\n\n /**\n * Sets the size of each individual cell that constitutes a value in x,y,z data space. By setting\n * the cell size, any previously set chart size will be overwritten with a value calculated based\n * upon this value and the number of cells along each axis.\n * \n * @param cellSize the new size to use for each individual data cell.\n * @since 0.6\n */\n public void setCellSize(Dimension cellSize) {\n this.cellSize = cellSize;\n }\n\n /**\n * Returns the size of each individual data cell that constitutes a value in the x,y,z space.\n * \n * @return the size of each individual data cell.\n * @since 0.6\n */\n public Dimension getCellSize() {\n return cellSize;\n }\n\n /**\n * Returns the width of the chart in pixels as calculated according to the cell dimensions, chart\n * margin and other size settings.\n * \n * @return the width in pixels of the chart image to be generated.\n * @deprecated As of release 0.6, replaced by {@link #getChartSize()}\n */\n @Deprecated\n public int getChartWidth() {\n return chartSize.width;\n }\n\n /**\n * Returns the height of the chart in pixels as calculated according to the cell dimensions, chart\n * margin and other size settings.\n * \n * @return the height in pixels of the chart image to be generated.\n * @deprecated As of release 0.6, replaced by {@link #getChartSize()}\n */\n @Deprecated\n public int getChartHeight() {\n return chartSize.height;\n }\n\n /**\n * Returns the size of the chart in pixels as calculated according to the cell dimensions, chart\n * margin and other size settings.\n * \n * @return the size in pixels of the chart image to be generated.\n * @since 0.6\n */\n public Dimension getChartSize() {\n return chartSize;\n }\n\n /**\n * Returns the String that will be used as the title of any successive calls to generate a chart.\n * \n * @return the title of the chart.\n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Sets the String that will be used as the title of any successive calls to generate a chart. The\n * title will be displayed centralised horizontally at the top of any generated charts.\n * \n * <p>\n * If the title is set to <tt>null</tt> then no title will be displayed.\n * \n * <p>\n * Defaults to null.\n * \n * @param title the chart title to set.\n */\n public void setTitle(String title) {\n this.title = title;\n }\n\n /**\n * Returns the String that will be displayed as a description of the x-axis in any generated\n * charts.\n * \n * @return the display label describing the x-axis.\n */\n public String getXAxisLabel() {\n return xAxisLabel;\n }\n\n /**\n * Sets the String that will be displayed as a description of the x-axis in any generated charts.\n * The label will be displayed horizontally central of the x-axis bar.\n * \n * <p>\n * If the xAxisLabel is set to <tt>null</tt> then no label will be displayed.\n * \n * <p>\n * Defaults to null.\n * \n * @param xAxisLabel the label to be displayed describing the x-axis.\n */\n public void setXAxisLabel(String xAxisLabel) {\n this.xAxisLabel = xAxisLabel;\n }\n\n /**\n * Returns the String that will be displayed as a description of the y-axis in any generated\n * charts.\n * \n * @return the display label describing the y-axis.\n */\n public String getYAxisLabel() {\n return yAxisLabel;\n }\n\n /**\n * Sets the String that will be displayed as a description of the y-axis in any generated charts.\n * The label will be displayed horizontally central of the y-axis bar.\n * \n * <p>\n * If the yAxisLabel is set to <tt>null</tt> then no label will be displayed.\n * \n * <p>\n * Defaults to null.\n * \n * @param yAxisLabel the label to be displayed describing the y-axis.\n */\n public void setYAxisLabel(String yAxisLabel) {\n this.yAxisLabel = yAxisLabel;\n }\n\n /**\n * Returns the width of the margin in pixels to be left as empty space around the heat map\n * element.\n * \n * @return the size of the margin to be left blank around the edge of the chart.\n */\n public int getChartMargin() {\n return margin;\n }\n\n /**\n * Sets the width of the margin in pixels to be left as empty space around the heat map element.\n * If a title is set then half the margin will be directly above the title and half directly below\n * it. Where axis labels are set then the axis labels may sit partially in the margin.\n * \n * <p>\n * Defaults to 20 pixels.\n * \n * @param margin the new margin to be left as blank space around the heat map.\n */\n public void setChartMargin(int margin) {\n this.margin = margin;\n }\n\n /**\n * Returns an object that represents the colour to be used as the background for the whole chart.\n * \n * @return the colour to be used to fill the chart background.\n */\n public Color getBackgroundColour() {\n return backgroundColour;\n }\n\n /**\n * Sets the colour to be used on the background of the chart. A transparent background can be set\n * by setting a background colour with an alpha value. The transparency will only be effective\n * when the image is saved as a png or gif.\n * \n * <p>\n * Defaults to <code>Color.WHITE</code>.\n * \n * @param backgroundColour the new colour to be set as the background fill.\n */\n public void setBackgroundColour(Color backgroundColour) {\n if (backgroundColour == null) {\n backgroundColour = Color.WHITE;\n }\n\n this.backgroundColour = backgroundColour;\n }\n\n /**\n * Returns the <code>Font</code> that describes the visual style of the title.\n * \n * @return the Font that will be used to render the title.\n */\n public Font getTitleFont() {\n return titleFont;\n }\n\n /**\n * Sets a new <code>Font</code> to be used in rendering the chart's title String.\n * \n * <p>\n * Defaults to Sans-Serif, BOLD, 16 pixels.\n * \n * @param titleFont the Font that should be used when rendering the chart title.\n */\n public void setTitleFont(Font titleFont) {\n this.titleFont = titleFont;\n }\n\n /**\n * Returns the <code>Color</code> that represents the colour the title text should be painted in.\n * \n * @return the currently set colour to be used in painting the chart title.\n */\n public Color getTitleColour() {\n return titleColour;\n }\n\n /**\n * Sets the <code>Color</code> that describes the colour to be used for the chart title String.\n * \n * <p>\n * Defaults to <code>Color.BLACK</code>.\n * \n * @param titleColour the colour to paint the chart's title String.\n */\n public void setTitleColour(Color titleColour) {\n this.titleColour = titleColour;\n }\n\n /**\n * Returns the width of the axis bars in pixels. Both axis bars have the same thickness.\n * \n * @return the thickness of the axis bars in pixels.\n */\n public int getAxisThickness() {\n return axisThickness;\n }\n\n /**\n * Sets the width of the axis bars in pixels. Both axis bars use the same thickness.\n * \n * <p>\n * Defaults to 2 pixels.\n * \n * @param axisThickness the thickness to use for the axis bars in any newly generated charts.\n */\n public void setAxisThickness(int axisThickness) {\n this.axisThickness = axisThickness;\n }\n\n /**\n * Returns the colour that is set to be used for the axis bars. Both axis bars use the same\n * colour.\n * \n * @return the colour in use for the axis bars.\n */\n public Color getAxisColour() {\n return axisColour;\n }\n\n /**\n * Sets the colour to be used on the axis bars. Both axis bars use the same colour.\n * \n * <p>\n * Defaults to <code>Color.BLACK</code>.\n * \n * @param axisColour the colour to be set for use on the axis bars.\n */\n public void setAxisColour(Color axisColour) {\n this.axisColour = axisColour;\n }\n\n /**\n * Returns the font that describes the visual style of the labels of the axis. Both axis' labels\n * use the same font.\n * \n * @return the font used to define the visual style of the axis labels.\n */\n public Font getAxisLabelsFont() {\n return axisLabelsFont;\n }\n\n /**\n * Sets the font that describes the visual style of the axis labels. Both axis' labels use the\n * same font.\n * \n * <p>\n * Defaults to Sans-Serif, PLAIN, 12 pixels.\n * \n * @param axisLabelsFont the font to be used to define the visual style of the axis labels.\n */\n public void setAxisLabelsFont(Font axisLabelsFont) {\n this.axisLabelsFont = axisLabelsFont;\n }\n\n /**\n * Returns the current colour of the axis labels. Both labels use the same colour.\n * \n * @return the colour of the axis label text.\n */\n public Color getAxisLabelColour() {\n return axisLabelColour;\n }\n\n /**\n * Sets the colour of the text displayed as axis labels. Both labels use the same colour.\n * \n * <p>\n * Defaults to Color.BLACK.\n * \n * @param axisLabelColour the colour to use for the axis label text.\n */\n public void setAxisLabelColour(Color axisLabelColour) {\n this.axisLabelColour = axisLabelColour;\n }\n\n /**\n * Returns the font which describes the visual style of the axis values. The axis values are those\n * values displayed alongside the axis bars at regular intervals. Both axis use the same font.\n * \n * @return the font in use for the axis values.\n */\n public Font getAxisValuesFont() {\n return axisValuesFont;\n }\n\n /**\n * Sets the font which describes the visual style of the axis values. The axis values are those\n * values displayed alongside the axis bars at regular intervals. Both axis use the same font.\n * \n * <p>\n * Defaults to Sans-Serif, PLAIN, 10 pixels.\n * \n * @param axisValuesFont the font that should be used for the axis values.\n */\n public void setAxisValuesFont(Font axisValuesFont) {\n this.axisValuesFont = axisValuesFont;\n }\n\n /**\n * Returns the colour of the axis values as they will be painted along the axis bars. Both axis\n * use the same colour.\n * \n * @return the colour of the values displayed along the axis bars.\n */\n public Color getAxisValuesColour() {\n return axisValuesColour;\n }\n\n /**\n * Sets the colour to be used for the axis values as they will be painted along the axis bars.\n * Both axis use the same colour.\n * \n * <p>\n * Defaults to Color.BLACK.\n * \n * @param axisValuesColour the new colour to be used for the axis bar values.\n */\n public void setAxisValuesColour(Color axisValuesColour) {\n this.axisValuesColour = axisValuesColour;\n }\n\n /**\n * Returns the frequency of the values displayed along the x-axis. The frequency is how many\n * columns in the x-dimension have their value displayed. A frequency of 2 would mean every other\n * column has a value shown and a frequency of 3 would mean every third column would be given a\n * value.\n * \n * @return the frequency of the values displayed against columns.\n */\n public int getXAxisValuesFrequency() {\n return xAxisValuesFrequency;\n }\n\n /**\n * Sets the frequency of the values displayed along the x-axis. The frequency is how many columns\n * in the x-dimension have their value displayed. A frequency of 2 would mean every other column\n * has a value and a frequency of 3 would mean every third column would be given a value.\n * \n * <p>\n * Defaults to 1. Every column is given a value.\n * \n * @param axisValuesFrequency the frequency of the values displayed against columns, where 1 is\n * every column and 2 is every other column.\n */\n public void setXAxisValuesFrequency(int axisValuesFrequency) {\n this.xAxisValuesFrequency = axisValuesFrequency;\n }\n\n /**\n * Returns the frequency of the values displayed along the y-axis. The frequency is how many rows\n * in the y-dimension have their value displayed. A frequency of 2 would mean every other row has\n * a value and a frequency of 3 would mean every third row would be given a value.\n * \n * @return the frequency of the values displayed against rows.\n */\n public int getYAxisValuesFrequency() {\n return yAxisValuesFrequency;\n }\n\n /**\n * Sets the frequency of the values displayed along the y-axis. The frequency is how many rows in\n * the y-dimension have their value displayed. A frequency of 2 would mean every other row has a\n * value and a frequency of 3 would mean every third row would be given a value.\n * \n * <p>\n * Defaults to 1. Every row is given a value.\n * \n * @param axisValuesFrequency the frequency of the values displayed against rows, where 1 is every\n * row and 2 is every other row.\n */\n public void setYAxisValuesFrequency(int axisValuesFrequency) {\n yAxisValuesFrequency = axisValuesFrequency;\n }\n\n /**\n * Returns whether axis values are to be shown at all for the x-axis.\n * \n * <p>\n * If axis values are not shown then more space is allocated to the heat map.\n * \n * @return true if the x-axis values will be displayed, false otherwise.\n */\n public boolean isShowXAxisValues() {\n // TODO Could get rid of these flags and use a frequency of -1 to signal no values.\n return showXAxisValues;\n }\n\n /**\n * Sets whether axis values are to be shown at all for the x-axis.\n * \n * <p>\n * If axis values are not shown then more space is allocated to the heat map.\n * \n * <p>\n * Defaults to true.\n * \n * @param showXAxisValues true if x-axis values should be displayed, false if they should be\n * hidden.\n */\n public void setShowXAxisValues(boolean showXAxisValues) {\n this.showXAxisValues = showXAxisValues;\n }\n\n /**\n * Returns whether axis values are to be shown at all for the y-axis.\n * \n * <p>\n * If axis values are not shown then more space is allocated to the heat map.\n * \n * @return true if the y-axis values will be displayed, false otherwise.\n */\n public boolean isShowYAxisValues() {\n return showYAxisValues;\n }\n\n /**\n * Sets whether axis values are to be shown at all for the y-axis.\n * \n * <p>\n * If axis values are not shown then more space is allocated to the heat map.\n * \n * <p>\n * Defaults to true.\n * \n * @param showYAxisValues true if y-axis values should be displayed, false if they should be\n * hidden.\n */\n public void setShowYAxisValues(boolean showYAxisValues) {\n this.showYAxisValues = showYAxisValues;\n }\n\n /**\n * Returns the colour that is currently to be displayed for the heat map cells with the highest\n * z-value in the dataset.\n * \n * <p>\n * The full colour range will go through each RGB step between the high value colour and the low\n * value colour.\n * \n * @return the colour in use for cells of the highest z-value.\n */\n public Color getHighValueColour() {\n return highValueColour;\n }\n\n /**\n * Sets the colour to be used to fill cells of the heat map with the highest z-values in the\n * dataset.\n * \n * <p>\n * The full colour range will go through each RGB step between the high value colour and the low\n * value colour.\n * \n * <p>\n * Defaults to Color.BLACK.\n * \n * @param highValueColour the colour to use for cells of the highest z-value.\n */\n public void setHighValueColour(Color highValueColour) {\n this.highValueColour = highValueColour;\n\n // updateColourDistance();\n }\n\n /**\n * Returns the colour that is currently to be displayed for the heat map cells with the lowest\n * z-value in the dataset.\n * \n * <p>\n * The full colour range will go through each RGB step between the high value colour and the low\n * value colour.\n * \n * @return the colour in use for cells of the lowest z-value.\n */\n public Color getLowValueColour() {\n return lowValueColour;\n }\n\n /**\n * Sets the colour to be used to fill cells of the heat map with the lowest z-values in the\n * dataset.\n * \n * <p>\n * The full colour range will go through each RGB step between the high value colour and the low\n * value colour.\n * \n * <p>\n * Defaults to Color.WHITE.\n * \n * @param lowValueColour the colour to use for cells of the lowest z-value.\n */\n public void setLowValueColour(Color lowValueColour) {\n this.lowValueColour = lowValueColour;\n\n // updateColourDistance();\n }\n\n /**\n * Returns the scale that is currently in use to map z-value to colour. A value of 1.0 will give a\n * <strong>linear</strong> scale, which will spread the distribution of colours evenly amoungst\n * the full range of represented z-values. A value of greater than 1.0 will give an\n * <strong>exponential</strong> scale that will produce greater emphasis for the separation\n * between higher values and a value between 0.0 and 1.0 will provide a\n * <strong>logarithmic</strong> scale, with greater separation of low values.\n * \n * @return the scale factor that is being used to map from z-value to colour.\n */\n public double getColourScale() {\n return colourScale;\n }\n\n /**\n * Sets the scale that is currently in use to map z-value to colour. A value of 1.0 will give a\n * <strong>linear</strong> scale, which will spread the distribution of colours evenly amoungst\n * the full range of represented z-values. A value of greater than 1.0 will give an\n * <strong>exponential</strong> scale that will produce greater emphasis for the separation\n * between higher values and a value between 0.0 and 1.0 will provide a\n * <strong>logarithmic</strong> scale, with greater separation of low values. Values of 0.0 or\n * less are illegal.\n * \n * <p>\n * Defaults to a linear scale value of 1.0.\n * \n * @param colourScale the scale that should be used to map from z-value to colour.\n */\n public void setColourScale(double colourScale) {\n this.colourScale = colourScale;\n }\n\n /*\n * Calculate and update the field for the distance between the low colour and high colour. The\n * distance is the number of steps between one colour and the other using an RGB coding with 0-255\n * values for each of red, green and blue. So the maximum colour distance is 255 + 255 + 255.\n */\n // private void updateColourDistance() {\n // int r1 = lowValueColour.getRed();\n // int g1 = lowValueColour.getGreen();\n // int b1 = lowValueColour.getBlue();\n // int r2 = highValueColour.getRed();\n // int g2 = highValueColour.getGreen();\n // int b2 = highValueColour.getBlue();\n //\n // colourValueDistance = Math.abs(r1 - r2);\n // colourValueDistance += Math.abs(g1 - g2);\n // colourValueDistance += Math.abs(b1 - b2);\n // }\n\n /**\n * Generates a new chart <code>Image</code> based upon the currently held settings and then\n * attempts to save that image to disk, to the location provided as a File parameter. The image\n * type of the saved file will equal the extension of the filename provided, so it is essential\n * that a suitable extension be included on the file name.\n * \n * <p>\n * All supported <code>ImageIO</code> file types are supported, including PNG, JPG and GIF.\n * \n * <p>\n * No chart will be generated until this or the related <code>getChartImage()</code> method are\n * called. All successive calls will result in the generation of a new chart image, no caching is\n * used.\n * \n * @param outputFile the file location that the generated image file should be written to. The\n * File must have a suitable filename, with an extension of a valid image format (as supported by\n * <code>ImageIO</code>).\n * @throws IOException if the output file's filename has no extension or if there the file is\n * unable to written to. Reasons for this include a non-existant file location (check with the\n * File exists() method on the parent directory), or the permissions of the write location may be\n * incorrect.\n */\n public void saveToFile(File outputFile) throws IOException {\n String filename = outputFile.getName();\n\n int extPoint = filename.lastIndexOf('.');\n\n if (extPoint < 0) {\n throw new IOException(\"Illegal filename, no extension used.\");\n }\n\n // Determine the extension of the filename.\n String ext = filename.substring(extPoint + 1);\n\n // Handle jpg without transparency.\n if (ext.toLowerCase().equals(\"jpg\") || ext.toLowerCase().equals(\"jpeg\")) {\n BufferedImage chart = (BufferedImage) getChartImage(false);\n\n // Save our graphic.\n saveGraphicJpeg(chart, outputFile, 1.0f);\n }\n else {\n BufferedImage chart = (BufferedImage) getChartImage(true);\n\n ImageIO.write(chart, ext, outputFile);\n }\n }\n\n private void saveGraphicJpeg(BufferedImage chart, File outputFile, float quality)\n throws IOException {\n // Setup correct compression for jpeg.\n Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(\"jpeg\");\n ImageWriter writer = (ImageWriter) iter.next();\n ImageWriteParam iwp = writer.getDefaultWriteParam();\n iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n iwp.setCompressionQuality(quality);\n\n // Output the image.\n FileImageOutputStream output = new FileImageOutputStream(outputFile);\n writer.setOutput(output);\n IIOImage image = new IIOImage(chart, null, null);\n writer.write(null, image, iwp);\n writer.dispose();\n\n }\n\n /**\n * Generates and returns a new chart <code>Image</code> configured according to this object's\n * currently held settings. The given parameter determines whether transparency should be enabled\n * for the generated image.\n * \n * <p>\n * No chart will be generated until this or the related <code>saveToFile(File)</code> method are\n * called. All successive calls will result in the generation of a new chart image, no caching is\n * used.\n * \n * @param alpha whether to enable transparency.\n * @return A newly generated chart <code>Image</code>. The returned image is a\n * <code>BufferedImage</code>.\n */\n public Image getChartImage(boolean alpha) {\n // Calculate all unknown dimensions.\n measureComponents();\n updateCoordinates();\n\n // Determine image type based upon whether require alpha or not.\n // Using BufferedImage.TYPE_INT_ARGB seems to break on jpg.\n int imageType = (alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);\n\n // Create our chart image which we will eventually draw everything on.\n BufferedImage chartImage = new BufferedImage(chartSize.width, chartSize.height, imageType);\n Graphics2D chartGraphics = chartImage.createGraphics();\n\n // Use anti-aliasing where ever possible.\n chartGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n // Set the background.\n chartGraphics.setColor(backgroundColour);\n chartGraphics.fillRect(0, 0, chartSize.width, chartSize.height);\n\n // Draw the title.\n drawTitle(chartGraphics);\n\n // Draw the heatmap image.\n drawHeatMap(chartGraphics, zValues);\n\n // Draw the axis labels.\n drawXLabel(chartGraphics);\n drawYLabel(chartGraphics);\n\n // Draw the axis bars.\n drawAxisBars(chartGraphics);\n\n // Draw axis values.\n drawXValues(chartGraphics);\n drawYValues(chartGraphics);\n\n return chartImage;\n }\n\n /**\n * Generates and returns a new chart <code>Image</code> configured according to this object's\n * currently held settings. By default the image is generated with no transparency.\n * \n * <p>\n * No chart will be generated until this or the related <code>saveToFile(File)</code> method are\n * called. All successive calls will result in the generation of a new chart image, no caching is\n * used.\n * \n * @return A newly generated chart <code>Image</code>. The returned image is a\n * <code>BufferedImage</code>.\n */\n public Image getChartImage() {\n return getChartImage(false);\n }\n\n /*\n * Calculates all unknown component dimensions.\n */\n private void measureComponents() {\n // TODO This would be a good place to check that all settings have sensible values or throw\n // illegal state exception.\n\n // TODO Put this somewhere so it only gets created once.\n BufferedImage chartImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);\n Graphics2D tempGraphics = chartImage.createGraphics();\n\n // Calculate title dimensions.\n if (title != null) {\n tempGraphics.setFont(titleFont);\n FontMetrics metrics = tempGraphics.getFontMetrics();\n titleSize = new Dimension(metrics.stringWidth(title), metrics.getHeight());\n titleAscent = metrics.getAscent();\n }\n else {\n titleSize = new Dimension(0, 0);\n }\n\n // Calculate x-axis label dimensions.\n if (xAxisLabel != null) {\n tempGraphics.setFont(axisLabelsFont);\n FontMetrics metrics = tempGraphics.getFontMetrics();\n xAxisLabelSize = new Dimension(metrics.stringWidth(xAxisLabel), metrics.getHeight());\n xAxisLabelDescent = metrics.getDescent();\n }\n else {\n xAxisLabelSize = new Dimension(0, 0);\n }\n\n // Calculate y-axis label dimensions.\n if (yAxisLabel != null) {\n tempGraphics.setFont(axisLabelsFont);\n FontMetrics metrics = tempGraphics.getFontMetrics();\n yAxisLabelSize = new Dimension(metrics.stringWidth(yAxisLabel), metrics.getHeight());\n yAxisLabelAscent = metrics.getAscent();\n }\n else {\n yAxisLabelSize = new Dimension(0, 0);\n }\n\n // Calculate x-axis value dimensions.\n if (showXAxisValues) {\n tempGraphics.setFont(axisValuesFont);\n FontMetrics metrics = tempGraphics.getFontMetrics();\n xAxisValuesHeight = metrics.getHeight();\n xAxisValuesWidthMax = 0;\n for (Object o : xValues) {\n int w = metrics.stringWidth(o.toString());\n if (w > xAxisValuesWidthMax) {\n xAxisValuesWidthMax = w;\n }\n }\n }\n else {\n xAxisValuesHeight = 0;\n }\n\n // Calculate y-axis value dimensions.\n if (showYAxisValues) {\n tempGraphics.setFont(axisValuesFont);\n FontMetrics metrics = tempGraphics.getFontMetrics();\n yAxisValuesHeight = metrics.getHeight();\n yAxisValuesAscent = metrics.getAscent();\n yAxisValuesWidthMax = 0;\n for (Object o : yValues) {\n int w = metrics.stringWidth(o.toString());\n if (w > yAxisValuesWidthMax) {\n yAxisValuesWidthMax = w;\n }\n }\n }\n else {\n yAxisValuesHeight = 0;\n }\n\n // Calculate heatmap dimensions.\n int heatMapWidth = (zValues[0].length * cellSize.width);\n int heatMapHeight = (zValues.length * cellSize.height);\n heatMapSize = new Dimension(heatMapWidth, heatMapHeight);\n\n int yValuesHorizontalSize = 0;\n if (yValuesHorizontal) {\n yValuesHorizontalSize = yAxisValuesWidthMax;\n }\n else {\n yValuesHorizontalSize = yAxisValuesHeight;\n }\n\n int xValuesVerticalSize = 0;\n if (xValuesHorizontal) {\n xValuesVerticalSize = xAxisValuesHeight;\n }\n else {\n xValuesVerticalSize = xAxisValuesWidthMax;\n }\n\n // Calculate chart dimensions.\n int chartWidth = heatMapWidth + (2 * margin) + yAxisLabelSize.height + yValuesHorizontalSize\n + axisThickness;\n int chartHeight = heatMapHeight + (2 * margin) + xAxisLabelSize.height + xValuesVerticalSize\n + titleSize.height + axisThickness;\n chartSize = new Dimension(chartWidth, chartHeight);\n }\n\n /*\n * Calculates the co-ordinates of some key positions.\n */\n private void updateCoordinates() {\n // Top-left of heat map.\n int x = margin + axisThickness + yAxisLabelSize.height;\n x += (yValuesHorizontal ? yAxisValuesWidthMax : yAxisValuesHeight);\n int y = titleSize.height + margin;\n heatMapTL = new Point(x, y);\n\n // Top-right of heat map.\n x = heatMapTL.x + heatMapSize.width;\n y = heatMapTL.y + heatMapSize.height;\n heatMapBR = new Point(x, y);\n\n // Centre of heat map.\n x = heatMapTL.x + (heatMapSize.width / 2);\n y = heatMapTL.y + (heatMapSize.height / 2);\n heatMapC = new Point(x, y);\n }\n\n /*\n * Draws the title String on the chart if title is not null.\n */\n private void drawTitle(Graphics2D chartGraphics) {\n if (title != null) {\n // Strings are drawn from the baseline position of the leftmost char.\n int yTitle = (margin / 2) + titleAscent;\n int xTitle = (chartSize.width / 2) - (titleSize.width / 2);\n\n chartGraphics.setFont(titleFont);\n chartGraphics.setColor(titleColour);\n chartGraphics.drawString(title, xTitle, yTitle);\n }\n }\n\n /*\n * Creates the actual heatmap element as an image, that can then be drawn onto a chart.\n */\n private void drawHeatMap(Graphics2D chartGraphics, double[][] data) {\n // Calculate the available size for the heatmap.\n int noYCells = data.length;\n int noXCells = data[0].length;\n\n // double dataMin = min(data);\n // double dataMax = max(data);\n\n BufferedImage heatMapImage = new BufferedImage(heatMapSize.width, heatMapSize.height,\n BufferedImage.TYPE_INT_ARGB);\n Graphics2D heatMapGraphics = heatMapImage.createGraphics();\n\n for (int x = 0; x < noXCells; x++) {\n for (int y = 0; y < noYCells; y++) {\n // Set colour depending on zValues.\n heatMapGraphics.setColor(getCellColour(data[y][x], lowValue, highValue));\n\n int cellX = x * cellSize.width;\n int cellY = y * cellSize.height;\n\n heatMapGraphics.fillRect(cellX, cellY, cellSize.width, cellSize.height);\n }\n }\n\n // Draw the heat map onto the chart.\n chartGraphics.drawImage(heatMapImage, heatMapTL.x, heatMapTL.y, heatMapSize.width,\n heatMapSize.height, null);\n }\n\n /*\n * Draws the x-axis label string if it is not null.\n */\n private void drawXLabel(Graphics2D chartGraphics) {\n if (xAxisLabel != null) {\n // Strings are drawn from the baseline position of the leftmost char.\n int yPosXAxisLabel = chartSize.height - (margin / 2) - xAxisLabelDescent;\n // TODO This will need to be updated if the y-axis values/label can be moved to the right.\n int xPosXAxisLabel = heatMapC.x - (xAxisLabelSize.width / 2);\n\n chartGraphics.setFont(axisLabelsFont);\n chartGraphics.setColor(axisLabelColour);\n chartGraphics.drawString(xAxisLabel, xPosXAxisLabel, yPosXAxisLabel);\n }\n }\n\n /*\n * Draws the y-axis label string if it is not null.\n */\n private void drawYLabel(Graphics2D chartGraphics) {\n if (yAxisLabel != null) {\n // Strings are drawn from the baseline position of the leftmost char.\n int yPosYAxisLabel = heatMapC.y + (yAxisLabelSize.width / 2);\n int xPosYAxisLabel = (margin / 2) + yAxisLabelAscent;\n\n chartGraphics.setFont(axisLabelsFont);\n chartGraphics.setColor(axisLabelColour);\n\n // Create 270 degree rotated transform.\n AffineTransform transform = chartGraphics.getTransform();\n AffineTransform originalTransform = (AffineTransform) transform.clone();\n transform.rotate(Math.toRadians(270), xPosYAxisLabel, yPosYAxisLabel);\n chartGraphics.setTransform(transform);\n\n // Draw string.\n chartGraphics.drawString(yAxisLabel, xPosYAxisLabel, yPosYAxisLabel);\n\n // Revert to original transform before rotation.\n chartGraphics.setTransform(originalTransform);\n }\n }\n\n /*\n * Draws the bars of the x-axis and y-axis.\n */\n private void drawAxisBars(Graphics2D chartGraphics) {\n if (axisThickness > 0) {\n chartGraphics.setColor(axisColour);\n\n // Draw x-axis.\n int x = heatMapTL.x - axisThickness;\n int y = heatMapBR.y;\n int width = heatMapSize.width + axisThickness;\n int height = axisThickness;\n chartGraphics.fillRect(x, y, width, height);\n\n // Draw y-axis.\n x = heatMapTL.x - axisThickness;\n y = heatMapTL.y;\n width = axisThickness;\n height = heatMapSize.height;\n chartGraphics.fillRect(x, y, width, height);\n }\n }\n\n /*\n * Draws the x-values onto the x-axis if showXAxisValues is set to true.\n */\n private void drawXValues(Graphics2D chartGraphics) {\n if (!showXAxisValues) {\n return;\n }\n\n chartGraphics.setColor(axisValuesColour);\n\n for (int i = 0; i < xValues.length; i++) {\n if (i % xAxisValuesFrequency != 0) {\n continue;\n }\n\n String xValueStr = xValues[i].toString();\n\n chartGraphics.setFont(axisValuesFont);\n FontMetrics metrics = chartGraphics.getFontMetrics();\n\n int valueWidth = metrics.stringWidth(xValueStr);\n\n if (xValuesHorizontal) {\n // Draw the value with whatever font is now set.\n int valueXPos = (i * cellSize.width) + ((cellSize.width / 2) - (valueWidth / 2));\n valueXPos += heatMapTL.x;\n int valueYPos = heatMapBR.y + metrics.getAscent() + 1;\n\n chartGraphics.drawString(xValueStr, valueXPos, valueYPos);\n }\n else {\n int valueXPos = heatMapTL.x + (i * cellSize.width)\n + ((cellSize.width / 2) + (xAxisValuesHeight / 2));\n int valueYPos = heatMapBR.y + axisThickness + valueWidth;\n\n // Create 270 degree rotated transform.\n AffineTransform transform = chartGraphics.getTransform();\n AffineTransform originalTransform = (AffineTransform) transform.clone();\n transform.rotate(Math.toRadians(270), valueXPos, valueYPos);\n chartGraphics.setTransform(transform);\n\n // Draw the string.\n chartGraphics.drawString(xValueStr, valueXPos, valueYPos);\n\n // Revert to original transform before rotation.\n chartGraphics.setTransform(originalTransform);\n }\n }\n }\n\n /*\n * Draws the y-values onto the y-axis if showYAxisValues is set to true.\n */\n private void drawYValues(Graphics2D chartGraphics) {\n if (!showYAxisValues) {\n return;\n }\n\n chartGraphics.setColor(axisValuesColour);\n\n for (int i = 0; i < yValues.length; i++) {\n if (i % yAxisValuesFrequency != 0) {\n continue;\n }\n\n String yValueStr = yValues[i].toString();\n\n chartGraphics.setFont(axisValuesFont);\n FontMetrics metrics = chartGraphics.getFontMetrics();\n\n int valueWidth = metrics.stringWidth(yValueStr);\n\n if (yValuesHorizontal) {\n // Draw the value with whatever font is now set.\n int valueXPos = margin + yAxisLabelSize.height + (yAxisValuesWidthMax - valueWidth);\n int valueYPos = heatMapTL.y + (i * cellSize.height) + (cellSize.height / 2)\n + (yAxisValuesAscent / 2);\n\n chartGraphics.drawString(yValueStr, valueXPos, valueYPos);\n }\n else {\n int valueXPos = margin + yAxisLabelSize.height + yAxisValuesAscent;\n int valueYPos = heatMapTL.y + (i * cellSize.height) + (cellSize.height / 2)\n + (valueWidth / 2);\n\n // Create 270 degree rotated transform.\n AffineTransform transform = chartGraphics.getTransform();\n AffineTransform originalTransform = (AffineTransform) transform.clone();\n transform.rotate(Math.toRadians(270), valueXPos, valueYPos);\n chartGraphics.setTransform(transform);\n\n // Draw the string.\n chartGraphics.drawString(yValueStr, valueXPos, valueYPos);\n\n // Revert to original transform before rotation.\n chartGraphics.setTransform(originalTransform);\n }\n }\n }\n\n /*\n * Determines what colour a heat map cell should be based upon the cell values.\n */\n private Color getCellColour(double data, double min, double max) {\n double range = max - min;\n double position = data - min;\n\n // What proportion of the way through the possible values is that.\n double percentPosition = position / range;\n\n // Which colour group does that put us in.\n // int colourPosition = getColourPosition(percentPosition);\n\n int r = (int) (255 * red(percentPosition * 2 - 1));\n int g = (int) (255 * green(percentPosition * 2 - 1));\n int b = (int) (255 * blue(percentPosition * 2 - 1));\n\n // int r = lowValueColour.getRed();\n // int g = lowValueColour.getGreen();\n // int b = lowValueColour.getBlue();\n //\n // // Make n shifts of the colour, where n is the colourPosition.\n // for (int i = 0; i < colourPosition; i++) {\n // int rDistance = r - highValueColour.getRed();\n // int gDistance = g - highValueColour.getGreen();\n // int bDistance = b - highValueColour.getBlue();\n //\n // if ((Math.abs(rDistance) >= Math.abs(gDistance))\n // && (Math.abs(rDistance) >= Math.abs(bDistance))) {\n // // Red must be the largest.\n // r = changeColourValue(r, rDistance);\n // }\n // else if (Math.abs(gDistance) >= Math.abs(bDistance)) {\n // // Green must be the largest.\n // g = changeColourValue(g, gDistance);\n // }\n // else {\n // // Blue must be the largest.\n // b = changeColourValue(b, bDistance);\n // }\n // }\n\n return new Color(r, g, b);\n }\n\n /*\n * Returns how many colour shifts are required from the lowValueColour to get to the correct\n * colour position. The result will be different depending on the colour scale used: LINEAR,\n * LOGARITHMIC, EXPONENTIAL.\n */\n // private int getColourPosition(double percentPosition) {\n // return (int) Math.round(colourValueDistance * Math.pow(percentPosition, colourScale));\n // }\n\n // private int changeColourValue(int colourValue, int colourDistance) {\n // if (colourDistance < 0) {\n // return colourValue + 1;\n // }\n // else if (colourDistance > 0) {\n // return colourValue - 1;\n // }\n // else {\n // // This shouldn't actually happen here.\n // return colourValue;\n // }\n // }\n\n /**\n * Finds and returns the maximum value in a 2-dimensional array of doubles.\n * \n * @param values the data to use.\n * \n * @return the largest value in the array.\n */\n public static double max(double[][] values) {\n double max = 0;\n for (int i = 0; i < values.length; i++) {\n for (int j = 0; j < values[i].length; j++) {\n max = (values[i][j] > max) ? values[i][j] : max;\n }\n }\n return max;\n }\n\n /**\n * Finds and returns the minimum value in a 2-dimensional array of doubles.\n * \n * @param values the data to use.\n * \n * @return the smallest value in the array.\n */\n public static double min(double[][] values) {\n double min = Double.MAX_VALUE;\n for (int i = 0; i < values.length; i++) {\n for (int j = 0; j < values[i].length; j++) {\n min = (values[i][j] < min) ? values[i][j] : min;\n }\n }\n return min;\n }\n\n // the part below is taken from\n // http://stackoverflow.com/questions/7706339/grayscale-to-red-green-blue-matlab-jet-color-scale\n //\n //\n\n double interpolate(double val, double y0, double x0, double y1, double x1) {\n return (val - x0) * (y1 - y0) / (x1 - x0) + y0;\n }\n\n double base(double val) {\n if (val <= -0.75)\n return 0;\n else if (val <= -0.25)\n return interpolate(val, 0.0, -0.75, 1.0, -0.25);\n else if (val <= 0.25)\n return 1.0;\n else if (val <= 0.75)\n return interpolate(val, 1.0, 0.25, 0.0, 0.75);\n else\n return 0.0;\n }\n\n double red(double gray) {\n return base(gray - 0.5);\n }\n\n double green(double gray) {\n return base(gray);\n }\n\n double blue(double gray) {\n return base(gray + 0.5);\n }\n}" ]
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.TreeSet; import javax.imageio.ImageIO; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.seninp.jmotif.distance.EuclideanDistance; import net.seninp.jmotif.sax.NumerosityReductionStrategy; import net.seninp.jmotif.sax.SAXProcessor; import net.seninp.jmotif.sax.TSProcessor; import net.seninp.util.HeatChart;
package net.seninp.jmotif.sax.tinker; public class MoviePrinter { private static final DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US); private static DecimalFormat df = new DecimalFormat("0.00000", otherSymbols); private static EuclideanDistance ed = new EuclideanDistance(); private static final String DAT_FNAME = "src/resources/dataset/depth/0890031.dat"; private static final int SAX_WINDOW_SIZE = 10; private static int cPoint = SAX_WINDOW_SIZE; private static final int SAX_PAA_SIZE = 10; private static final int SAX_ALPHABET_SIZE = 4; private static final double SAX_NORM_THRESHOLD = 0.001; private static final NumerosityReductionStrategy SAX_NR_STRATEGY = NumerosityReductionStrategy.NONE; private static final int SHINGLE_SIZE = 3; // logging stuff // private static Logger LOGGER = LoggerFactory.getLogger(MoviePrinter.class); // ffmpeg -framerate 5 -i frame%04d.png -s:v 1280x720 -vcodec libx264 -profile:v high -crf 20 // -pix_fmt yuv420p daimler_man.mp4 public static void main(String[] args) throws Exception { SAXProcessor sp = new SAXProcessor(); // data // double[] dat = TSProcessor.readFileColumn(DAT_FNAME, 1, 0); // TSProcessor tp = new TSProcessor(); // double[] dat = tp.readTS("src/resources/dataset/asys40.txt", 0); // double[] dat = TSProcessor.readFileColumn(filename, columnIdx, // sizeLimit)FileColumn(DAT_FNAME, 1, 0); LOGGER.info("read {} points from {}", dat.length, DAT_FNAME); String str = "win_width: " + cPoint + "; SAX: W " + SAX_WINDOW_SIZE + ", P " + SAX_PAA_SIZE + ", A " + SAX_ALPHABET_SIZE + ", STR " + SAX_NR_STRATEGY.toString(); int frameCounter = 0; int startOffset = cPoint; while (cPoint < dat.length - startOffset - 1) { if (0 == cPoint % 2) { BufferedImage tsChart = getChart(dat, cPoint); // bitmap 1 // double[] win1 = Arrays.copyOfRange(dat, cPoint - startOffset, cPoint); Map<String, Integer> shingledData1 = sp.ts2Shingles(win1, SAX_WINDOW_SIZE, SAX_PAA_SIZE, SAX_ALPHABET_SIZE, SAX_NR_STRATEGY, SAX_NORM_THRESHOLD, SHINGLE_SIZE); BufferedImage pam1 = getHeatMap(shingledData1, "pre-window"); double[] win2 = Arrays.copyOfRange(dat, cPoint, cPoint + startOffset); Map<String, Integer> shingledData2 = sp.ts2Shingles(win2, SAX_WINDOW_SIZE, SAX_PAA_SIZE, SAX_ALPHABET_SIZE, SAX_NR_STRATEGY, SAX_NORM_THRESHOLD, SHINGLE_SIZE); BufferedImage pam2 = getHeatMap(shingledData2, "post-window"); // the assemble // BufferedImage target = new BufferedImage(800, 530, BufferedImage.TYPE_INT_ARGB); Graphics targetGraphics = target.getGraphics(); targetGraphics.setColor(Color.WHITE); targetGraphics.fillRect(0, 0, 799, 529); targetGraphics.drawImage(tsChart, 0, 0, null); targetGraphics.drawImage(pam1, 10, 410, null);// draws the first image onto it targetGraphics.drawImage(pam2, 120, 410, null);// draws the first image onto it targetGraphics.setColor(Color.RED); targetGraphics.setFont(new Font("monospaced", Font.PLAIN, 16)); targetGraphics.drawString(str, 300, 420); targetGraphics.setColor(Color.BLUE); targetGraphics.setFont(new Font("monospaced", Font.PLAIN, 24)); double dist = ed.distance(toVector(shingledData1), toVector(shingledData2)); targetGraphics.drawString("ED=" + df.format(dist), 300, 480); // String fileName = new SimpleDateFormat("yyyyMMddhhmmssSS'.png'").format(new Date()); File outputfile = new File("dframe" + String.format("%04d", frameCounter) + ".png"); ImageIO.write(target, "png", outputfile); frameCounter++; } cPoint++; } } private static double[] toVector(Map<String, Integer> shingledData1) { TreeSet<String> keys = new TreeSet<String>(shingledData1.keySet()); double[] res = new double[shingledData1.size()]; int counter = 0; for (String shingle : keys) { Integer value = shingledData1.get(shingle); res[counter] = value; counter++; } return res; } private static BufferedImage getHeatMap(Map<String, Integer> shingledData1, String title) { TreeSet<String> keys = new TreeSet<String>(shingledData1.keySet()); double[][] heatmapData = new double[8][8]; int counter = 0; for (String shingle : keys) { Integer value = shingledData1.get(shingle); heatmapData[counter / 8][counter % 8] = value; counter++; }
HeatChart chart = new HeatChart(heatmapData);
4
fluxroot/pulse
src/main/java/com/fluxchess/pulse/Search.java
[ "final class MoveList<T extends MoveList.MoveEntry> {\n\n\tprivate static final int MAX_MOVES = 256;\n\n\tfinal T[] entries;\n\tint size = 0;\n\n\tstatic final class MoveVariation {\n\n\t\tfinal int[] moves = new int[MAX_PLY];\n\t\tint size = 0;\n\t}\n\n\tstatic class MoveEntry {\n\n\t\tint move = NOMOVE;\n\t\tint value = NOVALUE;\n\t}\n\n\tstatic final class RootEntry extends MoveEntry {\n\n\t\tfinal MoveVariation pv = new MoveVariation();\n\t}\n\n\tMoveList(Class<T> clazz) {\n\t\t@SuppressWarnings(\"unchecked\") final T[] entries = (T[]) Array.newInstance(clazz, MAX_MOVES);\n\t\tthis.entries = entries;\n\t\ttry {\n\t\t\tfor (int i = 0; i < entries.length; i++) {\n\t\t\t\tentries[i] = clazz.getDeclaredConstructor().newInstance();\n\t\t\t}\n\t\t} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Sorts the move list using a stable insertion sort.\n\t */\n\tvoid sort() {\n\t\tfor (int i = 1; i < size; i++) {\n\t\t\tT entry = entries[i];\n\n\t\t\tint j = i;\n\t\t\twhile ((j > 0) && (entries[j - 1].value < entry.value)) {\n\t\t\t\tentries[j] = entries[j - 1];\n\t\t\t\tj--;\n\t\t\t}\n\n\t\t\tentries[j] = entry;\n\t\t}\n\t}\n\n\t/**\n\t * Rates the moves in the list according to \"Most Valuable Victim - Least Valuable Aggressor\".\n\t */\n\tvoid rateFromMVVLVA() {\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tint move = entries[i].move;\n\t\t\tint value = 0;\n\n\t\t\tint piecetypeValue = PieceType.getValue(Piece.getType(Move.getOriginPiece(move)));\n\t\t\tvalue += KING_VALUE / piecetypeValue;\n\n\t\t\tint target = Move.getTargetPiece(move);\n\t\t\tif (Piece.isValid(target)) {\n\t\t\t\tvalue += 10 * PieceType.getValue(Piece.getType(target));\n\t\t\t}\n\n\t\t\tentries[i].value = value;\n\t\t}\n\t}\n}", "public static final int WHITE = 0;", "public static int opposite(int color) {\n\tswitch (color) {\n\t\tcase WHITE:\n\t\t\treturn BLACK;\n\t\tcase BLACK:\n\t\t\treturn WHITE;\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException();\n\t}\n}", "public static final int MAX_DEPTH = 64;", "public static final int MAX_PLY = 256;", "public static final int NOMOVE = (NOMOVETYPE << TYPE_SHIFT)\n\t\t| (NOSQUARE << ORIGIN_SQUARE_SHIFT)\n\t\t| (NOSQUARE << TARGET_SQUARE_SHIFT)\n\t\t| (NOPIECE << ORIGIN_PIECE_SHIFT)\n\t\t| (NOPIECE << TARGET_PIECE_SHIFT)\n\t\t| (NOPIECETYPE << PROMOTION_SHIFT);", "public final class Value {\n\n\tpublic static final int INFINITE = 200000;\n\tpublic static final int CHECKMATE = 100000;\n\tpublic static final int CHECKMATE_THRESHOLD = CHECKMATE - MAX_PLY;\n\tpublic static final int DRAW = 0;\n\n\tpublic static final int NOVALUE = 300000;\n\n\tprivate Value() {\n\t}\n\n\tpublic static boolean isCheckmate(int value) {\n\t\tint absvalue = abs(value);\n\t\treturn absvalue >= CHECKMATE_THRESHOLD && absvalue <= CHECKMATE;\n\t}\n}" ]
import java.util.Optional; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import static com.fluxchess.pulse.MoveList.*; import static com.fluxchess.pulse.model.Color.WHITE; import static com.fluxchess.pulse.model.Color.opposite; import static com.fluxchess.pulse.model.Depth.MAX_DEPTH; import static com.fluxchess.pulse.model.Depth.MAX_PLY; import static com.fluxchess.pulse.model.Move.NOMOVE; import static com.fluxchess.pulse.model.Value.*; import static java.lang.Math.abs; import static java.lang.Runtime.getRuntime; import static java.lang.Thread.currentThread; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.SECONDS;
/* * Copyright 2013-2021 Phokham Nonava * * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package com.fluxchess.pulse; final class Search { private final ExecutorService threadPool = newFixedThreadPool(getRuntime().availableProcessors()); private Optional<Future<?>> future = Optional.empty(); private volatile boolean abort; private final Protocol protocol; private Position position; private final Evaluation evaluation = new Evaluation(); // We will store a MoveGenerator for each ply so we don't have to create them // in search. (which is expensive) private final MoveGenerator[] moveGenerators = new MoveGenerator[MAX_PLY]; // Depth search private int searchDepth; // Nodes search private long searchNodes; // Time & Clock & Ponder search private long searchTime; private Timer timer; private boolean timerStopped; private boolean doTimeManagement; // Search parameters
private final MoveList<RootEntry> rootMoves = new MoveList<>(RootEntry.class);
0
apache/incubator-taverna-mobile
app/src/main/java/org/apache/taverna/mobile/ui/favouriteworkflowdetail/FavouriteWorkflowDetailFragment.java
[ "@Singleton\npublic class DataManager {\n\n private BaseApiManager mBaseApiManager;\n\n private DBHelper mDBHelper;\n\n private PreferencesHelper mPreferencesHelper;\n\n @Inject\n public DataManager(BaseApiManager baseApiManager, DBHelper dbHelper, PreferencesHelper\n mPreferencesHelper) {\n this.mPreferencesHelper = mPreferencesHelper;\n this.mBaseApiManager = baseApiManager;\n this.mDBHelper = dbHelper;\n }\n\n public DBHelper getDBHelper() {\n return mDBHelper;\n }\n\n /**\n * @return PreferenceHelper\n */\n public PreferencesHelper getPreferencesHelper() {\n return mPreferencesHelper;\n }\n\n /**\n * @return List of all Announcement\n */\n public Observable<Announcements> getAllAnnouncement(Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getAllAnnouncements( options);\n }\n\n /**\n * @return Detail of Announcement\n */\n public Observable<DetailAnnouncement> getAnnouncementDetail(String id) {\n return mBaseApiManager.getTavernaApi().getAnnouncement(id);\n }\n\n /**\n * @return List of all Workflow\n */\n public Observable<Workflows> getAllWorkflow(Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getAllWorkflows(options)\n .concatMap(new Function<Workflows, ObservableSource<? extends Workflows>>() {\n @Override\n public ObservableSource<? extends Workflows> apply(Workflows workflows)\n throws Exception {\n return mDBHelper.syncWorkflows(workflows);\n }\n });\n }\n\n /**\n * @return Detail of Workflow\n */\n\n public Observable<Workflow> getDetailWorkflow(String id, Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getDetailWorkflow(id, options)\n .concatMap(new Function<Workflow, ObservableSource<? extends Workflow>>() {\n @Override\n public ObservableSource<? extends Workflow> apply(Workflow workflow)\n throws Exception {\n return mDBHelper.syncWorkflow(workflow);\n }\n });\n }\n\n /**\n * @return Detail of User\n */\n\n public Observable<User> getUserDetail(String id, Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getUserDetail(id, options);\n }\n\n /**\n * @return Detail of Licence\n */\n\n public Observable<License> getLicenseDetail(String id, Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getLicenseDetail(id, options);\n }\n\n /**\n * @return Is Workflow toggle Favourite or not\n */\n\n public Observable<Boolean> setFavoriteWorkflow(String id) {\n return mDBHelper.setFavouriteWorkflow(id);\n }\n\n /**\n * @return Is Workflow Favourite or not\n */\n\n public Observable<Boolean> getFavoriteWorkflow(String id) {\n return mDBHelper.getFavouriteWorkflow(id);\n }\n\n /**\n * @return Favourite Workflow list\n */\n\n public Observable<List<Workflow>> getFavoriteWorkflowList() {\n return mDBHelper.getFavouriteWorkflow();\n }\n\n /**\n * @param id is the id of workflow\n * @return Favourite Workflow Detail from DBhelper\n */\n\n public Observable<Workflow> getFavoriteDetailWorkflow(String id) {\n return mDBHelper.getFavouriteWorkflowDetail(id);\n }\n\n /**\n * @param credentials is base64 encoded credential\n * @param flagLogin is used to maintain the Remain login or not\n * @return User Detail if valid credentials\n */\n\n public Observable<User> getLoginUserDetail(String credentials, final boolean flagLogin) {\n return mBaseApiManager.getTavernaApi().getLoginUserDetail(credentials)\n .concatMap(new Function<User, ObservableSource<? extends User>>() {\n @Override\n public ObservableSource<? extends User> apply(User user) throws Exception {\n mPreferencesHelper.setLoggedInFlag(flagLogin);\n return mPreferencesHelper.saveUserDetail(user);\n }\n });\n }\n\n /**\n * @param url is Workflow's content xml URL\n * @return OkHTTP ResponseBody of download file\n */\n public Observable<ResponseBody> downloadWorkflowContent(String url) {\n return mBaseApiManager.getTavernaApi().downloadWorkflowContent(url);\n }\n\n /**\n * @param body is body of upload workflow's detail\n * @param baseAuth is base64 encoded credential\n * @return Workflow's ID\n */\n public Observable<PlayerWorkflow> uploadWorkflowContent(RequestBody body, String baseAuth) {\n return mBaseApiManager.getTavernaPlayerApi().uploadWorkflow(body, baseAuth);\n }\n\n /**\n * @param credentials is base64 encoded credential\n * @param flagLogin is used to maintain the Remain login or not\n * @return okHTTP ResponseBody\n */\n\n public Observable<ResponseBody> authPlayerUserLoginDetail(final String credentials,\n final boolean flagLogin) {\n return mBaseApiManager.getTavernaPlayerApi().playerlogin(credentials);\n\n }\n\n public Observable<PlayerWorkflowDetail> getWorkflowDetail(int id) {\n return mBaseApiManager.getTavernaPlayerApi().getWorkflowDetail(id);\n }\n\n public Observable<User> getMyWorkflows(String userID, Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getUserDetail(userID, options);\n }\n\n public Observable<Search> getSearchWorkflowResult(Map<String, String> options) {\n return mBaseApiManager.getTavernaApi().getSearchWorkflowResult(options);\n }\n}", "@Root(name = \"user\")\npublic class User implements Parcelable {\n\n @Attribute(name = \"resource\", required = false)\n private String resource;\n\n @Attribute(name = \"uri\", required = false)\n private String uri;\n\n @Attribute(name = \"id\", required = false)\n private String id;\n\n @Element(name = \"id\", required = false)\n private String elementId;\n\n @Element(name = \"created-at\", required = false)\n private String createdAt;\n\n @Element(name = \"name\", required = false)\n private String name;\n\n @Element(name = \"description\", required = false)\n private String description;\n\n @Element(name = \"email\", required = false)\n private String email;\n\n @Element(name = \"city\", required = false)\n private String city;\n\n @Element(name = \"country\", required = false)\n private String country;\n\n @Element(name = \"website\", required = false)\n private String website;\n\n @Element(name = \"avatar\", required = false)\n private Avatar avatar;\n\n @Element(name = \"workflows\", required = false)\n private Workflows workflows;\n\n public String getResource() {\n return resource;\n }\n\n public void setResource(String resource) {\n this.resource = resource;\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 getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getElementId() {\n return elementId;\n }\n\n public void setElementId(String elementId) {\n this.elementId = elementId;\n }\n\n public String getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(String createdAt) {\n this.createdAt = createdAt;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public String getWebsite() {\n return website;\n }\n\n public void setWebsite(String website) {\n this.website = website;\n }\n\n public Avatar getAvatar() {\n return avatar;\n }\n\n public void setAvatar(Avatar avatar) {\n this.avatar = avatar;\n }\n\n public User() {\n }\n\n public Workflows getWorkflows() {\n return workflows;\n }\n\n public void setWorkflows(Workflows workflows) {\n this.workflows = workflows;\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.resource);\n dest.writeString(this.uri);\n dest.writeString(this.id);\n dest.writeString(this.elementId);\n dest.writeString(this.createdAt);\n dest.writeString(this.name);\n dest.writeString(this.description);\n dest.writeString(this.email);\n dest.writeString(this.city);\n dest.writeString(this.country);\n dest.writeString(this.website);\n dest.writeParcelable(this.avatar, flags);\n dest.writeParcelable(this.workflows, flags);\n }\n\n protected User(Parcel in) {\n this.resource = in.readString();\n this.uri = in.readString();\n this.id = in.readString();\n this.elementId = in.readString();\n this.createdAt = in.readString();\n this.name = in.readString();\n this.description = in.readString();\n this.email = in.readString();\n this.city = in.readString();\n this.country = in.readString();\n this.website = in.readString();\n this.avatar = in.readParcelable(Avatar.class.getClassLoader());\n this.workflows = in.readParcelable(Workflows.class.getClassLoader());\n }\n\n public static final Creator<User> CREATOR = new Creator<User>() {\n @Override\n public User createFromParcel(Parcel source) {\n return new User(source);\n }\n\n @Override\n public User[] newArray(int size) {\n return new User[size];\n }\n };\n}", "public class BaseActivity extends AppCompatActivity {\n\n private ActivityComponent activityComponent;\n\n\n public ActivityComponent getActivityComponent() {\n if (activityComponent == null) {\n activityComponent = DaggerActivityComponent.builder()\n .activityModule(new ActivityModule(this))\n .applicationComponent(TavernaApplication.get(this).getComponent())\n .build();\n }\n return activityComponent;\n }\n}", "public class ImageZoomActivity extends BaseActivity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_image_zoom);\n\n ButterKnife.bind(this);\n\n\n if (savedInstanceState == null) {\n\n ActivityUtils.addFragmentToActivity(\n getSupportFragmentManager(),\n ImageZoomFragment.newInstance(\n getIntent().getStringExtra(ImageZoomFragment.JPG_URI),\n getIntent().getStringExtra(ImageZoomFragment.SVG_URI)),\n R.id.frame_container);\n\n }\n\n }\n}", "public class ImageZoomFragment extends Fragment implements ImageZoomMvpView {\n\n public static final String JPG_URI = \"jpgURI\";\n\n public static final String SVG_URI = \"svgURI\";\n\n private static final String SERVER_ERROR = \"Sever Error. Please try after sometime\";\n\n @Inject ImageZoomPresenter mImageZoomPresenter;\n\n @BindView(R.id.ivWorkflowImage)\n ImageView workflowImage;\n\n @BindView(R.id.ivClose)\n ImageView close;\n\n PhotoViewAttacher mAttacher;\n\n private String svgURI;\n\n private String jpgURI;\n\n public static ImageZoomFragment newInstance(String jpgURI, String svgURI) {\n Bundle args = new Bundle();\n args.putString(JPG_URI, jpgURI);\n args.putString(SVG_URI, svgURI);\n ImageZoomFragment fragment = new ImageZoomFragment();\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n svgURI = getArguments().getString(SVG_URI);\n jpgURI = getArguments().getString(JPG_URI);\n\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle\n savedInstanceState) {\n\n View rootView = inflater.inflate(R.layout.fragment_image_zoom, container, false);\n ((BaseActivity) getActivity()).getActivityComponent().inject(this);\n ButterKnife.bind(this, rootView);\n\n mImageZoomPresenter.attachView(this);\n\n return rootView;\n }\n\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n\n if (ConnectionInfo.isConnectingToInternet(getContext())) {\n mImageZoomPresenter.loadImage(svgURI, workflowImage);\n } else {\n showErrorSnackBar(getString(R.string.no_internet_connection));\n }\n }\n\n @OnClick(R.id.ivClose)\n public void closeActivity(View v) {\n getActivity().finish();\n }\n\n\n @Override\n public void showErrorSnackBar(String error) {\n\n final Snackbar snackbar = Snackbar.make(workflowImage, error, Snackbar.LENGTH_INDEFINITE);\n snackbar.setAction(\"OK\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n snackbar.dismiss();\n getActivity().finish();\n }\n });\n snackbar.show();\n\n Handler handler = new Handler();\n handler.postDelayed(new Runnable() {\n public void run() {\n snackbar.dismiss();\n getActivity().finish();\n }\n }, 2000);\n }\n\n @Override\n public Context getAppContext() {\n return getContext();\n }\n\n\n @Override\n public void setJPGImage() {\n\n\n Glide.with(getContext())\n .load(jpgURI)\n .diskCacheStrategy(DiskCacheStrategy.SOURCE)\n .placeholder(R.drawable.placeholder)\n .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)\n .into(new Target<GlideDrawable>() {\n @Override\n public void onLoadStarted(Drawable placeholder) {\n workflowImage.setImageDrawable(placeholder);\n }\n\n @Override\n public void onLoadFailed(Exception e, Drawable errorDrawable) {\n showErrorSnackBar(SERVER_ERROR);\n }\n\n @Override\n public void onResourceReady(GlideDrawable resource,\n GlideAnimation<? super GlideDrawable>\n glideAnimation) {\n workflowImage.setImageDrawable(resource.getCurrent());\n addImageAttacher();\n\n }\n\n @Override\n public void onLoadCleared(Drawable placeholder) {\n workflowImage.setImageDrawable(placeholder);\n }\n\n @Override\n public void getSize(SizeReadyCallback cb) {\n\n }\n\n @Override\n public Request getRequest() {\n return null;\n }\n\n @Override\n public void setRequest(Request request) {\n\n }\n\n @Override\n public void onStart() {\n\n }\n\n @Override\n public void onStop() {\n\n }\n\n @Override\n public void onDestroy() {\n\n }\n });\n\n }\n\n @Override\n public void addImageAttacher() {\n mAttacher = new PhotoViewAttacher(workflowImage);\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n mImageZoomPresenter.detachView();\n }\n}", "public class WorkflowRunActivity extends BaseActivity implements WorkflowRunMvpView,\n PlayerLoginFragment.OnSuccessful {\n\n @Inject\n DataManager dataManager;\n @Inject\n WorkflowRunPresenter mWorkflowRunPresenter;\n PagerAdapter mPagerAdapter;\n\n @BindView(R.id.stepsView)\n StepsView mStepsView;\n\n @BindView(R.id.viewpager)\n NonSwipeableViewPager mPager;\n\n int position = 0;\n\n private String[] labels;\n private String workflowRunURL;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getActivityComponent().inject(this);\n setContentView(R.layout.activity_workflow_run);\n\n ButterKnife.bind(this);\n\n\n\n mWorkflowRunPresenter.attachView(this);\n\n labels = getResources().getStringArray(R.array.player_run_slider_view_labels);\n\n mStepsView.setCompletedPosition(position % labels.length)\n .setLabels(labels)\n .setBarColorIndicator(\n getContext().getResources().getColor(R.color.material_blue_grey_800))\n .setProgressColorIndicator(getContext().getResources().getColor(R.color\n .colorPrimary))\n .setLabelColorIndicator(getContext().getResources().getColor(R.color.colorPrimary))\n .drawView();\n\n\n mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());\n mPager.setAdapter(mPagerAdapter);\n\n if (dataManager.getPreferencesHelper().isUserPlayerLoggedInFlag()) {\n mPager.setCurrentItem(++position);\n mStepsView.setCompletedPosition(position % labels.length).drawView();\n\n mWorkflowRunPresenter.runWorkflow(getIntent().getStringExtra(Constants.WORKFLOW_URL));\n }\n\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n mWorkflowRunPresenter.detachView();\n }\n\n\n @Override\n public void onSuccessfulLogin() {\n position = 1;\n mPager.setCurrentItem(position);\n mStepsView.setCompletedPosition(position % labels.length).drawView();\n mWorkflowRunPresenter.runWorkflow(getIntent().getStringExtra(Constants.WORKFLOW_URL));\n }\n\n @Override\n public void movetoUploadWorkflow() {\n position = 2;\n mPager.setCurrentItem(position);\n mStepsView.setCompletedPosition(position % labels.length).drawView();\n }\n\n @Override\n public void movetoInputs() {\n position = 3;\n mStepsView.setCompletedPosition(position % labels.length).drawView();\n mPager.setCurrentItem(position);\n\n }\n\n @Override\n public void setInputsAttribute(int id) {\n String playerURL = dataManager.getPreferencesHelper().getPlayerURL();\n\n if (playerURL.trim().endsWith(\"/\")) {\n playerURL = playerURL.substring(0, playerURL.length() - 1);\n }\n workflowRunURL = playerURL + \"/workflows/\" + id +\n \"/runs/new\";\n mPager.getAdapter().notifyDataSetChanged();\n }\n\n @Override\n public void showError() {\n Toast.makeText(this, getString(R.string.servererr), Toast\n .LENGTH_LONG).show();\n finish();\n }\n\n\n private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {\n public ScreenSlidePagerAdapter(FragmentManager fm) {\n super(fm);\n }\n\n @Override\n public Fragment getItem(int position) {\n switch (position) {\n case 0:\n return PlayerLoginFragment.newInstance();\n case 1:\n return DownloadingFragment.newInstance(getString(R.string\n .downloading_workflow_lable));\n case 2:\n return DownloadingFragment.newInstance(getString(R.string\n .uploading_workflow_lable));\n default:\n return WebViewGenerator.newInstance(workflowRunURL);\n\n }\n }\n\n @Override\n public int getCount() {\n return 4;\n }\n }\n\n\n}" ]
import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import org.apache.taverna.mobile.R; import org.apache.taverna.mobile.data.DataManager; import org.apache.taverna.mobile.data.model.License; import org.apache.taverna.mobile.data.model.User; import org.apache.taverna.mobile.data.model.Workflow; import org.apache.taverna.mobile.ui.base.BaseActivity; import org.apache.taverna.mobile.ui.imagezoom.ImageZoomActivity; import org.apache.taverna.mobile.ui.imagezoom.ImageZoomFragment; import org.apache.taverna.mobile.ui.workflowrun.WorkflowRunActivity; import org.apache.taverna.mobile.utils.ConnectionInfo; import org.apache.taverna.mobile.utils.Constants; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.taverna.mobile.ui.favouriteworkflowdetail; public class FavouriteWorkflowDetailFragment extends Fragment implements FavouriteWorkflowDetailMvpView { private static final String ID = "id"; public final String LOG_TAG = getClass().getSimpleName(); @Inject DataManager dataManager; @Inject FavouriteWorkflowDetailPresenter mWorkflowDetailPresenter; @BindView(R.id.ivWorkflowImage) ImageView workflowImage; @BindView(R.id.tvTitle) TextView title; @BindView(R.id.ivUploader) ImageView uploaderImage; @BindView(R.id.tvUploaderName) TextView uploaderName; @BindView(R.id.tvDate) TextView date; @BindView(R.id.tvType) TextView type; @BindView(R.id.tvDescription) WebView description; @BindView(R.id.ivFav) ImageView ivFavourite; @BindView(R.id.progressBar) ProgressBar mProgressBar; @BindView(R.id.scrollView) ScrollView mScrollView; @BindView(R.id.rootLayout) RelativeLayout rootLayout; @BindView(R.id.fabRun) FloatingActionButton fabRun; private AlertDialog alertDialog; private String id; private String licenceId = null; private ProgressDialog dialog; private ActionBar actionBar; private Workflow mWorkflow; public static FavouriteWorkflowDetailFragment newInstance(String id) { Bundle args = new Bundle(); args.putString(ID, id); FavouriteWorkflowDetailFragment fragment = new FavouriteWorkflowDetailFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); id = getArguments().getString(ID); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_detail_workflow, container, false);
((BaseActivity) getActivity()).getActivityComponent().inject(this);
2
njustesen/hero-aicademy
src/ai/evaluation/MeanEvaluator.java
[ "public class MapLoader {\n\t\n\tprivate static final char P1CRYSTAL = 'c';\n\tprivate static final char P2CRYSTAL = 'C';\n\tstatic Map<Character, SquareType> codes = new HashMap<Character, SquareType>();\n\tstatic {\n\t\tcodes.put('0', SquareType.NONE);\n\t\tcodes.put('d', SquareType.DEPLOY_1);\n\t\tcodes.put('D', SquareType.DEPLOY_2);\n\t\tcodes.put('S', SquareType.DEFENSE);\n\t\tcodes.put('A', SquareType.ASSAULT);\n\t\tcodes.put('P', SquareType.POWER);\n\t\tcodes.put('c', SquareType.NONE);\n\t\tcodes.put('C', SquareType.NONE);\n\t\t//codes.put('H', SquareType.);\n\t}\n\tstatic Map<String, HaMap> maps = new HashMap<String, HaMap>();\n\n\tpublic static HaMap get(String name) throws IOException{\n\n\t\tif (maps.containsKey(name)) \n\t\t\treturn maps.get(name);\n\t\telse\n\t\t\tload (name);\n\t\t\n\t\treturn get(name);\n\t}\n\t\n\tpublic static void load(String name) throws IOException{\n\t\n\t\tString basePath = PathHelper.basePath();\n\t\tList<String> lines = readLines(basePath + \"/maps/\"+name+\".mhap\");\n\t\n\t\tList<Position> p1Crystals = new ArrayList<Position>();\n\t\tList<Position> p2Crystals = new ArrayList<Position>();\n\t\tList<List<SquareType>> squareLists = new ArrayList<List<SquareType>>();\n\t\tint y = 0;\n\t\tfor(String line : lines){\n\t\t\tif (line.length() == 0 || line.charAt(0) == '#')\n\t\t\t\tcontinue;\n\t\t\tList<SquareType> squareList = new ArrayList<SquareType>();\n\t\t\t\n\t\t\tfor(int x = 0; x < line.length(); x++){\n\t\t\t\tif (line.charAt(x) == P1CRYSTAL)\n\t\t\t\t\tp1Crystals.add(new Position(x, y));\n\t\t\t\telse if (line.charAt(x) == P2CRYSTAL)\n\t\t\t\t\tp2Crystals.add(new Position(x, y));\n\t\t\t\tsquareList.add(codes.get(line.charAt(x)));\n\t\t\t}\n\t\t\tsquareLists.add(squareList);\n\t\t\ty++;\n\t\t}\n\t\t\n\t\tint height = squareLists.size();\n\t\tint width = squareLists.get(0).size();\n\t\t\n\t\tfinal SquareType[][] grid = new SquareType[width][height];\n\t\tfor(y = 0; y < height; y++)\n\t\t\tfor(int x = 0; x < width; x++)\n\t\t\t\tgrid[x][y] = squareLists.get(y).get(x);\n\t\t\n\t\tfinal HaMap map = new HaMap(width, height, grid, name);\n\t\t\n\t\tfor (Position p : p1Crystals)\n\t\t\tmap.p1Crystals.add(p);\n\t\tfor (Position p : p2Crystals)\n\t\t\tmap.p2Crystals.add(p);\n\t\t\n\t\tmaps.put(name, map);\n\t}\n\n\tstatic List<String> readLines( String filename ) throws IOException {\n\t BufferedReader\treader = new BufferedReader( new FileReader (filename));\n\t String \tline = null;\n\t List<String> \tlines = new ArrayList<String>();\n\n\t while( ( line = reader.readLine() ) != null ) {\n\t lines.add(line);\n\t }\n\n\t reader.close();\n\t \n\t return lines;\n\t}\n\t\n}", "public class NormUtil {\n\t\n\tpublic static double normalize(double x, double dataLow, double dataHigh, double normHigh, double normLow) {\n\t\treturn ((x - dataLow) \n\t\t\t\t/ (dataHigh - dataLow))\n\t\t\t\t* (normHigh - normLow) + normLow;\n\t}\n\t\n}", "public class GameState {\n\t\n\tpublic static int TURN_LIMIT = 100;\n\tpublic static boolean RANDOMNESS = false;\n\tpublic static int STARTING_AP = 3;\n\tpublic static int ACTION_POINTS = 5;\n\t\n\tprivate static final int ASSAULT_BONUS = 300;\n\tprivate static final double INFERNO_DAMAGE = 350;\n\tprivate static final int REQUIRED_UNITS = 3;\n\tprivate static final int POTION_REVIVE = 100;\n\tprivate static final int POTION_HEAL = 1000;\n\tpublic static final boolean OPEN_HANDS = false;\n\n\tpublic HaMap map;\n\tpublic boolean p1Turn;\n\tpublic int turn;\n\tpublic int APLeft;\n\tpublic Unit[][] units;\n\tpublic CardSet p1Deck;\n\tpublic CardSet p2Deck;\n\tpublic CardSet p1Hand;\n\tpublic CardSet p2Hand;\n\tpublic boolean isTerminal;\n\n\tpublic List<Position> chainTargets;\n\n\tpublic GameState(HaMap map) {\n\t\tsuper();\n\t\tisTerminal = false;\n\t\tthis.map = map;\n\t\tp1Turn = true;\n\t\tturn = 1;\n\t\tAPLeft = STARTING_AP;\n\t\tp1Hand = new CardSet();\n\t\tp2Hand = new CardSet();\n\t\tp1Deck = new CardSet();\n\t\tp2Deck = new CardSet();\n\t\tchainTargets = new ArrayList<Position>();\n\t\tif (map != null)\n\t\t\tunits = new Unit[map.width][map.height];\n\t\telse\n\t\t\tunits = new Unit[0][0];\n\t}\n\n\tpublic GameState(HaMap map, boolean p1Turn, int turn, int APLeft,\n\t\t\tUnit[][] units, CardSet p1Hand, CardSet p2Hand, CardSet p1Deck,\n\t\t\tCardSet p2Deck, List<Position> chainTargets, boolean isTerminal) {\n\t\tsuper();\n\t\tthis.map = map;\n\t\tthis.p1Turn = p1Turn;\n\t\tthis.turn = turn;\n\t\tthis.APLeft = APLeft;\n\t\tthis.units = units;\n\t\tthis.p1Hand = p1Hand;\n\t\tthis.p2Hand = p2Hand;\n\t\tthis.p1Deck = p1Deck;\n\t\tthis.p2Deck = p2Deck;\n\t\tthis.chainTargets = chainTargets;\n\t\tthis.isTerminal = isTerminal;\n\t\t\n\t}\n\n\tpublic void init(DECK_SIZE deckSize) {\n\t\tp1Hand = new CardSet();\n\t\tp2Hand = new CardSet();\n\t\tp1Deck = new CardSet();\n\t\tp2Deck = new CardSet();\n\t\tshuffleDecks(deckSize);\n\t\tdealCards();\n\t\tfor (final Position pos : map.p1Crystals) {\n\t\t\tunits[pos.x][pos.y] = new Unit(Card.CRYSTAL, true);\n\t\t\tunits[pos.x][pos.y].init(Card.CRYSTAL, true);\n\t\t}\n\t\tfor (final Position pos : map.p2Crystals) {\n\t\t\tunits[pos.x][pos.y] = new Unit(Card.CRYSTAL, false);\n\t\t\tunits[pos.x][pos.y].init(Card.CRYSTAL, false);\n\t\t}\n\t}\n\n\tprivate void shuffleDecks(DECK_SIZE deckSize) {\n\t\tfor (final Card type : Council.deck(deckSize)) {\n\t\t\tp1Deck.add(type);\n\t\t\tp2Deck.add(type);\n\t\t}\n\t}\n\n\tpublic void possibleActions(List<Action> actions) {\n\n\t\tactions.clear();\n\n\t\tif (APLeft == 0) {\n\t\t\tactions.add(SingletonAction.endTurnAction);\n\t\t\treturn;\n\t\t}\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tpossibleActions(units[x][y], SingletonAction.positions[x][y], actions);\n\n\t\tfinal List<Card> visited = new ArrayList<Card>();\n\t\tfor (final Card card : Card.values())\n\t\t\tif (currentHand().contains(card)) {\n\t\t\t\tpossibleActions(card, actions);\n\t\t\t\tvisited.add(card);\n\t\t\t}\n\n\t}\n\n\tpublic void possibleActions(Card card, List<Action> actions) {\n\n\t\tif (APLeft == 0)\n\t\t\treturn;\n\n\t\tif (card.type == CardType.ITEM) {\n\t\t\tfor (int x = 0; x < map.width; x++)\n\t\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\t\tif (units[x][y] != null\n\t\t\t\t\t\t\t&& units[x][y].unitClass.card != Card.CRYSTAL) {\n\t\t\t\t\t\tif (units[x][y].equipment.contains(card))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (units[x][y].p1Owner == p1Turn) {\n\t\t\t\t\t\t\tif (card == Card.REVIVE_POTION\n\t\t\t\t\t\t\t\t\t&& units[x][y].fullHealth())\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif (card != Card.REVIVE_POTION\n\t\t\t\t\t\t\t\t\t&& units[x][y].hp == 0)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[x][y]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t} else if (card.type == CardType.SPELL)\n\t\t\tfor (int x = 0; x < map.width; x++)\n\t\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[x][y]));\n\t\telse if (card.type == CardType.UNIT)\n\t\t\tif (p1Turn) {\n\t\t\t\tfor (final Position pos : map.p1DeploySquares)\n\t\t\t\t\tif (units[pos.x][pos.y] == null\n\t\t\t\t\t\t\t|| units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[pos.x][pos.y]));\n\t\t\t} else\n\t\t\t\tfor (final Position pos : map.p2DeploySquares)\n\t\t\t\t\tif (units[pos.x][pos.y] == null\n\t\t\t\t\t\t\t|| units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[pos.x][pos.y]));\n\n\t\tif (!currentDeck().isEmpty())\n\t\t\tactions.add(SingletonAction.swapActions.get(card));\n\n\t}\n\n\tpublic void possibleActions(Unit unit, Position from, List<Action> actions) {\n\n\t\tif (unit.unitClass.card == Card.CRYSTAL)\n\t\t\treturn;\n\n\t\tif (APLeft == 0 || unit.hp == 0 || APLeft == 0\n\t\t\t\t|| unit.p1Owner != p1Turn)\n\t\t\treturn;\n\n\t\t// Movement and attack\n\t\tint d = unit.unitClass.speed;\n\t\tif (unit.unitClass.heal != null && unit.unitClass.heal.range > d)\n\t\t\td = unit.unitClass.heal.range;\n\t\tif (unit.unitClass.attack != null && unit.unitClass.attack.range > d)\n\t\t\td = unit.unitClass.attack.range;\n\t\tif (unit.unitClass.swap)\n\t\t\td = Math.max(map.width, map.height);\n\t\tfor (int x = d * (-1); x <= d; x++)\n\t\t\tfor (int y = d * (-1); y <= d; y++) {\n\t\t\t\tif (from.x + x >= map.width || from.x + x < 0 || from.y + y >= map.height || from.y + y < 0)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfinal Position to = SingletonAction.positions[from.x + x][from.y +y];\n\t\t\t\t\n\t\t\t\tif (to.equals(from))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (units[to.x][to.y] != null) {\n\n\t\t\t\t\tif (units[to.x][to.y].hp == 0) {\n\n\t\t\t\t\t\tif ((map.squares[to.x][to.y] == SquareType.DEPLOY_1 && !p1Turn)\n\t\t\t\t\t\t\t\t|| (map.squares[to.x][to.y] == SquareType.DEPLOY_2 && p1Turn)) {\n\t\t\t\t\t\t\t// NOT ALLOWED!\n\t\t\t\t\t\t} else if (unit.unitClass.heal != null\n\t\t\t\t\t\t\t\t&& from.distance(to) <= unit.unitClass.heal.range)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.HEAL));\n\t\t\t\t\t\telse if (from.distance(to) <= unit.unitClass.speed)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.MOVE));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfinal int distance = from.distance(to);\n\t\t\t\t\t\tif (unit.p1Owner != units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& distance <= unit.unitClass.attack.range) {\n\t\t\t\t\t\t\tif (!(distance > 1 && losBlocked(p1Turn, from, to)))\n\t\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\t\tUnitActionType.ATTACK));\n\t\t\t\t\t\t} else if (unit.p1Owner == units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& unit.unitClass.heal != null\n\t\t\t\t\t\t\t\t&& from.distance(to) <= unit.unitClass.heal.range\n\t\t\t\t\t\t\t\t&& !units[to.x][to.y].fullHealth()\n\t\t\t\t\t\t\t\t&& units[to.x][to.y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.HEAL));\n\t\t\t\t\t\telse if (unit.p1Owner == units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& unit.unitClass.swap\n\t\t\t\t\t\t\t\t&& units[to.x][to.y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.SWAP));\n\t\t\t\t\t}\n\n\t\t\t\t} else if (from.distance(to) <= unit.unitClass.speed)\n\t\t\t\t\tif ((map.squares[to.x][to.y] == SquareType.DEPLOY_1 && !p1Turn)\n\t\t\t\t\t\t\t|| (map.squares[to.x][to.y] == SquareType.DEPLOY_2 && p1Turn)) {\n\t\t\t\t\t\t// NOT ALLOWED!\n\t\t\t\t\t} else\n\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\tUnitActionType.MOVE));\n\t\t\t}\n\t}\n\n\tpublic void update(List<Action> actions) {\n\t\tfor (final Action action : actions)\n\t\t\tupdate(action);\n\t}\n\n\tpublic void update(Action action) {\n\n\t\ttry {\n\t\t\tchainTargets.clear();\n\n\t\t\tif (action instanceof EndTurnAction || APLeft <= 0)\n\t\t\t\tendTurn();\n\n\t\t\tif (action instanceof DropAction) {\n\n\t\t\t\tfinal DropAction drop = (DropAction) action;\n\n\t\t\t\t// Not a type in current players hand\n\t\t\t\tif (!currentHand().contains(drop.type))\n\t\t\t\t\treturn;\n\n\t\t\t\t// Unit\n\t\t\t\tif (drop.type.type == CardType.UNIT) {\n\n\t\t\t\t\t// Not current players deploy square\n\t\t\t\t\tif (map.squares[drop.to.x][drop.to.y] == SquareType.DEPLOY_1\n\t\t\t\t\t\t\t&& !p1Turn)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tif (map.squares[drop.to.x][drop.to.y] == SquareType.DEPLOY_2\n\t\t\t\t\t\t\t&& p1Turn)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tdeploy(drop.type, drop.to);\n\n\t\t\t\t}\n\n\t\t\t\t// Equipment\n\t\t\t\tif (drop.type.type == CardType.ITEM) {\n\n\t\t\t\t\t// Not a unit square or crystal\n\t\t\t\t\tif (units[drop.to.x][drop.to.y] == null\n\t\t\t\t\t\t\t|| units[drop.to.x][drop.to.y].unitClass.card == Card.CRYSTAL)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (units[drop.to.x][drop.to.y].p1Owner != p1Turn)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (drop.type == Card.REVIVE_POTION\n\t\t\t\t\t\t\t&& (units[drop.to.x][drop.to.y].unitClass.card == Card.CRYSTAL || units[drop.to.x][drop.to.y]\n\t\t\t\t\t\t\t\t\t.fullHealth()))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (drop.type != Card.REVIVE_POTION\n\t\t\t\t\t\t\t&& units[drop.to.x][drop.to.y].hp == 0)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (units[drop.to.x][drop.to.y].equipment\n\t\t\t\t\t\t\t.contains(drop.type))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tequip(drop.type, drop.to);\n\n\t\t\t\t}\n\n\t\t\t\t// Spell\n\t\t\t\tif (drop.type.type == CardType.SPELL)\n\t\t\t\t\tdropInferno(drop.to);\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tif (action instanceof UnitAction) {\n\n\t\t\t\tfinal UnitAction ua = (UnitAction) action;\n\n\t\t\t\tif (units[ua.from.x][ua.from.y] == null)\n\t\t\t\t\treturn;\n\n\t\t\t\tfinal Unit unit = units[ua.from.x][ua.from.y];\n\n\t\t\t\tif (unit == null)\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tif (unit.p1Owner != p1Turn)\n\t\t\t\t\treturn;\n\n\t\t\t\tif (unit.hp == 0)\n\t\t\t\t\treturn;\n\n\t\t\t\t// Move\n\t\t\t\tif (units[ua.to.x][ua.to.y] == null\n\t\t\t\t\t\t|| (unit.p1Owner == units[ua.to.x][ua.to.y].p1Owner\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].hp == 0 && unit.unitClass.heal == null)\n\t\t\t\t\t\t|| (unit.p1Owner != units[ua.to.x][ua.to.y].p1Owner && units[ua.to.x][ua.to.y].hp == 0)) {\n\n\t\t\t\t\tif (ua.from.distance(ua.to) > units[ua.from.x][ua.from.y].unitClass.speed)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (map.squares[ua.to.x][ua.to.y] == SquareType.DEPLOY_1\n\t\t\t\t\t\t\t&& !unit.p1Owner)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (map.squares[ua.to.x][ua.to.y] == SquareType.DEPLOY_2\n\t\t\t\t\t\t\t&& unit.p1Owner)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tmove(unit, ua.from, ua.to);\n\t\t\t\t\treturn;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tfinal Unit other = units[ua.to.x][ua.to.y];\n\n\t\t\t\t\t// Swap and heal\n\t\t\t\t\tif (unit.p1Owner == other.p1Owner) {\n\t\t\t\t\t\tif (unit.unitClass.swap\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].unitClass.card != Card.CRYSTAL\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].hp != 0) {\n\t\t\t\t\t\t\tswap(unit, ua.from, other, ua.to);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (unit.unitClass.heal == null)\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\tif (ua.from.distance(ua.to) > unit.unitClass.heal.range)\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\tif (other.fullHealth())\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\theal(unit, ua.from, other);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Attack\n\t\t\t\t\tfinal int distance = ua.from.distance(ua.to);\n\t\t\t\t\tif (unit.unitClass.attack != null\n\t\t\t\t\t\t\t&& distance > unit.unitClass.attack.range)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (distance > 1 && losBlocked(p1Turn, ua.from, ua.to))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (other == null)\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\n\t\t\t\t\tattack(unit, ua.from, other, ua.to);\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (action instanceof SwapCardAction) {\n\n\t\t\t\tfinal Card card = ((SwapCardAction) action).card;\n\n\t\t\t\tif (currentHand().contains(card)) {\n\n\t\t\t\t\tcurrentDeck().add(card);\n\t\t\t\t\tcurrentHand().remove(card);\n\t\t\t\t\tAPLeft--;\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t} catch (final Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t/**\n\t * Using the Bresenham-based super-cover line algorithm\n\t * \n\t * @param from\n\t * @param to\n\t * @return\n\t */\n\tpublic boolean losBlocked(boolean p1, Position from, Position to) {\n\n\t\tif (from.distance(to) == 1\n\t\t\t\t|| (from.getDirection(to).isDiagonal() && from.distance(to) == 2))\n\t\t\treturn false;\n\n\t\tfor (final Position pos : CachedLines.supercover(from, to)) {\n\t\t\tif (pos.equals(from) || pos.equals(to))\n\t\t\t\tcontinue;\n\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].p1Owner != p1\n\t\t\t\t\t&& units[pos.x][pos.y].hp != 0)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tprivate void dropInferno(Position to) throws Exception {\n\n\t\tfor (int x = -1; x <= 1; x++)\n\t\t\tfor (int y = -1; y <= 1; y++) {\n\t\t\t\tif (to.x + x < 0 || to.x + x >= map.width || to.y + y < 0 || to.y + y >= map.height)\n\t\t\t\t\tcontinue;\n\t\t\t\tfinal Position pos = SingletonAction.positions[to.x + x][to.y + y];\n\t\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t\t&& units[pos.x][pos.y].p1Owner != p1Turn) {\n\t\t\t\t\tif (units[pos.x][pos.y].hp == 0) {\n\t\t\t\t\t\tunits[pos.x][pos.y] = null;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdouble damage = INFERNO_DAMAGE;\n\t\t\t\t\tif (units[pos.x][pos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\t\tfinal int bonus = assaultBonus();\n\t\t\t\t\t\tdamage += bonus;\n\t\t\t\t\t}\n\t\t\t\t\tfinal double resistance = units[pos.x][pos.y].resistance(\n\t\t\t\t\t\t\tthis, pos, AttackType.Magical);\n\t\t\t\t\tdamage = damage * ((100d - resistance) / 100d);\n\t\t\t\t\tunits[pos.x][pos.y].hp -= damage;\n\t\t\t\t\tif (units[pos.x][pos.y].hp <= 0)\n\t\t\t\t\t\tif (units[pos.x][pos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t\t\t\tunits[pos.x][pos.y] = null;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tunits[pos.x][pos.y].hp = 0;\n\t\t\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcurrentHand().remove(Card.INFERNO);\n\t\tAPLeft--;\n\n\t}\n\n\tprivate void attack(Unit attacker, Position attPos, Unit defender, Position defPos) throws Exception {\n\t\tif (attacker.unitClass.attack == null)\n\t\t\treturn;\n\t\tif (defender.hp == 0) {\n\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t\tmove(attacker, attPos, defPos);\n\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t} else {\n\t\t\tint damage = attacker.damage(this, attPos, defender, defPos);\n\t\t\tif (defender.unitClass.card == Card.CRYSTAL) {\n\t\t\t\tfinal int bonus = assaultBonus();\n\t\t\t\tdamage += bonus;\n\t\t\t}\n\t\t\tdefender.hp -= damage;\n\t\t\tif (defender.hp <= 0) {\n\t\t\t\tdefender.hp = 0;\n\t\t\t\tif (defender.unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t} else {\n\t\t\t\t\tunits[defPos.x][defPos.y].hp = 0;\n\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (attacker.unitClass.attack.push)\n\t\t\t\tpush(defender, attPos, defPos);\n\t\t\tif (attacker.unitClass.attack.chain)\n\t\t\t\tchain(attacker,\n\t\t\t\t\t\tattPos,\n\t\t\t\t\t\tdefPos,\n\t\t\t\t\t\tDirection.direction(defPos.x - attPos.x, defPos.y\n\t\t\t\t\t\t\t\t- attPos.y), 1);\n\t\t}\n\t\tattacker.equipment.remove(Card.SCROLL);\n\t\tAPLeft--;\n\t}\n\n\tprivate void chain(Unit attacker, Position attPos, Position from,\n\t\t\tDirection dir, int jump) throws Exception {\n\n\t\tif (jump >= 3)\n\t\t\treturn;\n\n\t\tfinal Position bestPos = nextJump(from, dir);\n\n\t\t// Attack\n\t\tif (bestPos != null) {\n\t\t\tchainTargets.add(bestPos);\n\t\t\tint damage = attacker.damage(this, attPos,\n\t\t\t\t\tunits[bestPos.x][bestPos.y], bestPos);\n\t\t\tif (jump == 1)\n\t\t\t\tdamage = (int) (damage * 0.75);\n\t\t\telse if (jump == 2)\n\t\t\t\tdamage = (int) (damage * 0.56);\n\t\t\telse\n\t\t\t\tSystem.out.println(\"Illegal number of jumps!\");\n\n\t\t\tif (units[bestPos.x][bestPos.y].unitClass.card == Card.CRYSTAL)\n\t\t\t\tdamage += assaultBonus();\n\n\t\t\tunits[bestPos.x][bestPos.y].hp -= damage;\n\t\t\tif (units[bestPos.x][bestPos.y].hp <= 0) {\n\t\t\t\tunits[bestPos.x][bestPos.y].hp = 0;\n\t\t\t\tif (units[bestPos.x][bestPos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t\tunits[bestPos.x][bestPos.y] = null;\n\t\t\t\t} else {\n\t\t\t\t\tunits[bestPos.x][bestPos.y].hp = 0;\n\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tchain(attacker, attPos, bestPos, from.getDirection(bestPos),\n\t\t\t\t\tjump + 1);\n\t\t}\n\n\t}\n\n\tprivate Position nextJump(Position from, Direction dir) {\n\n\t\tint bestValue = 0;\n\t\tPosition bestPos = null;\n\n\t\t// Find best target\n\t\tfor (int newDirX = -1; newDirX <= 1; newDirX++)\n\t\t\tfor (int newDirY = -1; newDirY <= 1; newDirY++) {\n\t\t\t\tif (newDirX == 0 && newDirY == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (from.x + newDirX < 0 || from.x + newDirX >= map.width || from.y + newDirY < 0 || from.y + newDirY >= map.height)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfinal Position newPos = SingletonAction.positions[from.x + newDirX][from.y + newDirY];\n\t\t\t\t\n\t\t\t\tif (units[newPos.x][newPos.y] != null\n\t\t\t\t\t\t&& units[newPos.x][newPos.y].p1Owner != p1Turn\n\t\t\t\t\t\t&& units[newPos.x][newPos.y].hp > 0) {\n\n\t\t\t\t\tfinal Direction newDir = Direction.direction(newDirX,\n\t\t\t\t\t\t\tnewDirY);\n\n\t\t\t\t\tif (newDir.opposite(dir))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfinal int chainValue = chainValue(dir, newDir);\n\n\t\t\t\t\tif (chainValue > bestValue) {\n\t\t\t\t\t\tbestPos = newPos;\n\t\t\t\t\t\tbestValue = chainValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\treturn bestPos;\n\t}\n\n\tprivate int chainValue(Direction dir, Direction newDir) {\n\n\t\tif (dir.equals(newDir))\n\t\t\treturn 10;\n\n\t\tint value = 1;\n\n\t\tif (!newDir.isDiagonal())\n\t\t\tvalue += 4;\n\n\t\tif (newDir.isNorth())\n\t\t\tvalue += 2;\n\n\t\tif (newDir.isEast())\n\t\t\tvalue += 1;\n\n\t\treturn value;\n\n\t}\n\n\tprivate int assaultBonus() {\n\t\tint bonus = 0;\n\t\tfor (final Position pos : map.assaultSquares)\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].p1Owner == p1Turn\n\t\t\t\t\t&& units[pos.x][pos.y].hp != 0)\n\t\t\t\tbonus += ASSAULT_BONUS;\n\t\treturn bonus;\n\t}\n\n\tprivate void checkWinOnUnits(int p) {\n\n\t\tif (!aliveOnUnits(p))\n\t\t\tisTerminal = true;\n\n\t}\n\n\tprivate void checkWinOnCrystals(int p) {\n\n\t\tif (!aliveOnCrystals(p))\n\t\t\tisTerminal = true;\n\n\t}\n\n\tpublic int getWinner() {\n\n\t\tif (turn >= TURN_LIMIT)\n\t\t\treturn 0;\n\t\t\n\t\tboolean p1Alive = true;\n\t\tboolean p2Alive = true;\n\n\t\tif (!aliveOnCrystals(1) || !aliveOnUnits(1))\n\t\t\tp1Alive = false;\n\n\t\tif (!aliveOnCrystals(2) || !aliveOnUnits(2))\n\t\t\tp2Alive = false;\n\n\t\tif (p1Alive == p2Alive)\n\t\t\treturn 0;\n\n\t\tif (p1Alive)\n\t\t\treturn 1;\n\n\t\tif (p2Alive)\n\t\t\treturn 2;\n\n\t\treturn 0;\n\n\t}\n\n\tprivate boolean aliveOnCrystals(int player) {\n\n\t\tfor (final Position pos : crystals(player))\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].unitClass.card == Card.CRYSTAL\n\t\t\t\t\t&& units[pos.x][pos.y].hp > 0)\n\t\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate List<Position> crystals(int player) {\n\t\tif (player == 1)\n\t\t\treturn map.p1Crystals;\n\t\tif (player == 2)\n\t\t\treturn map.p2Crystals;\n\t\treturn null;\n\t}\n\n\tprivate boolean aliveOnUnits(int player) {\n\n\t\tif (deck(player).hasUnits() || hand(player).hasUnits())\n\t\t\treturn true;\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null && units[x][y].p1Owner == (player == 1)\n\t\t\t\t\t\t&& units[x][y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate CardSet deck(int player) {\n\t\tif (player == 1)\n\t\t\treturn p1Deck;\n\t\tif (player == 2)\n\t\t\treturn p2Deck;\n\t\treturn null;\n\t}\n\n\tprivate CardSet hand(int player) {\n\t\tif (player == 1)\n\t\t\treturn p1Hand;\n\t\tif (player == 2)\n\t\t\treturn p2Hand;\n\t\treturn null;\n\t}\n\n\tprivate void push(Unit defender, Position attPos, Position defPos)\n\t\t\tthrows Exception {\n\n\t\tif (defender.unitClass.card == Card.CRYSTAL)\n\t\t\treturn;\n\n\t\tint x = 0;\n\t\tint y = 0;\n\n\t\tif (attPos.x > defPos.x)\n\t\t\tx = -1;\n\t\tif (attPos.x < defPos.x)\n\t\t\tx = 1;\n\t\tif (attPos.y > defPos.y)\n\t\t\ty = -1;\n\t\tif (attPos.y < defPos.y)\n\t\t\ty = 1;\n\n\t\tif (defPos.x + x >= map.width || defPos.x + x < 0 || defPos.y + y >= map.height || defPos.y + y < 0)\n\t\t\treturn;\n\n\t\tfinal Position newPos = SingletonAction.positions[defPos.x + x][defPos.y + y];\n\t\t\n\t\tif (units[newPos.x][newPos.y] != null\n\t\t\t\t&& units[newPos.x][newPos.y].hp > 0)\n\t\t\treturn;\n\n\t\tif (map.squareAt(newPos) == SquareType.DEPLOY_1 && !defender.p1Owner)\n\t\t\treturn;\n\n\t\tif (map.squareAt(newPos) == SquareType.DEPLOY_2 && defender.p1Owner)\n\t\t\treturn;\n\n\t\tif (units[defPos.x][defPos.y] != null) {\n\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t}\n\n\t\tunits[newPos.x][newPos.y] = defender;\n\n\t}\n\n\tprivate void heal(Unit healer, Position pos, Unit unitTo) {\n\n\t\tint power = healer.power(this, pos);\n\n\t\tif (unitTo.hp == 0)\n\t\t\tpower *= healer.unitClass.heal.revive;\n\t\telse\n\t\t\tpower *= healer.unitClass.heal.heal;\n\t\t\n\t\tunitTo.heal(power);\n\t\thealer.equipment.remove(Card.SCROLL);\n\t\t\n\t\tAPLeft--;\n\n\t}\n\n\tprivate void swap(Unit unitFrom, Position from, Unit unitTo, Position to) {\n\t\tunits[from.x][from.y] = unitTo;\n\t\tunits[to.x][to.y] = unitFrom;\n\t\tAPLeft--;\n\t}\n\n\tprivate void move(Unit unit, Position from, Position to) throws Exception {\n\t\tunits[from.x][from.y] = null;\n\t\tunits[to.x][to.y] = unit;\n\t\tAPLeft--;\n\t}\n\n\tprivate void equip(Card card, Position pos) {\n\t\tif (card == Card.REVIVE_POTION) {\n\t\t\tif (units[pos.x][pos.y].hp == 0)\n\t\t\t\tunits[pos.x][pos.y].heal(POTION_REVIVE);\n\t\t\telse\n\t\t\t\tunits[pos.x][pos.y].heal(POTION_HEAL);\n\t\t} else\n\t\t\tunits[pos.x][pos.y].equip(card, this);\n\t\tcurrentHand().remove(card);\n\t\tAPLeft--;\n\t}\n\n\tprivate void deploy(Card card, Position pos) {\n\t\tunits[pos.x][pos.y] = new Unit(card, p1Turn);\n\t\tcurrentHand().remove(card);\n\t\tAPLeft--;\n\t}\n\n\tprivate void endTurn() throws Exception {\n\t\tremoveDying(p1Turn);\n\t\tcheckWinOnUnits(1);\n\t\tcheckWinOnUnits(2);\n\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\tif (turn >= TURN_LIMIT)\n\t\t\tisTerminal = true;\n\t\tif (!isTerminal) {\n\t\t\tdrawCards();\n\t\t\tp1Turn = !p1Turn;\n\t\t\tdrawCards();\n\t\t\tAPLeft = ACTION_POINTS;\n\t\t\tturn++;\n\t\t}\n\t\t\n\t}\n\n\tpublic void dealCards() {\n\t\twhile (!legalStartingHand(p1Hand))\n\t\t\tdealCards(1);\n\n\t\twhile (!legalStartingHand(p2Hand))\n\t\t\tdealCards(2);\n\t}\n\n\tprivate void dealCards(int player) {\n\t\tif (player == 1) {\n\t\t\tp1Deck.addAll(p1Hand);\n\t\t\tp1Hand.clear();\n\t\t\t// Collections.shuffle(p1Deck);\n\t\t\tdrawHandFrom(p1Deck, p1Hand);\n\t\t} else if (player == 2) {\n\t\t\tp2Deck.addAll(p2Hand);\n\t\t\tp2Hand.clear();\n\t\t\t// Collections.shuffle(p2Hand);\n\t\t\tdrawHandFrom(p2Deck, p2Hand);\n\t\t}\n\n\t}\n\n\tprivate boolean legalStartingHand(CardSet hand) {\n\t\tif (hand.size != 6)\n\t\t\treturn false;\n\n\t\tif (hand.units() == REQUIRED_UNITS)\n\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate void drawHandFrom(CardSet deck, CardSet hand) {\n\n\t\tCard card = null;\n\t\twhile (!deck.isEmpty() && hand.size < 6) {\n\t\t\tif (RANDOMNESS)\n\t\t\t\tcard = deck.random();\n\t\t\telse\n\t\t\t\tcard = deck.determined();\n\t\t\thand.add(card);\n\t\t\tdeck.remove(card);\n\t\t}\n\n\t}\n\n\tprivate void drawCards() {\n\n\t\tdrawHandFrom(currentDeck(), currentHand());\n\n\t}\n\n\tpublic CardSet currentHand() {\n\t\tif (p1Turn)\n\t\t\treturn p1Hand;\n\t\treturn p2Hand;\n\t}\n\n\tpublic CardSet currentDeck() {\n\t\tif (p1Turn)\n\t\t\treturn p1Deck;\n\t\treturn p2Deck;\n\t}\n\n\tpublic void removeDying(boolean p1) throws Exception {\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null && units[x][y].p1Owner == p1\n\t\t\t\t\t\t&& units[x][y].hp == 0) {\n\t\t\t\t\tunits[x][y] = null;\n\t\t\t\t}\n\t}\n\n\tpublic GameState copy() {\n\t\tfinal Unit[][] un = new Unit[map.width][map.height];\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tun[x][y] = units[x][y].copy();\n\t\tfinal CardSet p1h = new CardSet(p1Hand.seed);\n\t\tp1h.imitate(p1Hand);\n\t\tfinal CardSet p2h = new CardSet(p2Hand.seed);\n\t\tp2h.imitate(p2Hand);\n\t\tfinal CardSet p1d = new CardSet(p1Deck.seed);\n\t\tp1d.imitate(p1Deck);\n\t\tfinal CardSet p2d = new CardSet(p2Deck.seed);\n\t\tp2d.imitate(p2Deck);\n\n\t\treturn new GameState(map, p1Turn, turn, APLeft, un, p1h, p2h, p1d, p2d,\n\t\t\t\tchainTargets, isTerminal);\n\t}\n\n\tpublic void imitate(GameState state) {\n\n\t\tmap = state.map;\n\t\tif (units.length != state.units.length\n\t\t\t\t|| (state.units.length > 0 && units[0].length != state.units[0].length))\n\t\t\tunits = new Unit[map.width][map.height];\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++) {\n\t\t\t\tif (units[x][y] != null) \n\t\t\t\t\tunits[x][y] = null;\n\t\t\t\tif (state.units[x][y] != null) {\n\t\t\t\t\tunits[x][y] = new Unit(null, false);\n\t\t\t\t\tunits[x][y].imitate(state.units[x][y]);\n\t\t\t\t}\n\t\t\t}\n\t\tp1Hand.imitate(state.p1Hand);\n\t\tp2Hand.imitate(state.p2Hand);\n\t\tp1Deck.imitate(state.p1Deck);\n\t\tp2Deck.imitate(state.p2Deck);\n\t\tisTerminal = state.isTerminal;\n\t\tp1Turn = state.p1Turn;\n\t\tturn = state.turn;\n\t\tAPLeft = state.APLeft;\n\t\tmap = state.map;\n\t\t// chainTargets.clear();\n\t\t// chainTargets.addAll(state.chainTargets); // NOT NECESSARY\n\n\t}\n\t\n\tpublic long simpleHash() {\n\t\tfinal int prime = 1193;\n\t\tlong result = 1;\n\t\tresult = prime * result + (isTerminal ? 0 : 1);\n\t\tresult = prime * result + p1Hand.hashCode();\n\t\tresult = prime * result + p2Deck.hashCode();\n\t\tresult = prime * result + p2Hand.hashCode();\n\t\tresult = prime * result + p1Deck.hashCode();\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tresult = prime * result + units[x][y].hash(x, y);\n\n\t\treturn result;\n\t}\n\n\tpublic long hash() {\n\t\tfinal int prime = 1193;\n\t\tlong result = 1;\n\t\tresult = prime * result + APLeft;\n\t\tresult = prime * result + turn;\n\t\tresult = prime * result + (isTerminal ? 0 : 1);\n\t\tresult = prime * result + p1Hand.hashCode();\n\t\tresult = prime * result + p2Deck.hashCode();\n\t\tresult = prime * result + p2Hand.hashCode();\n\t\tresult = prime * result + p1Deck.hashCode();\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tresult = prime * result + units[x][y].hash(x, y);\n\n\t\treturn result;\n\t}\n\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\tfinal GameState other = (GameState) obj;\n\t\tif (APLeft != other.APLeft)\n\t\t\treturn false;\n\t\tif (isTerminal != other.isTerminal)\n\t\t\treturn false;\n\t\tif (map == null) {\n\t\t\tif (other.map != null)\n\t\t\t\treturn false;\n\t\t} else if (!map.equals(other.map))\n\t\t\treturn false;\n\t\tif (p1Deck == null) {\n\t\t\tif (other.p1Deck != null)\n\t\t\t\treturn false;\n\t\t} else if (!p1Deck.equals(other.p1Deck))\n\t\t\treturn false;\n\t\tif (p1Hand == null) {\n\t\t\tif (other.p1Hand != null)\n\t\t\t\treturn false;\n\t\t} else if (!p1Hand.equals(other.p1Hand))\n\t\t\treturn false;\n\t\tif (p1Turn != other.p1Turn)\n\t\t\treturn false;\n\t\tif (p2Deck == null) {\n\t\t\tif (other.p2Deck != null)\n\t\t\t\treturn false;\n\t\t} else if (!p2Deck.equals(other.p2Deck))\n\t\t\treturn false;\n\t\tif (p2Hand == null) {\n\t\t\tif (other.p2Hand != null)\n\t\t\t\treturn false;\n\t\t} else if (!p2Hand.equals(other.p2Hand))\n\t\t\treturn false;\n\t\tif (!Arrays.deepEquals(units, other.units))\n\t\t\treturn false;\n\t\tif (turn != other.turn)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic void print() {\n\t\tfinal List<Unit> p1Units = new ArrayList<Unit>();\n\t\tfinal List<Unit> p2Units = new ArrayList<Unit>();\n\t\tfor (int y = 0; y < units[0].length; y++) {\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor (int x = 0; x < units.length; x++)\n\t\t\t\tif (units[x][y] == null)\n\t\t\t\t\tSystem.out.print(\"__|\");\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.print(units[x][y].unitClass.card.name()\n\t\t\t\t\t\t\t.substring(0, 2) + \"|\");\n\t\t\t\t\tif (units[x][y].p1Owner)\n\t\t\t\t\t\tp1Units.add(units[x][y]);\n\t\t\t\t\telse\n\t\t\t\t\t\tp2Units.add(units[x][y]);\n\t\t\t\t}\n\t\t\tSystem.out.print(\"\\n\");\n\t\t}\n\t\tSystem.out.println(p1Hand);\n\t\tfor (final Unit unit : p1Units)\n\t\t\tSystem.out.println(unit);\n\t\tSystem.out.println(p2Hand);\n\t\tfor (final Unit unit : p2Units)\n\t\t\tSystem.out.println(unit);\n\n\t}\n\n\tpublic SquareType squareAt(Position pos) {\n\t\treturn map.squares[pos.x][pos.y];\n\t}\n\n\tpublic Unit unitAt(Position pos) {\n\t\treturn units[pos.x][pos.y];\n\t}\n\n\tpublic Unit unitAt(int x, int y) {\n\t\treturn units[x][y];\n\t}\n\n\tpublic int cardsLeft(int p) {\n\t\tif (p == 1)\n\t\t\treturn p1Deck.size + p1Hand.size;\n\t\telse if (p == 2)\n\t\t\treturn p2Deck.size + p2Hand.size;\n\t\treturn -1;\n\t}\n\n\tpublic void returnUnits() {\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null) \n\t\t\t\t\tunits[x][y] = null;\n\t}\n\n\tpublic void hideCards(boolean p1) {\n\t\tif (p1){\n\t\t\tfor(Card card : Card.values())\n\t\t\t\tfor(int i = 0; i < p1Hand.count(card); i++)\n\t\t\t\t\tp1Deck.add(card);\n\t\t\tp1Hand.clear();\n\t\t} else {\n\t\t\tfor(Card card : Card.values())\n\t\t\t\tfor(int i = 0; i < p2Hand.count(card); i++)\n\t\t\t\t\tp2Deck.add(card);\n\t\t\tp2Hand.clear();\n\t\t}\n\t}\n\n}", "public class UnitClassLib {\n\n\tpublic static HashMap<Card, UnitClass> lib = new HashMap<Card, UnitClass>();\n\n\tstatic {\n\n\t\t// Add units\n\t\tlib.put(Card.KNIGHT, new UnitClass(Card.KNIGHT, 1000, 2, 200, 20, 0,\n\t\t\t\tnull, null, false));\n\t\tlib.put(Card.ARCHER, new UnitClass(Card.ARCHER, 800, 2, 300, 0, 0,\n\t\t\t\tnull, null, false));\n\t\tlib.put(Card.CLERIC, new UnitClass(Card.CLERIC, 800, 2, 200, 0, 0,\n\t\t\t\tnull, null, false));\n\t\tlib.put(Card.WIZARD, new UnitClass(Card.WIZARD, 800, 2, 200, 0, 10,\n\t\t\t\tnull, null, false));\n\t\tlib.put(Card.NINJA, new UnitClass(Card.NINJA, 800, 3, 200, 0, 0, null,\n\t\t\t\tnull, false));\n\n\t\t// Add crystal\n\t\tlib.put(Card.CRYSTAL, new UnitClass(Card.CRYSTAL, 4500, 0, 0, 0, 0,\n\t\t\t\tnull, null, false));\n\n\t\t// Add attacks\n\t\tlib.get(Card.KNIGHT).attack = new Attack(1, AttackType.Physical, 200,\n\t\t\t\t1, 1, false, true);\n\t\tlib.get(Card.ARCHER).attack = new Attack(3, AttackType.Physical, 300,\n\t\t\t\t0.5, 1, false, false);\n\t\tlib.get(Card.CLERIC).attack = new Attack(2, AttackType.Magical, 200, 1,\n\t\t\t\t1, false, false);\n\t\tlib.get(Card.WIZARD).attack = new Attack(2, AttackType.Magical, 200, 1,\n\t\t\t\t1, true, false);\n\t\tlib.get(Card.NINJA).attack = new Attack(2, AttackType.Physical, 200, 2,\n\t\t\t\t1, false, false);\n\n\t\t// Add heal\n\t\tlib.get(Card.CLERIC).heal = new Heal(2, 3, 2);\n\t\tlib.get(Card.NINJA).swap = true;\n\n\t}\n\n}", "public enum Card {\n\n\tKNIGHT(CardType.UNIT), \n\tARCHER(CardType.UNIT), \n\tCLERIC(CardType.UNIT), \n\tWIZARD(CardType.UNIT), \n\tNINJA(CardType.UNIT),\n\tINFERNO(CardType.SPELL), \n\tREVIVE_POTION(CardType.ITEM), \n\tRUNEMETAL(CardType.ITEM), \n\tSCROLL(CardType.ITEM), \n\tDRAGONSCALE(CardType.ITEM), \n\tSHINING_HELM(CardType.ITEM), \n\tCRYSTAL(CardType.UNIT);\n\t\n\tpublic final CardType type;\n\t\n\tCard(CardType type) {\n\t\tthis.type = type;\n\t}\n\t\n}", "public enum CardType {\n\tUNIT, \n\tITEM,\n\tSPELL;\n}", "public enum DECK_SIZE {\n\tSTANDARD, SMALL, TINY;\n}", "public class Position {\n\n\tpublic int x;\n\tpublic int y;\n\n\tpublic Position(int x, int y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic Position() {\n\t\tsuper();\n\t\tx = 0;\n\t\ty = 0;\n\t}\n\n\tpublic Direction getDirection(Position pos) {\n\t\tif (pos == null)\n\t\t\treturn null;\n\t\treturn Direction.direction(pos.x - x, pos.y - y);\n\t}\n\n\tpublic int hashCode() {\n\t\tint result = 1;\n\t\tresult = 5 * result + x;\n\t\tresult = 5 * result + y;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + x + \",\" + y + \")\";\n\t}\n\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\tfinal Position other = (Position) 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\n\tpublic int distance(Position to) {\n\t\tint xx = x - to.x;\n\t\tif (xx < 0)\n\t\t\txx = xx * (-1);\n\t\tint yy = y - to.y;\n\t\tif (yy < 0)\n\t\t\tyy = yy * (-1);\n\t\treturn xx + yy;\n\t}\n\n}" ]
import java.io.IOException; import java.util.HashMap; import java.util.Map; import util.MapLoader; import ai.util.NormUtil; import game.GameState; import libs.UnitClassLib; import model.Card; import model.CardType; import model.DECK_SIZE; import model.Position;
package ai.evaluation; public class MeanEvaluator implements IStateEvaluator { public static double MAX_UNIT_TINY = 0; public static double MAX_CRYSTAL_TINY = 0; public static double MAX_UNIT_SMALL = 0; public static double MAX_CRYSTAL_SMALL = 0; public static double MAX_UNIT_STANDARD = 0; public static double MAX_CRYSTAL_STANDARD = 0; private static Map<Card, Double> values; static { values = new HashMap<Card, Double>(); values.put(Card.ARCHER, 1.1); values.put(Card.CLERIC, 1.2); values.put(Card.DRAGONSCALE, .4); values.put(Card.INFERNO, 1.6); values.put(Card.KNIGHT, 1.0); values.put(Card.NINJA, 1.5); values.put(Card.REVIVE_POTION, .9); values.put(Card.RUNEMETAL, .4); values.put(Card.SCROLL, .9); values.put(Card.SHINING_HELM, .4); values.put(Card.WIZARD, 1.1); try { GameState tiny = new GameState(MapLoader.get("a-tiny"));
tiny.init(DECK_SIZE.TINY);
6
TomGrill/gdx-dialogs
ios/src/de/tomgrill/gdxdialogs/ios/IOSGDXDialogs.java
[ "public abstract class GDXDialogs {\n\n\tprotected ArrayMap<String, String> registeredDialogs = new ArrayMap<String, String>();\n\n\tpublic <T> T newDialog(Class<T> cls) {\n\t\tString className = cls.getName();\n\t\tif (registeredDialogs.containsKey(className)) {\n\n\t\t\ttry {\n\t\t\t\tfinal Class<T> dialogClazz = ClassReflection.forName(registeredDialogs.get(className));\n\n\t\t\t\tObject dialogObject = ClassReflection.getConstructor(dialogClazz).newInstance();\n\t\t\t\treturn (T) dialogObject;\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tthrow new RuntimeException(cls.getName() + \"is not registered.\");\n\t}\n\n\tpublic void registerDialog(String interfaceName, String clazzName) {\n\t\tregisteredDialogs.put(interfaceName, clazzName);\n\t}\n}", "public interface GDXButtonDialog {\n\n\t/**\n\t * Only on Android: When set true, user can click outside of the dialog and\n\t * the dialog will be closed. Has no effect on other operating systems.\n\t * \n\t * @param cancelable this value will be set to the corresponding android property if applicable.\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog setCancelable(boolean cancelable);\n\n\t/**\n\t * Shows the dialog. show() can only be called after build() has been called\n\t * else there might be strange behavior. You need to add at least one button\n\t * with addButton() before calling build(). Runs asynchronously on a different thread.\n\t * \n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog show();\n\n\t/**\n\t * Dismisses the dialog. You can show the dialog again.\n\t * \n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog dismiss();\n\n\t/**\n\t * Sets the {@link ButtonClickListener}\n\t * \n\t * @param listener listener to be called when the event is triggered\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog setClickListener(ButtonClickListener listener);\n\n\t/**\n\t * Add new button to the dialog. You need to add at least one button.\n\t * \n\t * @param label Text of the added new button.\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog addButton(CharSequence label);\n\n\t/**\n\t * This builds the button and prepares for usage. You need to add at least\n\t * one button with addButton() before calling build().\n\t * \n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog build();\n\n\t/**\n\t * Sets the message.\n\t * \n\t * @param message The text to be displayed at the body of the dialog.\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog setMessage(CharSequence message);\n\n\t/**\n\t * Sets the title\n\t * \n\t * @param title String value to set the title\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXButtonDialog setTitle(CharSequence title);\n}", "public interface GDXProgressDialog {\n\t/**\n\t * Sets the message.\n\t * \n\t * @param message The text to be displayed at the body of the dialog.\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXProgressDialog setMessage(CharSequence message);\n\n\t/**\n\t * Sets the title\n\t * \n\t * @param title String value to set the title\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXProgressDialog setTitle(CharSequence title);\n\n\t/**\n\t * Shows the dialog. show() can only be called after build() has been called\n\t * else there might be strange behavior. Runs asynchronously on a different thread.\n\t *\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXProgressDialog show();\n\n\t/**\n\t * Dismisses the dialog. You can show the dialog again.\n\t * \n\t * @return The same instance that the method was called from.\n\t */\n\tGDXProgressDialog dismiss();\n\n\t/**\n\t * This builds the button and prepares for usage.\n\t * \n\t * @return The same instance that the method was called from.\n\t */\n\tGDXProgressDialog build();\n\n}", "public interface GDXTextPrompt {\n\n\t/**\n\t * Type of input used by the textfield\n\t */\n\tenum InputType {\n\t\t/**\n\t\t * prints readable text\n\t\t */\n\t\tPLAIN_TEXT,\n\n\t\t/**\n\t\t * hides typed text behind specified character\n\t\t */\n\t\tPASSWORD\n\t}\n\n\t/**\n\t * Sets the title\n\t *\n\t * @param title String value to set the title\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setTitle(CharSequence title);\n\n\n\t/**\n\t * Set the character limit for input. Default is 16.\n\t *\n\t * @param maxLength\n\t * @return\n\t */\n\tGDXTextPrompt setMaxLength(int maxLength);\n\n\t/**\n\t * Shows the dialog. show() can only be called after build() has been called\n\t * else there might be strange behavior. Runs asynchronously on a different thread.\n\t *\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt show();\n\n\t/**\n\t * Dismisses the dialog. You can show the dialog again.\n\t *\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt dismiss();\n\n\t/**\n\t * This builds the button and prepares for usage.\n\t *\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt build();\n\n\t/**\n\t * Sets the message.\n\t *\n\t * @param message The text to be displayed at the body of the dialog. Desktop implementation will ignore this method.\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setMessage(CharSequence message);\n\n\t/**\n\t * Sets the default value for the input field.\n\t *\n\t * @param inputTip Placeholder for the text input field.\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setValue(CharSequence inputTip);\n\n\t/**\n\t * Sets the label for the cancel button on the dialog.\n\t *\n\t * @param label Text of the cancel button\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setCancelButtonLabel(CharSequence label);\n\n\t/**\n\t * Sets the label for the confirm button on the dialog.\n\t *\n\t * @param label Text of the confirm button\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setConfirmButtonLabel(CharSequence label);\n\n\t/**\n\t * Sets the {@link TextPromptListener}\n\t *\n\t * @param listener listener to be called when the event is triggered\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setTextPromptListener(TextPromptListener listener);\n\n\t/**\n\t * Sets the type of input for the text input field.\n\t *\n\t * @param inputType type of input\n\t * @return The same instance that the method was called from.\n\t */\n\tGDXTextPrompt setInputType(InputType inputType);\n}", "public class IOSGDXButtonDialog implements GDXButtonDialog {\n\n\tprivate UIAlertView alertView;\n\n\tprivate String title = \"\";\n\tprivate String message = \"\";\n\n\tprivate ButtonClickListener listener;\n\n\tprivate Array<CharSequence> labels = new Array<CharSequence>();\n\n\tpublic IOSGDXButtonDialog() {\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog setCancelable(boolean cancelable) {\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog show() {\n\t\tif (alertView == null) {\n\t\t\tthrow new RuntimeException(GDXButtonDialog.class.getSimpleName() + \" has not been build. Use build() before show().\");\n\t\t}\n\t\tGdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXButtonDialog.class.getSimpleName() + \" now shown.\");\n\t\talertView.show();\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog dismiss() {\n\t\tif (alertView == null) {\n\t\t\tthrow new RuntimeException(GDXButtonDialog.class.getSimpleName() + \" has not been build. Use build() before show().\");\n\t\t}\n\t\tGdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXButtonDialog.class.getSimpleName() + \" dismissed.\");\n\t\talertView.dismiss(-1, false);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog setClickListener(ButtonClickListener listener) {\n\t\tthis.listener = listener;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog addButton(CharSequence label) {\n\t\tif (labels.size >= 3) {\n\t\t\tthrow new RuntimeException(\"You can only have up to three buttons added.\");\n\t\t}\n\t\tlabels.add(label);\n\t\treturn this;\n\t}\n\n\tprivate void performClickOnButton(long buttonIndex) {\n\t\tif (listener != null) {\n\n\t\t\tint buttonNr = (int) buttonIndex;\n\n\t\t\t// swap first and second if we have 2 buttons\n\t\t\tif (labels.size == 2) {\n\t\t\t\tif (buttonIndex == 0) {\n\t\t\t\t\tbuttonNr = 1;\n\t\t\t\t} else {\n\t\t\t\t\tbuttonNr = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfinal int resultNr = buttonNr;\n\t\t\tGdx.app.postRunnable(new Runnable() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tlistener.click(resultNr);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog build() {\n\n\t\tUIAlertViewDelegateAdapter delegate = new UIAlertViewDelegateAdapter() {\n\n\t\t\t@Override\n\t\t\tpublic void didDismiss(UIAlertView alertView, long buttonIndex) {\n\t\t\t\tperformClickOnButton(buttonIndex);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void clicked(UIAlertView alertView, long buttonIndex) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void cancel(UIAlertView alertView) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void willPresent(UIAlertView alertView) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void didPresent(UIAlertView alertView) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void willDismiss(UIAlertView alertView, long buttonIndex) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean shouldEnableFirstOtherButton(UIAlertView alertView) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t};\n\n\t\tString[] otherButtons = new String[labels.size - 1];\n\n\t\tString firstButton = (String) labels.get(0);\n\n\t\tif (labels.size == 2) {\n\t\t\tfirstButton = (String) labels.get(1);\n\t\t\totherButtons[0] = (String) labels.get(0);\n\t\t}\n\n\t\tif (labels.size == 3) {\n\t\t\tfor (int i = 1; i < labels.size; i++) {\n\t\t\t\totherButtons[i - 1] = (String) labels.get(i);\n\t\t\t}\n\t\t}\n\n\t\talertView = new UIAlertView(title, message, delegate, firstButton, otherButtons);\n\n\t\t// alertView.setCancelButtonIndex(2);\n\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog setMessage(CharSequence message) {\n\t\tthis.message = (String) message;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXButtonDialog setTitle(CharSequence title) {\n\t\tthis.title = (String) title;\n\t\treturn this;\n\t}\n\n}", "public class IOSGDXProgressDialog implements GDXProgressDialog {\n\n\tprivate UIAlertView alertView;\n\tprivate UIActivityIndicatorView indicator;\n\n\tprivate String title = \"\";\n\tprivate String message = \"\";\n\n\tpublic IOSGDXProgressDialog() {\n\t}\n\n\t@Override\n\tpublic GDXProgressDialog setMessage(CharSequence message) {\n\t\tthis.message = (String) message;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXProgressDialog setTitle(CharSequence title) {\n\t\tthis.title = (String) title;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXProgressDialog show() {\n\t\tif (alertView == null) {\n\t\t\tthrow new RuntimeException(GDXProgressDialog.class.getSimpleName() + \" has not been build. Use build() before show().\");\n\t\t}\n\t\tGdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXProgressDialog.class.getSimpleName() + \" now shown.\");\n\t\talertView.show();\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXProgressDialog dismiss() {\n\t\tif (alertView == null) {\n\t\t\tthrow new RuntimeException(GDXProgressDialog.class.getSimpleName() + \" has not been build. Use build() before dismiss().\");\n\t\t}\n\t\tGdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXProgressDialog.class.getSimpleName() + \" dismissed.\");\n\t\talertView.dismiss(0, false);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic GDXProgressDialog build() {\n\t\tif (alertView == null) {\n\n\t\t\talertView = new UIAlertView();\n\n\t\t\talertView.setTitle(title);\n\t\t\talertView.setMessage(message);\n\n\t\t\t// CGSize screenSize =\n\t\t\t// UIScreen.getMainScreen().getBounds().getSize();\n\n\t\t\t// indicator = new\n\t\t\t// UIActivityIndicatorView(UIActivityIndicatorViewStyle.White);\n\t\t\t// indicator.setFrame(new CGRect(0.0, 0.0, 40.0, 40.0));\n\t\t\t//\n\t\t\t// indicator.setCenter(new CGPoint(screenSize.getWidth() / 2f - 20f,\n\t\t\t// screenSize.getWidth() / 2f - 50));\n\t\t\t// indicator.startAnimating();\n\t\t\t// alertView.addSubview(indicator);\n\t\t\t// indicator.release();\n\n\t\t}\n\n\t\treturn this;\n\t}\n\n}", "public class IOSGDXTextPrompt implements GDXTextPrompt {\n\n private String message = \"\";\n private String title = \"\";\n private String cancelLabel = \"\";\n private String confirmLabel = \"\";\n\n private TextPromptListener listener;\n\n private UIAlertView alertView;\n\n private int maxLength = 16;\n\n private UIAlertViewStyle inputType = UIAlertViewStyle.PlainTextInput;\n\n public IOSGDXTextPrompt() {\n }\n\n @Override\n public GDXTextPrompt show() {\n\n if (alertView == null) {\n throw new RuntimeException(GDXTextPrompt.class.getSimpleName() + \" has not been build. Use build() before show().\");\n }\n Gdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXTextPrompt.class.getSimpleName() + \" now shown.\");\n alertView.show();\n return this;\n }\n\n @Override\n public GDXTextPrompt build() {\n\n if (alertView != null) {\n alertView.dispose();\n }\n\n UIAlertViewDelegateAdapter delegate = new UIAlertViewDelegateAdapter() {\n\n @Override\n public void didDismiss(UIAlertView alertView, long buttonIndex) {\n if (listener != null) {\n if (buttonIndex == 0) {\n Gdx.app.postRunnable(new Runnable() {\n @Override\n public void run() {\n listener.cancel();\n }\n });\n }\n\n if (buttonIndex == 1) {\n UITextField textField = alertView.getTextField(0);\n final String result = textField.getText();\n Gdx.app.postRunnable(new Runnable() {\n @Override\n public void run() {\n listener.confirm(result);\n }\n });\n }\n }\n }\n\n @Override\n public void clicked(UIAlertView alertView, long buttonIndex) {\n\n }\n\n @Override\n public void cancel(UIAlertView alertView) {\n\n }\n\n @Override\n public void willPresent(UIAlertView alertView) {\n\n }\n\n @Override\n public void didPresent(UIAlertView alertView) {\n\n }\n\n @Override\n public void willDismiss(UIAlertView alertView, long buttonIndex) {\n\n }\n\n @Override\n public boolean shouldEnableFirstOtherButton(UIAlertView alertView) {\n return false;\n }\n\n };\n\n String[] otherButtons = new String[1];\n otherButtons[0] = confirmLabel;\n\n alertView = new UIAlertView(title, message, delegate, cancelLabel, otherButtons);\n\n alertView.setAlertViewStyle(inputType);\n\n UITextField uiTextField = alertView.getTextField(0);\n//\t\tfinal UITextFieldDelegate ud = uiTextField.getDelegate();\n\n uiTextField.setDelegate(new UITextFieldDelegateAdapter() {\n @Override\n public boolean shouldChangeCharacters(UITextField textField, @ByVal NSRange nsRange, String additionalText) {\n\n if (textField.getText().length() + additionalText.length() > maxLength) {\n String oldText = textField.getText();\n String newText = oldText + additionalText;\n textField.setText(newText.substring(0, maxLength));\n return false;\n }\n return true;\n }\n });\n\n\n return this;\n }\n\n @Override\n public GDXTextPrompt setTitle(CharSequence title) {\n this.title = (String) title;\n return this;\n }\n\n @Override\n public GDXTextPrompt setMaxLength(int maxLength) {\n if (maxLength < 1) {\n throw new RuntimeException(\"Char limit must be >= 1\");\n }\n this.maxLength = maxLength;\n return this;\n }\n\n @Override\n public GDXTextPrompt setMessage(CharSequence message) {\n this.message = (String) message;\n return this;\n }\n\n @Override\n public GDXTextPrompt setValue(CharSequence inputTip) {\n return this;\n }\n\n @Override\n public GDXTextPrompt setCancelButtonLabel(CharSequence label) {\n this.cancelLabel = (String) label;\n return this;\n }\n\n @Override\n public GDXTextPrompt setConfirmButtonLabel(CharSequence label) {\n this.confirmLabel = (String) label;\n return this;\n }\n\n @Override\n public GDXTextPrompt setTextPromptListener(TextPromptListener listener) {\n this.listener = listener;\n return this;\n }\n\n @Override\n public GDXTextPrompt setInputType(InputType inputType) {\n switch (inputType) {\n case PLAIN_TEXT:\n this.inputType = UIAlertViewStyle.PlainTextInput;\n break;\n\n case PASSWORD:\n this.inputType = UIAlertViewStyle.SecureTextInput;\n break;\n }\n return this;\n }\n\n @Override\n public GDXTextPrompt dismiss() {\n if (alertView == null) {\n throw new RuntimeException(GDXTextPrompt.class.getSimpleName() + \" has not been build. Use build() before dismiss().\");\n }\n Gdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXTextPrompt.class.getSimpleName() + \" dismissed.\");\n alertView.dismiss(0, false);\n return this;\n }\n\n}" ]
import de.tomgrill.gdxdialogs.core.GDXDialogs; import de.tomgrill.gdxdialogs.core.dialogs.GDXButtonDialog; import de.tomgrill.gdxdialogs.core.dialogs.GDXProgressDialog; import de.tomgrill.gdxdialogs.core.dialogs.GDXTextPrompt; import de.tomgrill.gdxdialogs.ios.dialogs.IOSGDXButtonDialog; import de.tomgrill.gdxdialogs.ios.dialogs.IOSGDXProgressDialog; import de.tomgrill.gdxdialogs.ios.dialogs.IOSGDXTextPrompt;
/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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 de.tomgrill.gdxdialogs.ios; public class IOSGDXDialogs extends GDXDialogs { public IOSGDXDialogs() { registerDialog(GDXButtonDialog.class.getName(), IOSGDXButtonDialog.class.getName()); registerDialog(GDXProgressDialog.class.getName(), IOSGDXProgressDialog.class.getName());
registerDialog(GDXTextPrompt.class.getName(), IOSGDXTextPrompt.class.getName());
6
cjdaly/fold
net.locosoft.fold.channel.vitals/src/net/locosoft/fold/channel/vitals/internal/VitalsPostHtml.java
[ "public interface IChannelInternal extends IChannel {\n\n\tIChannelService getChannelService();\n\n\tvoid init(String channelId, IChannelService channelService,\n\t\t\tString channelDescription);\n\n\tvoid init();\n\n\tvoid fini();\n\n\tboolean channelSecurity(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException;\n\n\tvoid channelHttp(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException;\n\n\tProperties getChannelConfigProperties(String propertiesFilePrefix);\n\n\tIProject getChannelProject();\n\n\tlong getChannelNodeId();\n}", "public class DynamicVitals extends AbstractVitals {\n\n\tprivate String _id;\n\n\tpublic DynamicVitals(String id) {\n\t\t_id = id;\n\t\taddVital(createCheckTimeVital());\n\t\taddVital(createIdVital());\n\t}\n\n\tpublic String getId() {\n\t\treturn _id;\n\t}\n\n\tprivate boolean isJsonNumberFloaty(String jsonNumber) {\n\t\treturn jsonNumber.contains(\".\") || jsonNumber.contains(\"e\")\n\t\t\t\t|| jsonNumber.contains(\"E\");\n\t}\n\n\tpublic void saveVitals(long vitalsItemNodeId, JsonObject vitalsJson) {\n\t\tlong checkTime = vitalsJson.getLong(IVitals.NODE_PROPERTY_CHECK_TIME,\n\t\t\t\tSystem.currentTimeMillis());\n\t\trecordVital(IVitals.NODE_PROPERTY_CHECK_TIME, checkTime);\n\t\trecordVital(IVitals.NODE_PROPERTY_ID, getId());\n\n\t\tList<String> names = vitalsJson.names();\n\t\tfor (String name : names) {\n\t\t\tif (IVitals.NODE_PROPERTY_CHECK_TIME.equals(name))\n\t\t\t\tcontinue;\n\t\t\tif (IVitals.NODE_PROPERTY_ID.equals(name))\n\t\t\t\tcontinue;\n\n\t\t\tJsonValue jsonValue = vitalsJson.get(name);\n\t\t\tif (jsonValue.isNumber()) {\n\t\t\t\tString value = jsonValue.toString();\n\t\t\t\tif (isJsonNumberFloaty(value)) {\n\t\t\t\t\taddAndRecordVital(name, \"double\", jsonValue);\n\t\t\t\t} else {\n\t\t\t\t\taddAndRecordVital(name, \"long\", jsonValue);\n\t\t\t\t}\n\t\t\t} else if (jsonValue.isBoolean()) {\n\t\t\t\taddAndRecordVital(name, \"boolean\", jsonValue);\n\t\t\t} else if (jsonValue.isString()) {\n\t\t\t\taddAndRecordVital(name, \"string\", jsonValue);\n\t\t\t}\n\t\t}\n\n\t\tMultiPropertyAccessNode sketch = new MultiPropertyAccessNode(\n\t\t\t\tvitalsItemNodeId);\n\t\tfor (Vital vital : getVitalsCollection()) {\n\t\t\tvital.addTo(sketch);\n\t\t}\n\t\tsketch.setProperties();\n\n\t\tIChannelService channelService = ChannelUtil.getChannelService();\n\t\tITimesChannel timesChannel = channelService\n\t\t\t\t.getChannel(ITimesChannel.class);\n\t\ttimesChannel.createTimesRef(checkTime, vitalsItemNodeId);\n\t}\n\n\tpublic void loadVitals(long vitalsNodeId) {\n\t\tHierarchyNode vitalsNode = new HierarchyNode(vitalsNodeId);\n\t\tlong[] subIds = vitalsNode.getSubIds();\n\t\tfor (long subId : subIds) {\n\t\t\tPropertyAccessNode props = new PropertyAccessNode(subId);\n\t\t\tString id = props.getStringValue(\"fold_Hierarchy_segment\");\n\t\t\tString datatype = props.getStringValue(\"datatype\");\n\t\t\tString units = props.getStringValue(\"units\");\n\t\t\tString name = props.getStringValue(\"name\");\n\t\t\tString description = props.getStringValue(\"description\");\n\t\t\tVital vital = new Vital(id, datatype, units, name, description,\n\t\t\t\t\tfalse);\n\t\t\taddVital(vital);\n\t\t}\n\t}\n\n}", "public interface IVitals {\n\n\tpublic static final String NODE_PROPERTY_ID = \"Vitals_id\";\n\tpublic static final String NODE_PROPERTY_CHECK_TIME = \"Vitals_checkTime\";\n\n\tString getId();\n\n\tVital getVital(String id);\n\n\tVital[] getVitals();\n\n\tVital[] getVitals(boolean includeInternal);\n\n}", "public abstract class AbstractChannelHtmlSketch extends AbstractHtmlSketch {\n\n\tprivate IChannelInternal _channel;\n\n\tpublic AbstractChannelHtmlSketch(IChannelInternal channel) {\n\t\t_channel = channel;\n\t}\n\n\tprotected IChannelInternal getChannel() {\n\t\treturn _channel;\n\t}\n\n}", "public class ChannelItemNode extends OrdinalNode {\n\n\tprivate String _itemLabel;\n\n\tpublic ChannelItemNode(IChannelInternal channel, String itemLabel) {\n\t\tsuper(channel.getChannelNodeId(), channel.getChannelId() + \"_\"\n\t\t\t\t+ itemLabel);\n\t\t_itemLabel = itemLabel;\n\t}\n\n\tpublic String getItemLabel() {\n\t\treturn _itemLabel;\n\t}\n\n}", "public class HierarchyNode extends AbstractNodeSketch {\n\n\tpublic HierarchyNode(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tpublic void setNodeId(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tpublic long getSupId() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sub)={subId}\" //\n\t\t\t\t+ \" RETURN ID(sup)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"subId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue != null)\n\t\t\treturn jsonValue.asLong();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tpublic JsonObject getSubNode(String segment) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId} AND sub.fold_Hierarchy_segment={segment}\" //\n\t\t\t\t+ \" RETURN sub\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tcypher.addParameter(\"segment\", segment);\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif ((jsonValue == null) || (!jsonValue.isObject()))\n\t\t\treturn null;\n\t\telse\n\t\t\treturn jsonValue.asObject();\n\t}\n\n\tpublic long getSubId(String segment, boolean createIfAbsent) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText;\n\t\tif (createIfAbsent) {\n\t\t\tcypherText = \"MATCH sup\" //\n\t\t\t\t\t+ \" WHERE id(sup)={supId}\" //\n\t\t\t\t\t+ \" CREATE UNIQUE (sup)-[:fold_Hierarchy]->\"\n\t\t\t\t\t+ \"(sub{ fold_Hierarchy_segment:{segment} }) \"\n\t\t\t\t\t+ \" RETURN ID(sub)\";\n\t\t} else {\n\t\t\tcypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t\t+ \" WHERE ID(sup)={supId} AND sub.fold_Hierarchy_segment={segment}\" //\n\t\t\t\t\t+ \" RETURN ID(sub)\";\n\t\t}\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tcypher.addParameter(\"segment\", segment);\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue != null)\n\t\t\treturn jsonValue.asLong();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tpublic long[] getSubIds() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId}\" //\n\t\t\t\t+ \" RETURN ID(sub)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tlong[] subIds = new long[cypher.getResultDataRowCount()];\n\t\tfor (int i = 0; i < cypher.getResultDataRowCount(); i++) {\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(i);\n\t\t\tsubIds[i] = jsonValue.asLong();\n\t\t}\n\t\treturn subIds;\n\t}\n\n\tpublic String[] getSubSegments() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId}\"\n\t\t\t\t+ \" RETURN sub.fold_Hierarchy_segment\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tString[] subSegments = new String[cypher.getResultDataRowCount()];\n\t\tfor (int i = 0; i < cypher.getResultDataRowCount(); i++) {\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(i);\n\t\t\tsubSegments[i] = jsonValue.asString();\n\t\t}\n\t\treturn subSegments;\n\t}\n\n\t// TODO:\n\t// public long[] getPathNodeIds(Path path) {\n\t//\n\t// }\n\t//\n\t// TODO:\n\t// public long getPathEndNodeId(Path path) {\n\t// return -1;\n\t// }\n\n}", "public class MultiPropertyAccessNode extends AbstractNodeSketch {\n\n\tprivate String _propertyNamePrefix;\n\n\tprivate ICypher _cypher;\n\tprivate StringBuilder _cypherStatement;\n\tprivate boolean _firstProperty;\n\n\tpublic MultiPropertyAccessNode(long nodeId) {\n\t\tthis(nodeId, \"\");\n\t}\n\n\tpublic MultiPropertyAccessNode(long nodeId, String propertyNamePrefix) {\n\t\t_nodeId = nodeId;\n\t\t_propertyNamePrefix = propertyNamePrefix == null ? \"\"\n\t\t\t\t: propertyNamePrefix;\n\t\treset();\n\t}\n\n\tpublic void reset() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\t_cypher = neo4jService.constructCypher(\"...placeholder...\");\n\t\t_cypherStatement = new StringBuilder(\n\t\t\t\t\"MATCH node WHERE id(node)={nodeId} SET \");\n\t\t_firstProperty = true;\n\t}\n\n\tpublic JsonObject getProperties() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH node\" //\n\t\t\t\t+ \" WHERE id(node)={nodeId}\" //\n\t\t\t\t+ \" RETURN node\";\n\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"nodeId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif ((jsonValue == null) || (!jsonValue.isObject()))\n\t\t\treturn null;\n\t\telse\n\t\t\treturn jsonValue.asObject();\n\t}\n\n\tprivate void addCypherSet(String name) {\n\t\tif (_firstProperty)\n\t\t\t_firstProperty = false;\n\t\telse\n\t\t\t_cypherStatement.append(\",\");\n\n\t\t_cypherStatement.append(\"node.`\" + _propertyNamePrefix + name + \"`={\"\n\t\t\t\t+ name + \"}\");\n\t}\n\n\tpublic void addProperty(String name, JsonValue value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void addProperty(String name, int value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void addProperty(String name, long value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void addProperty(String name, float value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void addProperty(String name, double value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void addProperty(String name, boolean value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void addProperty(String name, String value) {\n\t\taddCypherSet(name);\n\t\t_cypher.addParameter(name, value);\n\t}\n\n\tpublic void setProperties() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\t_cypher.addParameter(\"nodeId\", getNodeId());\n\t\t_cypher.setStatementText(_cypherStatement.toString());\n\t\tneo4jService.invokeCypher(_cypher);\n\t}\n}" ]
import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.locosoft.fold.channel.IChannelInternal; import net.locosoft.fold.channel.vitals.DynamicVitals; import net.locosoft.fold.channel.vitals.IVitals; import net.locosoft.fold.sketch.pad.html.AbstractChannelHtmlSketch; import net.locosoft.fold.sketch.pad.neo4j.ChannelItemNode; import net.locosoft.fold.sketch.pad.neo4j.HierarchyNode; import net.locosoft.fold.sketch.pad.neo4j.MultiPropertyAccessNode; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue;
/***************************************************************************** * Copyright (c) 2015 Chris J Daly (github user cjdaly) * 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: * cjdaly - initial API and implementation ****************************************************************************/ package net.locosoft.fold.channel.vitals.internal; public class VitalsPostHtml extends AbstractChannelHtmlSketch { public VitalsPostHtml(IChannelInternal channel) { super(channel); } public void postVitals(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonObject jsonObject = JsonObject.readFrom(request.getReader()); String vitalsId = jsonObject.getString(IVitals.NODE_PROPERTY_ID, null); if (vitalsId == null) { response.getWriter().println( "POST missing " + IVitals.NODE_PROPERTY_ID); return; } ChannelItemNode vitalsNode = new ChannelItemNode(getChannel(), "Vitals"); long vitalsItemNodeId = vitalsNode.nextOrdinalNodeId(); DynamicVitals vitals = new DynamicVitals(vitalsId); vitals.saveVitals(vitalsItemNodeId, jsonObject); response.getWriter().println( "Posted vitals: " + vitalsNode.getOrdinalIndex(vitalsItemNodeId)); } public void postVitalsDef(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonObject jsonObject = JsonObject.readFrom(request.getReader()); String vitalsId = jsonObject.getString(IVitals.NODE_PROPERTY_ID, null); if (vitalsId == null) { response.getWriter().println( "POST missing " + IVitals.NODE_PROPERTY_ID); return; } HierarchyNode channelNode = new HierarchyNode(getChannel() .getChannelNodeId()); long defsNodeId = channelNode.getSubId("defs", true); HierarchyNode defsNode = new HierarchyNode(defsNodeId); long vitalsNodeId = defsNode.getSubId(vitalsId, true); HierarchyNode vitalsNode = new HierarchyNode(vitalsNodeId); JsonValue vitalsJsonValue = jsonObject.get("Vitals"); if ((vitalsJsonValue == null) || !vitalsJsonValue.isObject()) { response.getWriter().println("POST missing Vitals defs"); return; } JsonObject vitalsJson = vitalsJsonValue.asObject(); List<String> names = vitalsJson.names(); for (String name : names) { JsonValue jsonValue = vitalsJson.get(name); if (!jsonValue.isObject()) continue; JsonObject vitalDef = jsonValue.asObject(); long subId = vitalsNode.getSubId(name, true);
MultiPropertyAccessNode props = new MultiPropertyAccessNode(subId);
6
engswee/equalize-xpi-modules
com.equalize.xpi.af.modules.ejb/ejbModule/com/equalize/xpi/af/modules/json/XML2JSONConverter.java
[ "public abstract class AbstractModuleConverter {\n\tprotected final Message msg;\n\tprotected final XMLPayload payload;\n\tprotected final AuditLogHelper audit;\n\tprotected final ParameterHelper param;\n\tprotected final DynamicConfigurationHelper dyncfg;\n\tprotected final boolean debug;\n\t\n\tpublic AbstractModuleConverter (Message msg, ParameterHelper param, AuditLogHelper audit, DynamicConfigurationHelper dyncfg, Boolean debug) {\n\t\tthis.msg = msg;\n\t\tthis.payload = this.msg.getDocument();\n\t\tthis.param = param;\n\t\tthis.dyncfg = dyncfg;\n\t\tthis.audit = audit;\t\n\t\tthis.debug = debug;\n\t}\n\t\n\tpublic abstract void retrieveModuleParameters() throws ModuleException;\n\n\tpublic abstract void parseInput() throws ModuleException;\n\n\tpublic abstract byte[] generateOutput() throws ModuleException;\n}", "public class AuditLogHelper {\n\n\tprivate final MessageKey msgkey;\n\tprivate AuditAccess audit;\n\t\n\tpublic AuditLogHelper (Message msg){\n\t\t// Get audit log\n\t\tthis.msgkey = new MessageKey(msg.getMessageId(), msg.getMessageDirection());\n\t\ttry {\n\t\t\tthis.audit = PublicAPIAccessFactory.getPublicAPIAccess().getAuditAccess();\t\t\t\t\t\t\n\t\t} catch (MessagingException e) {\n\t\t\tthis.audit = null;\n\t\t\tSystem.out.println(\"WARNING: Audit log not available in standalone testing\");\n\t\t}\n\t}\n\n\tpublic void addLog (AuditLogStatus status, String message) {\n\t\tif (this.audit != null) {\n\t\t\tthis.audit.addAuditLogEntry(this.msgkey, status, message);\t\n\t\t} else {\n\t\t\tSystem.out.println( \"Audit Log: \" + message);\n\t\t}\n\t}\n\n}", "public class DynamicConfigurationHelper {\n\n\tprivate final Message msg;\n\t\n\tpublic DynamicConfigurationHelper (Message msg) {\n\t\tthis.msg = msg;\n\t}\n\n\tpublic String get(String namespace, String attribute) {\n\t\tMessagePropertyKey mpk = new MessagePropertyKey(attribute, namespace);\n\t\treturn this.msg.getMessageProperty(mpk);\t\t\n\t}\n\n\tpublic void add(String namespace, String attribute, String value) throws InvalidParamException {\n\t\tMessagePropertyKey mpk = new MessagePropertyKey(attribute, namespace);\n\t\tthis.msg.setMessageProperty(mpk, value );\n\t}\n\n\tpublic void change(String namespace, String attribute, String value) throws InvalidParamException {\n\t\tMessagePropertyKey mpk = new MessagePropertyKey(attribute, namespace);\n\t\tthis.msg.removeMessageProperty(mpk);\n\t\tthis.msg.setMessageProperty(mpk, value);\n\t}\n\n\tpublic void delete(String namespace, String attribute) {\n\t\tMessagePropertyKey mpk = new MessagePropertyKey(attribute, namespace);\n\t\tthis.msg.removeMessageProperty(mpk);\n\t}\n}", "public class ParameterHelper {\n\n\tprivate final ModuleContext mc;\n\tprivate final AuditLogHelper audit;\n\n\tpublic ParameterHelper (ModuleContext mc, AuditLogHelper audit) {\n\t\tthis.mc = mc;\n\t\tthis.audit = audit;\n\t}\n\n\tpublic String getMandatoryParameter(String paramName) throws ModuleException {\n\t\tString paramValue = this.mc.getContextData(paramName);\n\t\tif (paramValue == null) {\n\t\t\tthrow new ModuleException(\"Mandatory parameter '\" + paramName + \"' is missing\");\n\t\t}\t\n\t\treturn paramValue;\n\t}\n\n\tpublic String getParameter(String paramName, String defaultValue, boolean outputLog) {\n\t\tString paramValue = this.mc.getContextData(paramName);\n\t\tif (paramValue == null && defaultValue != null) {\n\t\t\tparamValue = defaultValue;\n\t\t\tif(outputLog) {\n\t\t\t\tthis.audit.addLog(AuditLogStatus.SUCCESS, \"Parameter '\" + paramName + \"' is not set. Using default value = '\" + paramValue + \"'\");\n\t\t\t}\n\t\t}\t\n\t\treturn paramValue;\n\t}\n\n\tpublic String getConditionallyMandatoryParameter(String paramName, String dependentParamName, String dependentParamValue) throws ModuleException {\n\t\tString paramValue = this.mc.getContextData(paramName);\n\t\tif (paramValue == null) {\n\t\t\tthrow new ModuleException(\"Parameter '\" + paramName + \"' required when '\" + dependentParamName + \"' = \" + dependentParamValue);\n\t\t}\t\n\t\treturn paramValue;\n\t}\n\n\tpublic String getParameter(String paramName) {\n\t\treturn getParameter(paramName, null, false);\n\t}\n\n\tpublic int getIntParameter(String paramName, int defaultValue, boolean outputLog) throws ModuleException {\n\t\tString paramValue = getParameter(paramName, Integer.toString(defaultValue), outputLog);\n\t\ttry {\n\t\t\tint result = Integer.parseInt(paramValue);\n\t\t\tif (result < 0) {\n\t\t\t\tthrow new ModuleException(\"Negative integers not allowed for \"+ paramName);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new ModuleException(\"Only integers allowed for \"+ paramName);\n\t\t}\n\t}\n\n\tpublic int getIntParameter(String paramName) throws ModuleException {\n\t\treturn getIntParameter(paramName, 0, false);\n\t}\n\n\tpublic int getIntMandatoryParameter(String paramName) throws ModuleException {\n\t\tgetMandatoryParameter(paramName);\n\t\treturn getIntParameter(paramName);\n\t}\n\n\tpublic boolean getBoolParameter(String paramName, String defaultValue, boolean outputLog) throws ModuleException {\n\t\tString paramValue = getParameter(paramName, defaultValue, outputLog);\n\t\tif(paramValue.equalsIgnoreCase(\"Y\")) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean getBoolParameter(String paramName) throws ModuleException {\n\t\treturn getBoolParameter(paramName, \"N\", false);\n\t}\n\n\tpublic boolean getBoolMandatoryParameter(String paramName) throws ModuleException {\n\t\tgetMandatoryParameter(paramName);\n\t\treturn getBoolParameter(paramName);\n\t}\n\n\tpublic void checkParamValidValues(String paramName, String validValues) throws ModuleException {\n\t\tString paramValue = this.mc.getContextData(paramName);\n\t\tif(paramValue != null) {\n\t\t\tString[] valid = validValues.split(\",\");\n\t\t\tboolean found = false;\n\t\t\tfor (int i = 0 ; i < valid.length ; i++) {\n\t\t\t\tif (valid[i].trim().equalsIgnoreCase(paramValue)) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\tthrow new ModuleException(\"Value '\" + paramValue + \"' not valid for parameter \" + paramName);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic ModuleContext getModuleContext() {\n\t\treturn this.mc;\n\t}\n}", "public class ConversionDOMInput {\n\tprivate final Document doc;\n\tprivate XPathFactory xpathFac;\n\n\tpublic ConversionDOMInput(InputStream inStream) throws ParserConfigurationException, SAXException, IOException {\n\t\tDocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n\t\tthis.doc = docBuilder.parse(inStream);\n\t}\n\n\tpublic ConversionDOMInput(String string, String encoding) throws ParserConfigurationException, SAXException, IOException {\n\t\tthis(Converter.toInputStream(string, encoding));\n\t}\n\n\tpublic ConversionDOMInput(String string) throws ParserConfigurationException, SAXException, IOException {\n\t\tthis(Converter.toInputStream(string));\n\t}\n\n\tpublic ConversionDOMInput(byte[] inputBytes) throws ParserConfigurationException, SAXException, IOException {\n\t\tthis(Converter.toInputStream(inputBytes));\n\t}\n\n\tpublic Document getDocument() {\n\t\treturn this.doc;\n\t}\n\n\tpublic XMLElementContainer extractDOMContent() {\n\t\tNode root = this.doc.getDocumentElement();\n\t\tXMLElementContainer rootElement = (XMLElementContainer) parseNode(root);\n\t\treturn rootElement;\n\t}\n\n\tpublic Node evaluateXPathToNode(String xpath) throws XPathExpressionException {\n\t\tif(this.xpathFac == null) {\n\t\t\tthis.xpathFac = XPathFactory.newInstance();\n\t\t}\n\t\tXPath xp = this.xpathFac.newXPath();\n\t\tXPathExpression xpe = xp.compile(xpath);\n\t\treturn (Node) xpe.evaluate(this.doc, XPathConstants.NODE);\n\t}\n\n\tpublic String evaluateXPathToString(String xpath) throws XPathExpressionException {\n\t\tNode node = evaluateXPathToNode(xpath);\t\t\t\t\n\t\tif(node == null) {\n\t\t\tthrow new XPathExpressionException(\"XPath \" + xpath + \" does not exist\");\n\t\t}\n\t\treturn node.getTextContent();\n\t}\n\n\tprivate Object parseNode(Node node) {\n\t\tboolean hasChildElements = false;\n\t\tString textContent = \"\";\n\n\t\t// Recursively parse the children nodes\n\t\tXMLElementContainer element = new XMLElementContainer(node.getNodeName());\n\t\tNodeList nl = node.getChildNodes();\n\t\tfor (int i = 0; i < nl.getLength(); i++) {\n\t\t\tNode child = nl.item(i);\n\t\t\tswitch(child.getNodeType()) {\n\t\t\t\tcase Node.ELEMENT_NODE:\n\t\t\t\t\thasChildElements = true;\n\t\t\t\t\telement.addChildField(child.getNodeName(), parseNode(child));\n\t\t\t\t\tbreak;\n\t\t\t\tcase Node.TEXT_NODE:\n\t\t\t\t\ttextContent = child.getNodeValue();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t\t// If an element node has no further child element nodes, then it is a leaf node\n\t\t// If it has child text node, then it should extract that text node\n\t\tif(!hasChildElements)\t\t\t\n\t\t\treturn textContent.trim();\t\t\n\t\telse\n\t\t\treturn element;\n\t}\n\n\t/*\tpublic static String getTextOfChildElement (Node parentNode, String elementName) {\n\t\tNodeList nl = parentNode.getChildNodes();\n\t\tString elementTextValue = \"\";\n\t\tfor (int i = 0; i < nl.getLength(); i++) {\t\t\t\n\t\t\tif (nl.item(i).getNodeName().equals(elementName)) {\n\t\t\t\telementTextValue = nl.item(i).getFirstChild().getNodeValue();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn elementTextValue;\n\t}\n\n\tpublic static ArrayList<Node> getMatchingChildNodes ( Node parentNode, String childName ) {\n\t\tArrayList<Node> childNodes = new ArrayList<Node>(10);\n\t\tNodeList nl = parentNode.getChildNodes();\n\t\tfor ( int i = 0; i < nl.getLength(); i++) {\n\t\t\tif ( nl.item(i).getNodeName().equals(childName)) {\n\t\t\t\tchildNodes.add(nl.item(i));\n\t\t\t}\n\t\t}\n\t\treturn childNodes;\n\t}*/\n}", "public class ConversionJSONOutput {\n\n\tprivate boolean forceArray = false;\n\tprivate HashSet<String> arrayFields;\n\t\n\tpublic String generateJSONText(XMLElementContainer xmlElement, boolean skipRoot, int indentFactor) {\n\t\tJSONObject jo = new JSONObject();\n\t\tconstructJSONContentfromXML(jo, xmlElement);\n\t\tif (skipRoot) {\n\t\t\treturn getJSONText(jo, indentFactor);\n\t\t} else {\n\t\t\tJSONObject rootjo = new JSONObject();\n\t\t\trootjo.put(xmlElement.getElementName(), jo);\n\t\t\treturn getJSONText(rootjo, indentFactor);\n\t\t}\n\t}\n\n\tpublic String generateJSONText(XMLElementContainer element, boolean skipRoot) {\t\t\n\t\treturn generateJSONText(element, skipRoot, 0);\n\t}\n\n\tpublic ByteArrayOutputStream generateJSONOutputStream(XMLElementContainer element, boolean skipRoot, int indentFactor) throws IOException {\n\t\tString output = generateJSONText(element, skipRoot, indentFactor);\n\t\treturn Converter.toBAOS(output);\n\t}\n\n\tpublic ByteArrayOutputStream generateJSONOutputStream(XMLElementContainer element, boolean skipRoot) throws IOException {\n\t\treturn generateJSONOutputStream(element, skipRoot, 0);\n\t}\n\t\n\tpublic void setForceArray(boolean forceArray) {\n\t\tthis.forceArray = forceArray;\n\t}\n\n\tpublic void setArrayFields(HashSet<String> arrayFields) {\n\t\tthis.arrayFields = arrayFields;\n\t}\n\n\tprivate void constructJSONContentfromXML(JSONObject parent, XMLElementContainer element) {\n\t\tLinkedHashMap<String, JSONArray> map = new LinkedHashMap<String, JSONArray>();\n\t\t// Process all the child fields of the XML element\n\t\tfor (Field childField : element.getChildFields()) {\n\t\t\t// Check if it is an array first\n\t\t\tint count = element.getChildFieldList().get(childField.fieldName);\n\n\t\t\tObject fieldContent = childField.fieldContent;\t\t\t\n\t\t\tif(fieldContent instanceof XMLElementContainer) {\n\t\t\t\t// If it is a segment, create a JSON object for it first before adding into parent\n\t\t\t\tJSONObject childjo = new JSONObject();\n\t\t\t\tconstructJSONContentfromXML(childjo, (XMLElementContainer) fieldContent);\n\t\t\t\tputObjectIntoJSONObject(count, map, parent, childField.fieldName, childjo);\n\t\t\t} else if (fieldContent instanceof String) {\n\t\t\t\t// If it is a string, directly add it to parent\n\t\t\t\tputObjectIntoJSONObject(count, map, parent, childField.fieldName, fieldContent);\n\t\t\t}\n\t\t\t// If a JSONArray is created for this field and hasn't been added to the parent,\n\t\t\t// then add the JSONArray to the parent\n\t\t\tif(map.containsKey(childField.fieldName) && !parent.has(childField.fieldName)) {\n\t\t\t\tparent.put(childField.fieldName, map.get(childField.fieldName));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void putObjectIntoJSONObject(int fieldCount, LinkedHashMap<String, JSONArray> jsonArrMap, JSONObject parent, String fieldName, Object child) {\n\t\t// If it is an array, put it into the corresponding JSON array in the map\t\t\n\t\tif (fieldCount > 1 || \n\t\t this.forceArray || \n\t\t\t(this.arrayFields != null && this.arrayFields.contains(fieldName)) ) {\n\t\t\tJSONArray ja = getJSONArray(jsonArrMap, fieldName); \n\t\t\tja.put(child);\n\t\t} else {\n\t\t\t// Otherwise directly put it into the parent\n\t\t\tparent.put(fieldName, child);\n\t\t}\n\t}\n\n\tprivate String getJSONText(JSONObject jo, int indentFactor) {\n\t\treturn jo.toString(indentFactor);\n\t}\n\n\tprivate JSONArray getJSONArray(LinkedHashMap<String, JSONArray> map, String arrayName) {\n\t\t// Get the current JSONArray for this key or create a new JSONArray\n\t\tif(map.containsKey(arrayName)) {\n\t\t\treturn map.get(arrayName);\n\t\t} else {\n\t\t\tJSONArray ja = new JSONArray();\n\t\t\tmap.put(arrayName, ja);\n\t\t\treturn ja;\n\t\t}\n\t}\n}", "public class XMLElementContainer {\n\n\tprivate final String elementName;\n\tprivate final LinkedHashMap<String, Integer> childFieldList;\n\tprivate final ArrayList<Field> childFields;\n\t\n\tpublic XMLElementContainer(String elementName) {\n\t\tthis.childFieldList = new LinkedHashMap<String, Integer>();\n\t\tthis.childFields = new ArrayList<Field>();\n\t\tthis.elementName = elementName;\n\t}\n\n\tpublic String getElementName() {\n\t\treturn this.elementName;\n\t}\t\n\t\n\tpublic LinkedHashMap<String, Integer> getChildFieldList() {\n\t\treturn this.childFieldList;\n\t}\n\n\tpublic ArrayList<Field> getChildFields() {\n\t\treturn this.childFields;\n\t}\n\t\n\tpublic void addChildField(String fieldName, Object fieldContent) {\n\t\t// Add field\t\n\t\tthis.childFields.add(new Field(fieldName, fieldContent));\n\t\t// Update count of field in list\n\t\tint count;\n\t\tif (this.childFieldList.containsKey(fieldName)) {\n\t\t\tcount = this.childFieldList.get(fieldName);\n\t\t\tcount++;\n\t\t} else {\n\t\t\tcount = 1;\n\t\t}\n\t\tthis.childFieldList.put(fieldName, count);\n\t}\n}" ]
import java.util.HashSet; import com.equalize.xpi.af.modules.util.AbstractModuleConverter; import com.equalize.xpi.af.modules.util.AuditLogHelper; import com.equalize.xpi.af.modules.util.DynamicConfigurationHelper; import com.equalize.xpi.af.modules.util.ParameterHelper; import com.equalize.xpi.util.converter.ConversionDOMInput; import com.equalize.xpi.util.converter.ConversionJSONOutput; import com.equalize.xpi.util.converter.XMLElementContainer; import com.sap.aii.af.lib.mp.module.ModuleException; import com.sap.engine.interfaces.messaging.api.Message; import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus;
package com.equalize.xpi.af.modules.json; public class XML2JSONConverter extends AbstractModuleConverter { private ConversionDOMInput domIn; private ConversionJSONOutput jsonOut; private XMLElementContainer rootXML; private int indentFactor; private boolean skipRootNode; private boolean forceArrayAll; private HashSet<String> arrayFields;
public XML2JSONConverter(Message msg, ParameterHelper param, AuditLogHelper audit, DynamicConfigurationHelper dyncfg, Boolean debug) {
3
alphagov/locate-api
locate-api-service/src/test/uk/gov/gds/locate/api/resources/AddressResourceTest.java
[ "@Provider\n@Produces(MediaType.APPLICATION_JSON)\npublic class LocateExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Throwable> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(LocateExceptionMapper.class);\n\n protected static final String CONTENT_TYPE = \"application/json; charset=utf-8\";\n protected static final String CONTENT_TYPE_HEADER = \"Content-Type\";\n\n @Override\n public Response toResponse(Throwable exception) {\n\n if (exception instanceof LocateWebException) {\n LOGGER.error(\"WebApplicationException\", exception);\n return ((LocateWebException) exception).getResponse();\n }\n\n LOGGER.error(\"Server Error\", exception);\n\n return Response.status(\n Response.Status.fromStatusCode(500))\n .header(CONTENT_TYPE_HEADER, CONTENT_TYPE)\n .entity(\"{ \\\"error\\\" : \\\"Internal Server Error\\\" }\")\n .build();\n }\n}", "public class BearerTokenAuthProvider implements InjectableProvider<Auth, Parameter> {\n\n private final LocateApiConfiguration configuration;\n private final UsageDao usageDao;\n private final Authenticator<String, AuthorizationToken> authenticator;\n\n\n public BearerTokenAuthProvider(LocateApiConfiguration configuration, UsageDao usageDao, Authenticator<String, AuthorizationToken> bearerTokenAuthenticator) {\n this.configuration = configuration;\n this.usageDao = usageDao;\n this.authenticator = bearerTokenAuthenticator;\n }\n\n @Override\n public ComponentScope getScope() {\n return ComponentScope.PerRequest;\n }\n\n @Override\n public Injectable<?> getInjectable(ComponentContext ic, Auth a, Parameter c) {\n return new BearerTokenAuthInjectable(configuration, authenticator, usageDao);\n }\n}", "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class LocateApiConfiguration extends Configuration {\n\n @Valid\n @NotNull\n @JsonProperty\n private MongoConfiguration mongoConfiguration = new MongoConfiguration();\n\n @Valid\n @NotNull\n @JsonProperty\n private Integer maxRequestsPerDay;\n\n @Valid\n @NotNull\n @JsonProperty\n private String encryptionKey;\n\n @Valid\n @NotNull\n @JsonProperty\n private Boolean encrypted;\n\n @Valid\n @NotNull\n @JsonProperty\n private String allowedOrigins;\n\n public MongoConfiguration getMongoConfiguration() {\n return mongoConfiguration;\n }\n\n public Integer getMaxRequestsPerDay() {\n return maxRequestsPerDay;\n }\n\n public String getEncryptionKey() {\n return encryptionKey;\n }\n\n public Boolean getEncrypted() {\n return encrypted;\n }\n\n public String getAllowedOrigins() {\n return allowedOrigins;\n }\n\n @Override\n public String toString() {\n return \"LocateApiConfiguration{\" +\n \"mongoConfiguration=\" + mongoConfiguration +\n \", maxRequestsPerDay=\" + maxRequestsPerDay +\n \", encryptionKey='\" + encryptionKey + '\\'' +\n \", encrypted=\" + encrypted +\n \", allowedOrigins='\" + allowedOrigins + '\\'' +\n '}';\n }\n}", "public class AddressDao {\n\n private final JacksonDBCollection<Address, String> addresses;\n\n public AddressDao(JacksonDBCollection<Address, String> addresses) {\n this.addresses = addresses;\n }\n\n @Timed\n public List<Address> findAllForPostcode(String postcode) {\n return addresses.find().is(\"postcode\", postcode).toArray();\n }\n}", "public class UsageDao {\n\n private final JacksonDBCollection<Usage, String> collection;\n\n public UsageDao(JacksonDBCollection<Usage, String> collection) {\n this.collection = collection;\n }\n\n @Timed\n public Optional<Usage> findUsageByIdentifier(String identifier) {\n return Optional.fromNullable(collection.findAndModify(new BasicDBObject(\"identifier\", identifier), new DBUpdate.Builder().inc(\"count\")));\n }\n\n @Timed\n public Boolean create(String identifier) {\n Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate();\n return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1;\n }\n\n @Timed\n public void applyIndexes() {\n collection.ensureIndex(new BasicDBObject(\"identifier\", 1), \"identifier_index\", true);\n collection.ensureIndex(new BasicDBObject(\"expireAt\", 1), new BasicDBObject(\"expireAfterSeconds\", 0));\n }\n}", "public class DetailsBuilder {\n private Date blpuCreatedAt;\n private Date blpuUpdatedAt;\n private String classification;\n private String state;\n private Boolean isPostalAddress;\n private Boolean isCommercial;\n private Boolean isResidential;\n private Boolean isHigherEducational;\n private Boolean isElectoral;\n private String usrn;\n private String file;\n private String primaryClassification;\n private String secondaryClassification;\n\n public DetailsBuilder(String suffix) {\n isPostalAddress = false;\n isCommercial = false;\n isResidential = false;\n isHigherEducational = false;\n isElectoral = false;\n blpuCreatedAt = new Date();\n blpuUpdatedAt = new Date();\n classification = \"classification-\" + suffix;\n state = \"state-\" + suffix;\n usrn = \"usrn-\" + suffix;\n file = \"file-\" + suffix;\n primaryClassification = \"primaryClassification-\" + suffix;\n secondaryClassification = \"secondaryClassification-\" + suffix;\n }\n\n public DetailsBuilder postal(Boolean isPostalAddress) {\n this.isPostalAddress = isPostalAddress;\n return this;\n }\n\n public DetailsBuilder residential(Boolean isResidential) {\n this.isResidential = isResidential;\n return this;\n }\n\n public DetailsBuilder commercial(Boolean isCommercial) {\n this.isCommercial = isCommercial;\n return this;\n }\n\n public DetailsBuilder electoral(Boolean isElectoral) {\n this.isElectoral = isElectoral;\n return this;\n }\n\n public DetailsBuilder higherEducational(Boolean isHigherEducational) {\n this.isHigherEducational = isHigherEducational;\n return this;\n }\n\n public Details build() {\n return new Details(blpuCreatedAt, blpuUpdatedAt, classification, state, isPostalAddress, isCommercial, isResidential, isHigherEducational, isElectoral, usrn, file, primaryClassification, secondaryClassification);\n }\n}", "public class OrderingBuilder {\n\n private Integer saoStartNumber;\n private String saoStartSuffix;\n private Integer saoEndNumber;\n private String saoEndSuffix;\n private Integer paoStartNumber;\n private String paoStartSuffix;\n private Integer paoEndNumber;\n private String paoEndSuffix;\n private String paoText;\n private String saoText;\n private String street;\n\n\n public OrderingBuilder() {\n this.saoStartNumber = null;\n this.saoStartSuffix = null;\n this.saoEndNumber = null;\n this.saoEndSuffix = null;\n this.paoStartNumber = null;\n this.paoStartSuffix = null;\n this.paoEndNumber = null;\n this.paoEndSuffix = null;\n this.paoText = null;\n this.saoText = null;\n this.street = null;\n }\n\n public OrderingBuilder saoStartNumber(Integer i) {\n this.saoStartNumber = i;\n return this;\n }\n\n public OrderingBuilder saoStartSuffix(String i) {\n this.saoStartSuffix = i;\n return this;\n }\n\n public OrderingBuilder saoEndNumber(Integer i) {\n this.saoEndNumber = i;\n return this;\n }\n\n public OrderingBuilder saoEndSuffix(String i) {\n this.saoEndSuffix = i;\n return this;\n }\n\n public OrderingBuilder paoStartNumber(Integer i) {\n this.paoStartNumber = i;\n return this;\n }\n\n public OrderingBuilder paoStartSuffix(String i) {\n this.paoStartSuffix = i;\n return this;\n }\n\n public OrderingBuilder paoEndNumber(Integer i) {\n this.paoEndNumber = i;\n return this;\n }\n\n public OrderingBuilder paoEndSuffix(String i) {\n this.paoEndSuffix = i;\n return this;\n }\n\n public OrderingBuilder paoText(String i) {\n this.paoText = i;\n return this;\n }\n\n public OrderingBuilder saoText(String i) {\n this.saoText = i;\n return this;\n }\n\n public OrderingBuilder street(String i) {\n this.street = i;\n return this;\n }\n\n public Ordering build() {\n return new Ordering(\n this.saoStartNumber,\n this.saoStartSuffix,\n this.saoEndNumber,\n this.saoEndSuffix,\n this.paoStartNumber,\n this.paoStartSuffix,\n this.paoEndNumber,\n this.paoEndSuffix,\n this.paoText,\n this.saoText,\n this.street\n );\n }\n}", "public class PresentationBuilder {\n\n private String property;\n private String street;\n private String locality;\n private String town;\n private String area;\n private String postcode;\n\n public PresentationBuilder(String suffix) {\n this.property = \"property-\" + suffix;\n this.street = \"street-\" + suffix;\n this.locality = \"locality-\" + suffix;\n this.town = \"town-\" + suffix;\n this.area = \"area-\" + suffix;\n this.postcode = \"postcode-\" + suffix;\n }\n\n public PresentationBuilder property(String p) {\n this.property = p;\n return this;\n }\n\n public PresentationBuilder street(String p) {\n this.street = p;\n return this;\n }\n\n public PresentationBuilder locality(String p) {\n this.locality = p;\n return this;\n }\n\n public PresentationBuilder town(String p) {\n this.town = p;\n return this;\n }\n\n public PresentationBuilder area(String p) {\n this.area = p;\n return this;\n }\n\n public Presentation build() {\n return new Presentation(property, street, locality, town, area, postcode);\n }\n}" ]
import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.UniformInterfaceException; import com.yammer.dropwizard.auth.AuthenticationException; import com.yammer.dropwizard.auth.Authenticator; import com.yammer.dropwizard.testing.ResourceTest; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import uk.gov.gds.locate.api.LocateExceptionMapper; import uk.gov.gds.locate.api.authentication.BearerTokenAuthProvider; import uk.gov.gds.locate.api.configuration.LocateApiConfiguration; import uk.gov.gds.locate.api.dao.AddressDao; import uk.gov.gds.locate.api.dao.UsageDao; import uk.gov.gds.locate.api.helpers.DetailsBuilder; import uk.gov.gds.locate.api.helpers.OrderingBuilder; import uk.gov.gds.locate.api.helpers.PresentationBuilder; import uk.gov.gds.locate.api.model.*; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Collections; import java.util.Date; import java.util.List; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.*;
assertThat(result).contains("\"gssCode\":\"gssCode\""); assertThat(result).contains("\"uprn\":\"uprn\""); assertThat(result).contains("\"presentation\""); assertThat(result).contains("\"details\""); assertThat(result).contains("\"location\""); assertThat(result).contains("\"property\":\"property-test\""); assertThat(result).contains("\"street\":\"street-test\""); assertThat(result).contains("\"locality\":\"locality-test\""); assertThat(result).contains("\"town\":\"town-test\""); assertThat(result).contains("\"area\":\"area-test\""); assertThat(result).contains("\"postcode\":\"postcode-test\""); } @Test public void shouldReturnAListOfAddressesForASuccessfulSearchUsingPresentationFormatAsDefault() { List<SimpleAddress> result = client().resource("/locate/addresses?postcode=" + validPostcode).header("Authorization", presentationDataFieldsToken).get(new GenericType<List<SimpleAddress>>() { }); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0).getGssCode()).isEqualTo(address.getGssCode()); assertThat(result.get(0).getUprn()).isEqualTo(address.getUprn()); assertThat(result.get(0).getProperty()).isEqualTo("property-test"); assertThat(result.get(0).getStreet()).isEqualTo("street-test"); assertThat(result.get(0).getLocality()).isEqualTo("locality-test"); assertThat(result.get(0).getArea()).isEqualTo("area-test"); assertThat(result.get(0).getTown()).isEqualTo("town-test"); assertThat(result.get(0).getPostcode()).isEqualTo("postcode-test"); verify(dao, times(1)).findAllForPostcode(validPostcode); } @Test public void shouldReturnAListOfAddressesForASuccessfulSearchWithPresentationFormatQuery() { List<SimpleAddress> result = client().resource("/locate/addresses?format=presentation&postcode=" + validPostcode).header("Authorization", presentationDataFieldsToken).get(new GenericType<List<SimpleAddress>>() { }); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0).getGssCode()).isEqualTo(address.getGssCode()); assertThat(result.get(0).getUprn()).isEqualTo(address.getUprn()); assertThat(result.get(0).getProperty()).isEqualTo("property-test"); assertThat(result.get(0).getStreet()).isEqualTo("street-test"); assertThat(result.get(0).getLocality()).isEqualTo("locality-test"); assertThat(result.get(0).getArea()).isEqualTo("area-test"); assertThat(result.get(0).getTown()).isEqualTo("town-test"); assertThat(result.get(0).getPostcode()).isEqualTo("postcode-test"); verify(dao, times(1)).findAllForPostcode(validPostcode); } @Test public void shouldReturnAListOfAddressesAsValidJSONForASuccessfulSearchWithPresentationFormatQuery() { String result = client().resource("/locate/addresses?format=presentation&postcode=" + validPostcode).header("Authorization", presentationDataFieldsToken).get(String.class); verify(dao, times(1)).findAllForPostcode(validPostcode); assertThat(result).contains("\"gssCode\":\"gssCode\""); assertThat(result).contains("\"uprn\":\"uprn\""); assertThat(result).doesNotContain("\"presentation\""); assertThat(result).doesNotContain("\"details\""); assertThat(result).doesNotContain("\"location\""); assertThat(result).contains("\"property\":\"property-test\""); assertThat(result).contains("\"street\":\"street-test\""); assertThat(result).contains("\"locality\":\"locality-test\""); assertThat(result).contains("\"town\":\"town-test\""); assertThat(result).contains("\"area\":\"area-test\""); assertThat(result).contains("\"postcode\":\"postcode-test\""); } @Test public void shouldReturnAListOfAddressesForASuccessfulSearchWithVCardFormatQuery() { String result = client().resource("/locate/addresses?format=vcard&postcode=" + validPostcode).header("Authorization", allDataFieldsToken).get(String.class); verify(dao, times(1)).findAllForPostcode(validPostcode); assertThat(result).contains("\"x-uprn\":\"uprn\""); assertThat(result).contains("\"extended-address\":\"property-test\""); assertThat(result).contains("\"street-address\":\"street-test\""); assertThat(result).contains("\"locality\":\"town-test\""); assertThat(result).contains("\"region\":\"area-test\""); assertThat(result).contains("\"postal-code\":\"postcode-test\""); assertThat(result).contains("\"vcard\":\"ADR;:;;property-test;street-test;town-test;area-test;postcode-test;country\""); } @Test public void shouldReturnAListOfAddressesWithoutNullFieldsAsValidJSONForASuccessfulSearch() { Presentation presentation = new Presentation(); Address addressWithMissingFields = new Address("gssCode", "uprn", null, "country", new Date(), presentation, validAddress, new Location(), new Ordering(), "iv"); when(dao.findAllForPostcode(validPostcode)).thenReturn(ImmutableList.of(addressWithMissingFields)); String result = client().resource("/locate/addresses?postcode=" + validPostcode).header("Authorization", allDataFieldsToken).get(String.class); verify(dao, times(1)).findAllForPostcode(validPostcode); assertThat(result).contains("\"gssCode\":\"gssCode\""); assertThat(result).contains("\"uprn\":\"uprn\""); assertThat(result).doesNotContain("\"property\""); assertThat(result).doesNotContain("\"street\""); assertThat(result).doesNotContain("\"locality\""); assertThat(result).doesNotContain("\"town\""); assertThat(result).doesNotContain("\"area\""); assertThat(result).doesNotContain("\"postcode\""); } @Test public void shouldReturnAnEmptyListOfAddressesForAnUnsuccessfulSearch() { List<SimpleAddress> result = client().resource("/locate/addresses?postcode=" + inValidPostcode).header("Authorization", allDataFieldsToken).get(new GenericType<List<SimpleAddress>>() { }); assertThat(result.size()).isEqualTo(0); verify(dao, times(1)).findAllForPostcode(inValidPostcode); } @Test public void shouldReturnAnEmptyListOfAddressesAsValidJSONForAnUnsuccessfulSearch() { String result = client().resource("/locate/addresses?postcode=" + inValidPostcode).header("Authorization", allDataFieldsToken).get(String.class); assertThat(result).contains("[]"); verify(dao, times(1)).findAllForPostcode(inValidPostcode); } @Test public void shouldCallDaoWithTidyPostcode() throws UnsupportedEncodingException { client().resource("/locate/addresses?postcode=" + URLEncoder.encode(" PE1 1eR ", "UTF-8")).header("Authorization", allDataFieldsToken).get(String.class); verify(dao, times(1)).findAllForPostcode("pe11er"); } @Override protected void setUpResources() throws Exception { addResource(new AddressResource(dao, configuration));
addProvider(new BearerTokenAuthProvider(configuration, usageDao, new TestAuthenticator()));
1
dmfs/oauth2-essentials
src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java
[ "public interface OAuth2AccessToken\n{\n /**\n * Returns the actual access token String.\n *\n * @return\n *\n * @throws ProtocolException\n */\n public CharSequence accessToken() throws ProtocolException;\n\n /**\n * Returns the access token type.\n *\n * @return\n *\n * @throws ProtocolException\n */\n public CharSequence tokenType() throws ProtocolException;\n\n /**\n * Returns whether the response also contained a refresh token.\n *\n * @return\n */\n public boolean hasRefreshToken();\n\n /**\n * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.\n *\n * @return\n *\n * @throws NoSuchElementException\n * If the token doesn't contain a refresh token.\n * @throws ProtocolException\n */\n public CharSequence refreshToken() throws ProtocolException;\n\n /**\n * Returns the expected expiration date of the access token.\n *\n * @return\n *\n * @throws ProtocolException\n */\n public DateTime expirationDate() throws ProtocolException;\n\n /**\n * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.\n *\n * @return An {@link OAuth2Scope}.\n *\n * @throws ProtocolException\n */\n public OAuth2Scope scope() throws ProtocolException;\n\n /**\n * Returns a value stored in the token response under the {@code parameterName}.\n *\n * @param parameterName\n * the key under which the value is stored in the response\n */\n public Optional<CharSequence> extraParameter(final String parameterName);\n}", "public interface OAuth2Scope\n{\n /**\n * Returns whether this scope is empty.\n *\n * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.\n */\n boolean isEmpty();\n\n /**\n * Returns whether this scope contains the given scope token or not.\n *\n * @param token\n * The scope token to check for.\n *\n * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.\n */\n boolean hasToken(String token);\n\n /**\n * Returns the number of tokens in this {@link OAuth2Scope}.\n *\n * @return The number of tokens in this {@link OAuth2Scope}.\n */\n int tokenCount();\n\n /**\n * Returns a string version of this scope as described in <a href=\"https://tools.ietf.org/html/rfc6749#section-3.3\">RFC 6749, section 3.3</a>, i.e. a list\n * of scope tokens separated by spaces.\n *\n * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.\n */\n String toString();\n}", "public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>(\"access_token\", TextValueType.INSTANCE);", "public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>(\"expires_in\", new DurationValueType());", "public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>(\"scope\", new OAuth2ScopeValueType());", "public final static ParameterType<CharSequence> STATE = new BasicParameterType<>(\"state\", TextValueType.INSTANCE);", "public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>(\"token_type\", TextValueType.INSTANCE);" ]
import org.dmfs.httpessentials.exceptions.ProtocolException; import org.dmfs.jems.optional.Optional; import org.dmfs.oauth2.client.OAuth2AccessToken; import org.dmfs.oauth2.client.OAuth2Scope; import org.dmfs.rfc3986.Uri; import org.dmfs.rfc3986.parameters.ParameterList; import org.dmfs.rfc3986.parameters.adapters.OptionalParameter; import org.dmfs.rfc3986.parameters.adapters.TextParameter; import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList; import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType; import org.dmfs.rfc3986.parameters.valuetypes.TextValueType; import org.dmfs.rfc5545.DateTime; import org.dmfs.rfc5545.Duration; import java.util.NoSuchElementException; import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN; import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN; import static org.dmfs.oauth2.client.utils.Parameters.SCOPE; import static org.dmfs.oauth2.client.utils.Parameters.STATE; import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE;
/* * Copyright 2016 dmfs GmbH * * 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.dmfs.oauth2.client.tokens; /** * Represents an {@link OAuth2AccessToken} received from an Implicit Grant. * * @author Marten Gajda */ public final class ImplicitGrantAccessToken implements OAuth2AccessToken { private final Uri mRedirectUri; private final ParameterList mRedirectUriParameters; private final DateTime mIssueDate; private final OAuth2Scope mScope; private final Duration mDefaultExpiresIn; /** * Represents the {@link OAuth2AccessToken} that's contained in the provided redirect URI. * * @param redirectUri * The URI the user agent was redirected to. * @param scope * The scope that has been requested from the server. * @param state * The state that was provided to the authorization endpoint. * @param defaultExpiresIn * The default expiration duration to assume if no expiration duration was provided with the response. * * @throws ProtocolException * If the state doesn't match the one returned by the server. */ public ImplicitGrantAccessToken(Uri redirectUri, OAuth2Scope scope, CharSequence state, Duration defaultExpiresIn) throws ProtocolException { mRedirectUri = redirectUri; mRedirectUriParameters = new XwfueParameterList(redirectUri.fragment().value()); if (!state.toString().equals(new TextParameter(STATE, mRedirectUriParameters).toString())) { throw new ProtocolException("State in redirect uri doesn't match the original state!"); } mIssueDate = DateTime.now(); mScope = scope; mDefaultExpiresIn = defaultExpiresIn; } @Override public CharSequence accessToken() throws ProtocolException {
OptionalParameter<CharSequence> accessToken = new OptionalParameter<>(ACCESS_TOKEN, mRedirectUriParameters);
2
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/processor/resourcerule/CProcessorRendezvousResourceCertifiedTest.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 CProcessorRendezvousResourceCertifiedTest { private static final Logger LOGGER = Logger.getLogger(CProcessorRendezvousResourceCertifiedTest.class); @Test public void testCProcessorRendezvousResourceCertifiedTest() { TIBResource fileresource; try { fileresource = new TIBResource("src/test/resources/FileResources/RendezvousResourceCertified.rvResource"); fileresource.toString(); LOGGER.info(fileresource.toString()); assertTrue(fileresource.toString().equals("TIBResource [filePath=src/test/resources/FileResources/RendezvousResourceCertified.rvResource, type=rvsharedresource:RVResource]")); Tibrules tibrules= RulesParser.getInstance().parseFile("src/test/resources/FileResources/xml/RendezvousResourceCertified.xml");
Resource resource = tibrules.getResource();
4
JoshuaKissoon/DOSNA
src/dosna/simulations/performance/large/SimulatedUser.java
[ "public class DOSNA\r\n{\r\n\r\n private DataManager dataManager = null;\r\n private PeriodicNotificationsChecker notificationsChecker;\r\n\r\n public DOSNA()\r\n {\r\n\r\n }\r\n\r\n /**\r\n * Launch the main node for this instance\r\n * Connect to the network\r\n * Launch the main Application UI\r\n *\r\n * @param actorId\r\n * @param nid\r\n *\r\n * @return Boolean Whether the initialization was successful or not\r\n */\r\n public boolean initRouting(String actorId, KademliaId nid)\r\n {\r\n if (dataManager == null)\r\n {\r\n boolean isConnected = false;\r\n while (!isConnected)\r\n {\r\n try\r\n {\r\n dataManager = new DosnaDataManager(actorId, nid);\r\n isConnected = true;\r\n }\r\n catch (IOException ex)\r\n {\r\n /* Try again, since we may have tried to use a port already used */\r\n\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /* Starts the DOSNA */\r\n public void start()\r\n {\r\n this.userLogin();\r\n }\r\n\r\n /**\r\n * Launch the user login form and handle logging in the user\r\n */\r\n public void userLogin()\r\n {\r\n /* Ask the user to login */\r\n final LoginFrame login = new LoginFrame();\r\n login.setActionListener((final ActionEvent event) ->\r\n {\r\n switch (event.getActionCommand())\r\n {\r\n case \"login\":\r\n /* @todo Login the user */\r\n final String username = login.getUsername();\r\n final String password = login.getPassword();\r\n\r\n final LoginResult res = this.loginUser(username, password);\r\n if (res.isLoginSuccessful)\r\n {\r\n /* Everything's great! Launch the app */\r\n login.dispose();\r\n DOSNA.this.launchMainGUI(res.loggedInActor);\r\n }\r\n else\r\n {\r\n if (res.isActorExistent)\r\n {\r\n JOptionPane.showMessageDialog(null, \"Invalid password! please try again.\");\r\n }\r\n else\r\n {\r\n JOptionPane.showMessageDialog(null, \"Sorry, no account exists for the given user.\");\r\n }\r\n }\r\n break;\r\n case \"signup\":\r\n /* The user wants to signup, get them the signup form */\r\n login.dispose();\r\n DOSNA.this.userSignup();\r\n break;\r\n }\r\n });\r\n login.createGUI();\r\n login.display();\r\n }\r\n\r\n /**\r\n * Try to login a user into the system, handles the logic for logging in the user.\r\n *\r\n * @param actorId\r\n * @param password\r\n *\r\n * @return Whether the user login was successful or not\r\n */\r\n public LoginResult loginUser(String actorId, String password)\r\n {\r\n final Actor u = new Actor(actorId);\r\n\r\n DOSNA.this.initRouting(actorId, u.getKey());\r\n\r\n try\r\n {\r\n /* Checking if a user exists */\r\n final GetParameter gp = new GetParameter(u.getKey(), u.getType(), actorId);\r\n KademliaStorageEntry items = this.dataManager.get(gp);\r\n\r\n /* User exists! Now check if password matches */\r\n Actor actor = (Actor) new Actor().fromSerializedForm(items.getContent());\r\n if (actor.isPassword(password))\r\n {\r\n return new LoginResult(actor, true);\r\n }\r\n }\r\n catch (ContentNotFoundException cnfex)\r\n {\r\n /* The user does not exist */\r\n return new LoginResult();\r\n }\r\n catch (IOException ex)\r\n {\r\n\r\n }\r\n\r\n /* Login was unsuccessful */\r\n return new LoginResult(false);\r\n }\r\n\r\n /**\r\n * A class used to return the result of a login\r\n */\r\n public class LoginResult\r\n {\r\n\r\n public Actor loggedInActor = null;\r\n public boolean isLoginSuccessful = false;\r\n public boolean isActorExistent = false;\r\n\r\n public LoginResult(final Actor loggedInActor, final boolean isLoginSuccessful, final boolean isUserExistent)\r\n {\r\n this.loggedInActor = loggedInActor;\r\n this.isLoginSuccessful = isLoginSuccessful;\r\n this.isActorExistent = isUserExistent;\r\n }\r\n\r\n public LoginResult(final Actor loggedInActor, final boolean isLoginSuccessful)\r\n {\r\n this(loggedInActor, isLoginSuccessful, true);\r\n }\r\n\r\n public LoginResult(final Boolean isLoginSuccessful)\r\n {\r\n this.isLoginSuccessful = isLoginSuccessful;\r\n this.isActorExistent = true;\r\n }\r\n\r\n public LoginResult()\r\n {\r\n\r\n }\r\n }\r\n\r\n /**\r\n * Launch the user signup form and handle signing in the user\r\n */\r\n public void userSignup()\r\n {\r\n final SignupFrame signup = new SignupFrame();\r\n\r\n signup.setActionListener((ActionEvent e) ->\r\n {\r\n final String username = signup.getUsername().trim();\r\n final String password = signup.getPassword().trim();\r\n final String fullName = signup.getFullName().trim();\r\n\r\n if (username.isEmpty() || password.isEmpty() || fullName.isEmpty())\r\n {\r\n JOptionPane.showMessageDialog(null, \"All fields are required.\");\r\n }\r\n else\r\n {\r\n SignupResult res = this.signupUser(username, password, fullName);\r\n\r\n if (res.isSignupSuccessful)\r\n {\r\n signup.dispose();\r\n JOptionPane.showMessageDialog(null, \"You have successfully joined! welcome!\");\r\n DOSNA.this.launchMainGUI(res.actor);\r\n }\r\n else\r\n {\r\n if (res.isActorExistent)\r\n {\r\n JOptionPane.showMessageDialog(null, \"This username is already taken! Please try another username.\");\r\n }\r\n else\r\n {\r\n JOptionPane.showMessageDialog(null, \"The signup process encountered an error, please try again later.\");\r\n }\r\n }\r\n }\r\n });\r\n\r\n signup.createGUI();\r\n signup.display();\r\n }\r\n\r\n /**\r\n * Try to signup a user into the system, handles the logic for signing up the user.\r\n *\r\n * @param actor The actor object of the user to signup\r\n *\r\n * @return Whether the user signup was successful or not\r\n */\r\n public SignupResult signupUser(final Actor actor)\r\n {\r\n try\r\n {\r\n /* Initialize our routing */\r\n DOSNA.this.initRouting(actor.getId(), actor.getKey());\r\n\r\n /* See if this user object already exists on the network */\r\n GetParameter gp = new GetParameter(actor.getKey(), actor.getType(), actor.getId());\r\n dataManager.get(gp);\r\n\r\n /* Username is already taken */\r\n return new SignupResult(false);\r\n }\r\n catch (IOException | ContentNotFoundException ex)\r\n {\r\n try\r\n {\r\n /* Lets add this user to the system */\r\n ActorManager ac = new ActorManager(dataManager);\r\n Actor createdActor = ac.createActor(actor);\r\n\r\n /* User added, now launch DOSNA */\r\n return new SignupResult(createdActor, true);\r\n }\r\n catch (IOException exc)\r\n {\r\n\r\n }\r\n }\r\n\r\n /* We got here means things were not successful */\r\n return new SignupResult();\r\n }\r\n\r\n public SignupResult signupUser(final String userId, final String password, final String fullName)\r\n {\r\n final Actor u = new Actor(userId);\r\n u.setPassword(password);\r\n u.setName(fullName);\r\n\r\n return this.signupUser(u);\r\n }\r\n\r\n /**\r\n * A class used to return the result of a login\r\n */\r\n public class SignupResult\r\n {\r\n\r\n public Actor actor = null;\r\n public boolean isSignupSuccessful = false;\r\n public boolean isActorExistent = false;\r\n\r\n public SignupResult(final Actor actor, final boolean isSignupSuccessful, final boolean isActorExistent)\r\n {\r\n this.actor = actor;\r\n this.isSignupSuccessful = isSignupSuccessful;\r\n this.isActorExistent = isActorExistent;\r\n }\r\n\r\n public SignupResult(final Actor actor, final boolean isSignupSuccessful)\r\n {\r\n this(actor, isSignupSuccessful, false);\r\n }\r\n\r\n public SignupResult(final Boolean isSignupSuccessful)\r\n {\r\n this.isSignupSuccessful = isSignupSuccessful;\r\n this.isActorExistent = true;\r\n }\r\n\r\n public SignupResult()\r\n {\r\n\r\n }\r\n }\r\n\r\n /**\r\n * Launch the main GUI\r\n *\r\n * @param actor Which actor are we launching it for\r\n */\r\n public void launchMainGUI(final Actor actor)\r\n {\r\n /* Lets set the data manager for this actor's content manager */\r\n actor.init(this.dataManager);\r\n AnanciUI mainUi = new AnanciUI(dataManager, actor);\r\n mainUi.create();\r\n mainUi.display();\r\n\r\n /* Lets also launch the notifications checker */\r\n this.launchNotificationChecker(actor);\r\n }\r\n\r\n /**\r\n * Launch the notification checker\r\n *\r\n * @param actor\r\n */\r\n public void launchNotificationChecker(final Actor actor)\r\n {\r\n notificationsChecker = new PeriodicNotificationsChecker(this.dataManager, actor);\r\n notificationsChecker.startTimer();\r\n }\r\n\r\n public DataManager getDataManager()\r\n {\r\n return this.dataManager;\r\n }\r\n\r\n /**\r\n * Shuts down the core components of dosna\r\n *\r\n * @param saveState\r\n *\r\n * @throws java.io.IOException\r\n */\r\n public void shutdown(boolean saveState) throws IOException\r\n {\r\n this.dataManager.shutdown(saveState);\r\n this.notificationsChecker.shutdown();\r\n }\r\n\r\n /**\r\n * @param args the command line arguments\r\n */\r\n public static void main(String[] args)\r\n {\r\n new DOSNA().start();\r\n }\r\n\r\n}\r", "public class ContentManager\n{\n\n private final DataManager dataManager;\n\n /**\n * Construct a new content manager\n *\n * @param dataManager\n */\n public ContentManager(DataManager dataManager)\n {\n this.dataManager = dataManager;\n }\n\n /**\n * Places a content object update on the DHT and handles all of the extra operations.\n *\n * When a content is to be updated:\n * - The updated content is placed on the DHT.\n * - A notification is added to the Notification box of all of it's associated actors\n * -- All of these notification boxes are updated onto the DHT.\n *\n * @param content The updated content to be placed.\n */\n public void updateContent(DOSNAContent content)\n {\n try\n {\n /* Firstly, lets put the updated content onto the network */\n this.dataManager.put(content);\n\n /* Now lets notify associated users */\n List<String> associatedUsers = content.getRelatedActors();\n for (String actorId : associatedUsers)\n {\n /* Lets construct a temporary Notification Box for this actor since the key will be generated */\n NotificationBox temp = new NotificationBox(actorId);\n\n try\n {\n /* Retrieve this users notification box from the network */\n KademliaStorageEntry e = this.dataManager.get(temp.getKey(), temp.getType());\n NotificationBox original = (NotificationBox) new NotificationBox().fromSerializedForm(e.getContent());\n\n /* Add the updated notification box */\n original.addNotification(new Notification(content.getKey(), \"Content has been modified\"));\n\n /* Push the notification box back onto the network */\n dataManager.put(original);\n }\n catch (IOException | ContentNotFoundException ex)\n {\n\n }\n }\n }\n catch (IOException ex)\n {\n\n }\n\n }\n}", "public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable\r\n{\r\n\r\n public static final String TYPE = \"DOSNAContent\";\r\n\r\n public final long createTs;\r\n public long updateTs;\r\n\r\n /* Set of actors related to this content */\r\n Map<String, String> relatedActors;\r\n\r\n \r\n {\r\n this.createTs = this.updateTs = System.currentTimeMillis() / 1000L;\r\n relatedActors = new HashMap<>();\r\n }\r\n\r\n public DOSNAContent()\r\n {\r\n\r\n }\r\n\r\n @Override\r\n public long getCreatedTimestamp()\r\n {\r\n return this.createTs;\r\n }\r\n\r\n @Override\r\n public long getLastUpdatedTimestamp()\r\n {\r\n return this.updateTs;\r\n }\r\n\r\n @Override\r\n public byte[] toSerializedForm()\r\n {\r\n Gson gson = new Gson();\r\n// try (\r\n// ByteArrayOutputStream bout = new ByteArrayOutputStream();\r\n// ObjectOutputStream out = new ObjectOutputStream(bout))\r\n// {\r\n// out.writeObject(this);\r\n// out.close();\r\n// return bout.toByteArray();\r\n// }\r\n// catch (IOException ex)\r\n// {\r\n// ex.printStackTrace();\r\n// }\r\n\r\n return gson.toJson(this).getBytes();\r\n }\r\n\r\n @Override\r\n public DOSNAContent fromSerializedForm(byte[] data)\r\n {\r\n// try (ByteArrayInputStream bin = new ByteArrayInputStream(data);\r\n// ObjectInputStream oin = new ObjectInputStream(bin))\r\n// {\r\n// DOSNAContent val = (DOSNAContent) oin.readObject();\r\n// oin.close();\r\n// System.out.println(\"Deserialized: \" + val);\r\n// return val;\r\n// }\r\n// catch (IOException | ClassNotFoundException ex)\r\n// {\r\n// ex.printStackTrace();\r\n// }\r\n Gson gson = new Gson();\r\n DOSNAContent val = gson.fromJson(new String(data), this.getClass());\r\n return val;\r\n }\r\n\r\n /**\r\n * When some updates have been made to a content,\r\n * this method can be called to update the lastUpdated timestamp.\r\n */\r\n public void setUpdated()\r\n {\r\n this.updateTs = System.currentTimeMillis() / 1000L;\r\n }\r\n\r\n /**\r\n * When adding an actor we store the actor's ID and the actor's relationship to this content\r\n */\r\n @Override\r\n public void addActor(String userId, String relationship)\r\n {\r\n this.relatedActors.put(userId, relationship);\r\n }\r\n\r\n @Override\r\n public void addActor(Actor a, String relationship)\r\n {\r\n addActor(a.getId(), relationship);\r\n }\r\n\r\n @Override\r\n public List<String> getRelatedActors()\r\n {\r\n return new ArrayList<>(this.relatedActors.keySet());\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n StringBuilder sb = new StringBuilder(this.getType());\r\n\r\n sb.append(\": \");\r\n\r\n sb.append(\"[Actors: \");\r\n\r\n for (String a : this.relatedActors.keySet())\r\n {\r\n sb.append(a);\r\n sb.append(\"; \");\r\n }\r\n\r\n sb.append(\"]\");\r\n\r\n return sb.toString();\r\n }\r\n}\r", "public final class ContentMetadata implements Comparable<ContentMetadata>, Serializable\r\n{\r\n\r\n private KademliaId key;\r\n private long updateTs;\r\n private String ownerId;\r\n private String type;\r\n\r\n /**\r\n * Blank constructor used mainly by serializers.\r\n */\r\n public ContentMetadata()\r\n {\r\n\r\n }\r\n\r\n /**\r\n * Create a new ContentMetadata object for the given content\r\n *\r\n * @param content\r\n */\r\n public ContentMetadata(final DOSNAContent content)\r\n {\r\n this.key = content.getKey();\r\n this.updateTs = content.getLastUpdatedTimestamp();\r\n this.ownerId = content.getOwnerId();\r\n this.type = content.getType();\r\n }\r\n\r\n public KademliaId getKey()\r\n {\r\n return this.key;\r\n }\r\n\r\n public long getLastUpdatedTimestamp()\r\n {\r\n return this.updateTs;\r\n }\r\n\r\n public String getOwnerId()\r\n {\r\n return this.ownerId;\r\n }\r\n\r\n public String getType()\r\n {\r\n return this.type;\r\n }\r\n\r\n /**\r\n * We compare content Metadata based on timestamp\r\n */\r\n @Override\r\n public int compareTo(final ContentMetadata o)\r\n {\r\n if (this.getKey().equals(o.getKey()))\r\n {\r\n return 0;\r\n }\r\n\r\n return this.getLastUpdatedTimestamp() > o.getLastUpdatedTimestamp() ? 1 : -1;\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n StringBuilder sb = new StringBuilder(\"ContentMetadata: \");\r\n\r\n sb.append(\"[Type: \");\r\n sb.append(this.getType());\r\n sb.append(\"]\");\r\n\r\n sb.append(\"[Owner: \");\r\n sb.append(this.getOwnerId());\r\n sb.append(\"]\");\r\n\r\n sb.append(\"\");\r\n\r\n return sb.toString();\r\n }\r\n}\r", "public class ActivityStreamManager\n{\n\n private final Actor currentActor;\n private final DataManager dataManager;\n private final ActivityStream homeStream;\n\n private final DOSNAStatistician statistician;\n\n /* The total time it took to load the home stream */\n private transient long totalLoadingTime;\n\n /**\n * Initialize the HomeStreamManager\n *\n * @param currentActor The actor currently logged in\n * @param mngr Used to manage Data sending/receiving to/from the DHT\n * @param statistician Guy to manage the statistics\n */\n public ActivityStreamManager(final Actor currentActor, final DataManager mngr, final DOSNAStatistician statistician)\n {\n this.currentActor = currentActor;\n this.dataManager = mngr;\n this.statistician = statistician;\n\n this.homeStream = new ActivityStream();\n }\n\n public ActivityStreamManager(final Actor currentActor, final DataManager mngr)\n {\n this(currentActor, mngr, new DOSNAStatistician());\n }\n\n /**\n * @return HomeStream The homestream object\n */\n public ActivityStream getHomeStream()\n {\n return this.homeStream;\n }\n\n public ActivityStream createHomeStream()\n {\n /* Get the home stream content */\n Collection<DOSNAContent> homeStreamContent = getHomeStreamContent();\n Collection<ActivityStreamContent> toAdd = new ArrayList<>();\n for (DOSNAContent c : homeStreamContent)\n {\n if (c.getType().equals(Status.TYPE))\n {\n toAdd.add(new StatusHomeStreamDisplay((Status) c));\n }\n }\n\n this.homeStream.setContent(toAdd);\n this.homeStream.create();\n\n return this.homeStream;\n }\n\n /**\n * Loads the Home stream content from the DHT.\n *\n * Here we check the activity stream load time since:\n * - We want to check the time content takes to load.\n * - We don't want to check the time it takes for GUI display.\n *\n * @return The content to be displayed on the Home stream\n */\n public Collection<DOSNAContent> getHomeStreamContent()\n {\n /* Get the MetaData of the home stream content */\n Collection homeStreamContent = getHomeStreamContentMD();\n\n /* Use the home stream data manager to load the required content */\n ActivityStreamDataManager hsdm = new ActivityStreamDataManager(dataManager);\n Collection<DOSNAContent> content = hsdm.loadContent(homeStreamContent);\n\n this.statistician.addActivityStreamLoad(hsdm.getLoadingTime());\n\n return content;\n }\n\n /**\n * @return A set of content to be displayed on the home stream\n */\n public Collection<ContentMetadata> getHomeStreamContentMD()\n {\n /* Get a list of all content for all of this actor's connections */\n List<ContentMetadata> content = getConnectionsContentList();\n\n /* Use the selection algorithm to select which on the list is to be shown on the home stream */\n ActivityStreamContentSelector hscs = new ActivityStreamContentSelector(content);\n return hscs.getHomeStreamContent();\n }\n\n /**\n * Get a list of all content for all of this actor's connections\n *\n * @return\n */\n public List<ContentMetadata> getConnectionsContentList()\n {\n /* Load the actor objects of this actor's connections */\n Collection<Actor> connections = this.getConnections();\n\n /* Get a list of all content for all of this actor's connections */\n List<ContentMetadata> content = new ArrayList<>();\n for (Actor a : connections)\n {\n content.addAll(a.getContentManager().getAllContent());\n }\n \n System.out.println(this.currentActor.getId() + \" Total content possible for activity stream \" + content.size());\n\n return content;\n }\n\n /**\n * Gets the Actor object of all connections\n *\n * @return The set of connections\n */\n public Collection<Actor> getConnections()\n {\n Collection<Actor> connections = currentActor.getConnectionManager().loadConnections(this.dataManager);\n connections.add(currentActor);\n return connections;\n }\n}", "public class Actor extends DOSNAContent\n{\n\n public static final String TYPE = \"Actor\";\n\n /* Serialization keys */\n final static String SERIALK_CONTENT_MANAGER = \"CManager\";\n\n /* Manage the content posted by this actor */\n protected ActorContentManager contentManager;\n\n /* Manage relationships this actor have to other actors */\n protected ActorConnectionsManager connectionManager;\n\n /* Attributes */\n private String id;\n private String fullName;\n private KademliaId key;\n private String hashedPassword;\n\n /* References to other objects */\n private KademliaId notificationBoxNid;\n\n \n {\n this.contentManager = ActorContentManager.createNew(this);\n this.connectionManager = ActorConnectionsManager.createNew(this);\n }\n\n /**\n * Empty constructor mainly used by serializers\n */\n public Actor()\n {\n\n }\n\n /**\n * Create a new Actor object\n *\n * @param id\n */\n public Actor(final String id)\n {\n this.id = id.toLowerCase();\n this.generateKey();\n }\n\n /**\n * Generate a Node ID for this User object is the username/ownerId repeated until it have 20 characters\n *\n * @note The NodeId for this User object is the same as for the node this user uses,\n * A node will always store it's local user's uid\n */\n private void generateKey()\n {\n byte[] keyData = null;\n try\n {\n keyData = HashCalculator.sha1Hash(this.id);\n }\n catch (NoSuchAlgorithmException ex)\n {\n /*@todo try some other hash here */\n System.err.println(\"SHA-1 Hash algorithm isn't existent.\");\n }\n this.key = new KademliaId(keyData);\n }\n\n /**\n * Method that initializes the actor object and it's components.\n *\n * @param mngr The DataManager to manage content on the DHT\n */\n public final void init(final DataManager mngr)\n {\n /* After the ContentManager have been loaded from file, we need to set a few things */\n this.contentManager.setDataManager(mngr);\n this.contentManager.setActor(this);\n\n /* After the ConnectionsManager have been loaded from file, we need to set a few things */\n this.connectionManager.setActor(this);\n }\n\n public String getId()\n {\n return this.id;\n }\n\n public void setName(final String fullName)\n {\n this.fullName = fullName;\n }\n\n /**\n * @return String This user's full name\n */\n public String getName()\n {\n return this.fullName;\n }\n\n /**\n * Sets a new password for this user\n *\n * @param password\n */\n public void setPassword(final String password)\n {\n if (password.trim().equals(\"\"))\n {\n throw new NullPointerException();\n }\n\n this.hashedPassword = this.hashPassword(password);\n }\n\n public boolean isPassword(final String password)\n {\n return this.hashedPassword.equals(this.hashPassword(password));\n }\n\n /**\n * Hashes the password\n *\n * @param password The password to be hashed\n *\n * @return String The hashed password\n */\n private String hashPassword(final String password)\n {\n final String salt = \"iu4rkjd&^876%ewfuhi4Y&*&*^*03487658347*&^&^\";\n\n try\n {\n /* Return a string version of the hash */\n return new BigInteger(1, HashCalculator.md5Hash(password, salt)).toString(16);\n }\n catch (NoSuchAlgorithmException e)\n {\n return new BigInteger(1, password.getBytes()).multiply(new BigInteger(1, salt.getBytes())).toString(16);\n }\n }\n\n @Override\n public String getOwnerId()\n {\n return this.id;\n }\n\n @Override\n public KademliaId getKey()\n {\n return this.key;\n }\n\n @Override\n public String getType()\n {\n return TYPE;\n }\n\n /**\n * @return The ContentManager that manages this actors contents\n */\n public ActorContentManager getContentManager()\n {\n return this.contentManager;\n }\n\n /**\n * Set a new ContentManager for this Actor\n *\n * @param cm The new content manager\n */\n public void setContentManager(final ActorContentManager cm)\n {\n this.contentManager = cm;\n }\n\n /**\n * Add a new connection\n *\n * @param actorId The actor to connect to\n */\n public void addConnection(String actorId)\n {\n this.getConnectionManager().addConnection(new Relationship(this, actorId));\n this.setUpdated();\n }\n\n /**\n * Whether this actor is connected to the given actor\n *\n * @param conn The actor to check for connection with\n *\n * @return Whether the relationship exists\n */\n public boolean hasConnection(final Actor conn)\n {\n return this.getConnectionManager().hasConnection(conn);\n }\n\n /**\n * @return The ConnectionManager for this actor\n */\n public ActorConnectionsManager getConnectionManager()\n {\n return this.connectionManager;\n }\n\n /**\n * Sets the reference to the Notification Box Node ID on the network for this actor.\n *\n * @param notificationBoxNid\n */\n public void setNotificationBoxNid(KademliaId notificationBoxNid)\n {\n this.notificationBoxNid = notificationBoxNid;\n }\n\n @Override\n public String toString()\n {\n StringBuilder sb = new StringBuilder(\"User: \");\n\n sb.append(\"[username: \");\n sb.append(this.getOwnerId());\n\n sb.append(\"] \");\n sb.append(\"[name: \");\n sb.append(this.fullName);\n sb.append(\"] \");\n\n sb.append(\"[ContentManager: \");\n sb.append(this.getContentManager());\n sb.append(\"] \");\n\n sb.append(\"[ConnectionsManager: \");\n sb.append(this.getConnectionManager());\n sb.append(\"] \");\n\n return sb.toString();\n }\n}", "public class ActorManager\n{\n\n private final DataManager dataManager;\n\n /**\n * Initialize the actor creator class\n *\n * @param dataManager The Network Data Manager\n */\n public ActorManager(DataManager dataManager)\n {\n this.dataManager = dataManager;\n }\n\n /**\n * Method that creates the new actor\n *\n * @param actor The actor to place on the DHT\n *\n * @return Boolean whether the actor creation was successful or not\n *\n * @throws java.io.IOException\n */\n public Actor createActor(Actor actor) throws IOException\n {\n /* Lets create a new notification box for this actor */\n NotificationBox nb = new NotificationBox(actor);\n dataManager.put(nb);\n actor.setNotificationBoxNid(nb.getKey());\n\n dataManager.put(actor);\n\n return actor;\n }\n\n /**\n * Load the actor object from the DHT\n *\n * @param id The actor's user ID on the network\n *\n * @return The actor\n *\n * @throws java.io.IOException\n * @throws kademlia.exceptions.ContentNotFoundException\n */\n public Actor loadActor(String id) throws IOException, ContentNotFoundException\n {\n Actor a = new Actor(id);\n GetParameter gp = new GetParameter(a.getKey(), a.getType(), a.getId());\n KademliaStorageEntry se = dataManager.get(gp);\n return (Actor) new Actor().fromSerializedForm(se.getContent());\n }\n}", "public class Status extends DOSNAContent\n{\n\n public static final String TYPE = \"Status\";\n\n private String text;\n private String userId;\n\n private KademliaId key;\n\n /**\n * Blank public constructor mainly used by serializer.\n */\n public Status()\n {\n\n }\n\n /**\n * Private constructor used to create a new status\n *\n * @param actor The currently logged in actor\n * @param text The text of the status\n */\n private Status(final Actor actor, final String text)\n {\n this.text = text;\n this.userId = actor.getId();\n this.generateKey();\n\n /* Add the owner as an actor related to this content */\n addActor(actor, \"owner\");\n }\n\n /**\n * Generate a new key for this status given the userId.\n *\n * The key contains 10 characters of the userId first followed by the current timestamp (10 characters).\n */\n private void generateKey()\n {\n final long currentTs = System.currentTimeMillis() / 1000L;\n\n try\n {\n this.key = new KademliaId(HashCalculator.sha1Hash(userId + currentTs));\n }\n catch (NoSuchAlgorithmException ex)\n {\n /* @todo Handle this error */\n }\n }\n\n /**\n * We wrap the Status constructor that creates a new Status object to make it explicit.\n *\n * @param actor The actor who owns object\n * @param text The text of the status\n *\n * @return A new Status object\n */\n public static Status createNew(final Actor actor, final String text)\n {\n return new Status(actor, text);\n }\n\n /**\n * @return String The text of the status\n */\n public String getStatusText()\n {\n return this.text;\n }\n\n @Override\n public KademliaId getKey()\n {\n return this.key;\n }\n\n @Override\n public String getType()\n {\n return TYPE;\n }\n\n @Override\n public String getOwnerId()\n {\n return this.userId;\n }\n\n @Override\n public String toString()\n {\n StringBuilder sb = new StringBuilder(super.toString());\n\n sb.append(\"[\");\n\n sb.append(\"owner: \");\n sb.append(this.userId);\n sb.append(\"; \");\n\n sb.append(\"text: \");\n sb.append(this.text);\n sb.append(\"; \");\n\n sb.append(\"]\");\n\n return sb.toString();\n }\n}" ]
import dosna.DOSNA; import dosna.content.ContentManager; import dosna.content.DOSNAContent; import dosna.core.ContentMetadata; import dosna.core.DOSNAStatistician; import dosna.osn.activitystream.ActivityStreamManager; import dosna.osn.actor.Actor; import dosna.osn.actor.ActorManager; import dosna.osn.status.Status; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import kademlia.JKademliaNode; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId;
package dosna.simulations.performance.large; /** * A user used in simulation; this user performs the actions of a user of the system. * * @author Joshua Kissoon * @since 20140508 */ public class SimulatedUser { private Actor actor; private final DOSNA dosna; private String password; public int userNumber; /* Content Manager to manage the content on the network */ private ContentManager contentManager; /* DOSNA Statistician */ private final DOSNAStatistician statistician; /* Set of users in the simulation */ private final SimulatedUser[] users; /* Whether this user is online or not */ private boolean isOnline; { this.dosna = new DOSNA(); statistician = new DOSNAStatistician(); this.isOnline = false; } /** * Setup the simulated user * * @param actor The DOSN actor object for this user * @param userNumber The user number in the simulation * @param users Set of users in the simulation */ public SimulatedUser(final Actor actor, final int userNumber, final SimulatedUser[] users) { this.actor = actor; this.userNumber = userNumber; this.users = users; } /** * Setup the simulated user * * @param actorId The DOSN actor's id for this user * @param name * @param password * @param userNumber The user number in the simulation * @param users The set of users in the simulation */ public SimulatedUser(final String actorId, final String password, final String name, final int userNumber, final SimulatedUser[] users) { this.actor = new Actor(actorId); this.actor.setName(name); this.actor.setPassword(password); this.password = password; this.userNumber = userNumber; this.users = users; } public Actor getActor() { return this.actor; } public boolean signup() { DOSNA.SignupResult res = this.dosna.signupUser(this.actor); this.contentManager = new ContentManager(this.dosna.getDataManager()); if (res.isSignupSuccessful) { this.actor = res.actor; this.actor.init(this.dosna.getDataManager()); this.dosna.launchNotificationChecker(this.actor); this.isOnline = true; } return res.isSignupSuccessful; } public boolean login() { DOSNA.LoginResult res = this.dosna.loginUser(this.actor.getId(), this.password); this.contentManager = new ContentManager(this.dosna.getDataManager()); if (res.isLoginSuccessful) { this.actor = res.loggedInActor; this.actor.init(this.dosna.getDataManager()); this.dosna.launchNotificationChecker(this.actor); this.isOnline = true; } return res.isLoginSuccessful; } /** * Log the user out and shutdown the system * * @param saveState Whether to save the Node state or not * * @return Whether logout and shutdown was successful or not */ public boolean logout(boolean saveState) { try { this.dosna.shutdown(saveState); this.isOnline = false; return true; } catch (IOException ex) { return false; } } /** * Creates a new status for this user and places it on the DHT. * * @param statusText The status to put * * @throws java.io.IOException */ public synchronized void setNewStatus(String statusText) throws IOException { Status status = Status.createNew(this.getActor(), statusText); this.getActor().getContentManager().store(status); } public Actor loadActor(String uid) throws IOException, ContentNotFoundException {
return new ActorManager(this.dosna.getDataManager()).loadActor(uid);
6
DevLeoko/AdvancedBan
bukkit/src/main/java/me/leoko/advancedban/bukkit/BukkitMain.java
[ "public class Universal {\n\n private static Universal instance = null;\n\n public static void setRedis(boolean redis) {\n Universal.redis = redis;\n }\n\n private final Map<String, String> ips = new HashMap<>();\n private MethodInterface mi;\n private LogManager logManager;\n\n private static boolean redis = false;\n\n\n private final Gson gson = new Gson();\n\n\n\n\n\n /**\n * Get universal.\n *\n * @return the universal instance\n */\n public static Universal get() {\n return instance == null ? instance = new Universal() : instance;\n }\n\n /**\n * Initially sets up the plugin.\n *\n * @param mi the mi\n */\n public void setup(MethodInterface mi) {\n this.mi = mi;\n mi.loadFiles();\n logManager = new LogManager();\n UpdateManager.get().setup();\n UUIDManager.get().setup();\n\n try {\n DatabaseManager.get().setup(mi.getBoolean(mi.getConfig(), \"UseMySQL\", false));\n } catch (Exception ex) {\n log(\"Failed enabling database-manager...\");\n debugException(ex);\n }\n\n mi.setupMetrics();\n PunishmentManager.get().setup();\n\n for (Command command : Command.values()) {\n for (String commandName : command.getNames()) {\n mi.setCommandExecutor(commandName, command.getTabCompleter());\n }\n }\n\n String upt = \"You have the newest version\";\n String response = getFromURL(\"https://api.spigotmc.org/legacy/update.php?resource=8695\");\n if (response == null) {\n upt = \"Failed to check for updates :(\";\n } else if ((!mi.getVersion().startsWith(response))) {\n upt = \"There is a new version available! [\" + response + \"]\";\n }\n\n if (mi.getBoolean(mi.getConfig(), \"DetailedEnableMessage\", true)) {\n mi.log(\"\\n \\n&8[]=====[&7Enabling AdvancedBan&8]=====[]&r\"\n + \"\\n&8| &cInformation:&r\"\n + \"\\n&8| &cName: &7AdvancedBan&r\"\n + \"\\n&8| &cDeveloper: &7Leoko&r\"\n + \"\\n&8| &cVersion: &7\" + mi.getVersion() + \"&r\"\n + \"\\n&8| &cStorage: &7\" + (DatabaseManager.get().isUseMySQL() ? \"MySQL (external)\" : \"HSQLDB (local)\") + \"&r\"\n + \"\\n&8| &cSupport:&r\"\n + \"\\n&8| &cGithub: &7https://github.com/DevLeoko/AdvancedBan/issues &r\"\n + \"\\n&8| &cDiscord: &7https://discord.gg/ycDG6rS &r\"\n + \"\\n&8| &cTwitter: &7@LeokoGar&r\"\n + \"\\n&8| &cUpdate:&r\"\n + \"\\n&8| &7\" + upt + \"&r\"\n + \"\\n&8[]================================[]&r\\n \");\n } else {\n mi.log(\"&cEnabling AdvancedBan on Version &7&r\" + mi.getVersion());\n mi.log(\"&cCoded by &7Leoko &8| &7Twitter: @LeokoGar&r\");\n }\n }\n\n /**\n * Shutdown.\n */\n public void shutdown() {\n DatabaseManager.get().shutdown();\n\n if (mi.getBoolean(mi.getConfig(), \"DetailedDisableMessage\", true)) {\n mi.log(\"\\n \\n&8[]=====[&7Disabling AdvancedBan&8]=====[]\"\n + \"\\n&8| &cInformation:\"\n + \"\\n&8| &cName: &7AdvancedBan\"\n + \"\\n&8| &cDeveloper: &7Leoko\"\n + \"\\n&8| &cVersion: &7\" + getMethods().getVersion()\n + \"\\n&8| &cStorage: &7\" + (DatabaseManager.get().isUseMySQL() ? \"MySQL (external)\" : \"HSQLDB (local)\")\n + \"\\n&8| &cSupport:\"\n + \"\\n&8| &cGithub: &7https://github.com/DevLeoko/AdvancedBan/issues\"\n + \"\\n&8| &cDiscord: &7https://discord.gg/ycDG6rS\"\n + \"\\n&8| &cTwitter: &7@LeokoGar\"\n + \"\\n&8[]================================[]&r\\n \");\n } else {\n mi.log(\"&cDisabling AdvancedBan on Version &7\" + getMethods().getVersion());\n mi.log(\"&cCoded by Leoko &8| &7Twitter: @LeokoGar\");\n }\n }\n\n /**\n * Gets methods.\n *\n * @return the methods\n */\n public MethodInterface getMethods() {\n return mi;\n }\n\n /**\n * Is bungee boolean.\n *\n * @return the boolean\n */\n public boolean isBungee() {\n return mi.isBungee();\n }\n\n public Map<String, String> getIps() {\n return ips;\n }\n\n public static boolean isRedis() {\n return redis;\n }\n\n public Gson getGson() {\n return gson;\n }\n\n /**\n * Gets from url.\n *\n * @param surl the surl\n * @return the from url\n */\n public String getFromURL(String surl) {\n String response = null;\n try {\n URL url = new URL(surl);\n Scanner s = new Scanner(url.openStream());\n if (s.hasNext()) {\n response = s.next();\n s.close();\n }\n } catch (IOException exc) {\n debug(\"!! Failed to connect to URL: \" + surl);\n }\n return response;\n }\n\n /**\n * Is mute command boolean.\n *\n * @param cmd the cmd\n * @return the boolean\n */\n public boolean isMuteCommand(String cmd) {\n return isMuteCommand(cmd, getMethods().getStringList(getMethods().getConfig(), \"MuteCommands\"));\n }\n\n /**\n * Visible for testing. Do not use this. Please use {@link #isMuteCommand(String)}.\n * \n * @param cmd the command\n * @param muteCommands the mute commands from the config\n * @return true if the command matched any of the mute commands.\n */\n boolean isMuteCommand(String cmd, List<String> muteCommands) {\n String[] words = cmd.split(\" \");\n // Handle commands with colons\n if (words[0].indexOf(':') != -1) {\n words[0] = words[0].split(\":\", 2)[1];\n }\n for (String muteCommand : muteCommands) {\n if (muteCommandMatches(words, muteCommand)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Visible for testing. Do not use this.\n * \n * @param commandWords the command run by a player, separated into its words\n * @param muteCommand a mute command from the config\n * @return true if they match, false otherwise\n */\n boolean muteCommandMatches(String[] commandWords, String muteCommand) {\n // Basic equality check\n if (commandWords[0].equalsIgnoreCase(muteCommand)) {\n return true;\n }\n // Advanced equality check\n // Essentially a case-insensitive \"startsWith\" for arrays\n if (muteCommand.indexOf(' ') != -1) {\n String[] muteCommandWords = muteCommand.split(\" \");\n if (muteCommandWords.length > commandWords.length) {\n return false;\n }\n for (int n = 0; n < muteCommandWords.length; n++) {\n if (!muteCommandWords[n].equalsIgnoreCase(commandWords[n])) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Is exempt player boolean.\n *\n * @param name the name\n * @return the boolean\n */\n public boolean isExemptPlayer(String name) {\n List<String> exempt = getMethods().getStringList(getMethods().getConfig(), \"ExemptPlayers\");\n if (exempt != null) {\n for (String str : exempt) {\n if (name.equalsIgnoreCase(str)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Broadcast leoko boolean.\n *\n * @return the boolean\n */\n public boolean broadcastLeoko() {\n File readme = new File(getMethods().getDataFolder(), \"readme.txt\");\n if (!readme.exists()) {\n return true;\n }\n try {\n if (Files.readAllLines(Paths.get(readme.getPath()), Charset.defaultCharset()).get(0).equalsIgnoreCase(\"I don't want that there will be any message when the dev of this plugin joins the server! I want this even though the plugin is 100% free and the join-message is the only reward for the Dev :(\")) {\n return false;\n }\n } catch (IOException ignore) {\n }\n return true;\n }\n\n /**\n * Call connection string.\n *\n * @param name the name\n * @param ip the ip\n * @return the string\n */\n public String callConnection(String name, String ip) {\n name = name.toLowerCase();\n String uuid = UUIDManager.get().getUUID(name);\n if (uuid == null) return \"[AdvancedBan] Failed to fetch your UUID\";\n\n if (ip != null) {\n getIps().remove(name);\n getIps().put(name, ip);\n }\n\n InterimData interimData = PunishmentManager.get().load(name, uuid, ip);\n\n if (interimData == null) {\n if (getMethods().getBoolean(mi.getConfig(), \"LockdownOnError\", true)) {\n return \"[AdvancedBan] Failed to load player data!\";\n } else {\n return null;\n }\n }\n\n Punishment pt = interimData.getBan();\n\n if (pt == null) {\n interimData.accept();\n return null;\n }\n\n return pt.getLayoutBSN();\n }\n\n /**\n * Has perms boolean.\n *\n * @param player the player\n * @param perms the perms\n * @return the boolean\n */\n public boolean hasPerms(Object player, String perms) {\n if (mi.hasPerms(player, perms)) {\n return true;\n }\n\n if (mi.getBoolean(mi.getConfig(), \"EnableAllPermissionNodes\", false)) {\n while (perms.contains(\".\")) {\n perms = perms.substring(0, perms.lastIndexOf('.'));\n if (mi.hasPerms(player, perms + \".all\")) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Log.\n *\n * @param msg the msg\n */\n public void log(String msg) {\n mi.log(\"§8[§cAdvancedBan§8] §7\" + msg);\n debugToFile(msg);\n }\n\n /**\n * Debug.\n *\n * @param msg the msg\n */\n public void debug(Object msg) {\n if (mi.getBoolean(mi.getConfig(), \"Debug\", false)) {\n mi.log(\"§8[§cAdvancedBan§8] §cDebug: §7\" + msg.toString());\n }\n debugToFile(msg);\n }\n\n public void debugException(Exception exc) {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n exc.printStackTrace(pw);\n debug(sw.toString());\n }\n\n /**\n * Debug.\n *\n * @param ex the ex\n */\n public void debugSqlException(SQLException ex) {\n if (mi.getBoolean(mi.getConfig(), \"Debug\", false)) {\n debug(\"§7An error has occurred with the database, the error code is: '\" + ex.getErrorCode() + \"'\");\n debug(\"§7The state of the sql is: \" + ex.getSQLState());\n debug(\"§7Error message: \" + ex.getMessage());\n }\n debugException(ex);\n }\n\n private void debugToFile(Object msg) {\n File debugFile = new File(mi.getDataFolder(), \"logs/latest.log\");\n if (!debugFile.exists()) {\n try {\n debugFile.createNewFile();\n } catch (IOException ex) {\n System.out.print(\"An error has occurred creating the 'latest.log' file again, check your server.\");\n System.out.print(\"Error message\" + ex.getMessage());\n }\n } else {\n logManager.checkLastLog(false);\n }\n try {\n FileUtils.writeStringToFile(debugFile, \"[\" + new SimpleDateFormat(\"HH:mm:ss\").format(System.currentTimeMillis()) + \"] \" + mi.clearFormatting(msg.toString()) + \"\\n\", \"UTF8\", true);\n } catch (IOException ex) {\n System.out.print(\"An error has occurred writing to 'latest.log' file.\");\n System.out.print(ex.getMessage());\n }\n }\n}", "public class ChatListener implements Listener {\n @EventHandler(priority = EventPriority.HIGHEST)\n public void onChat(AsyncPlayerChatEvent event) {\n if (Universal.get().getMethods().callChat(event.getPlayer())) {\n event.setCancelled(true);\n }\n }\n}", "public class CommandListener implements Listener {\n @EventHandler(priority = EventPriority.HIGHEST)\n public void onCommand(PlayerCommandPreprocessEvent event) {\n if (Universal.get().getMethods().callCMD(event.getPlayer(), event.getMessage())) {\n event.setCancelled(true);\n }\n }\n}", "public class ConnectionListener implements Listener {\n @EventHandler(priority = EventPriority.HIGH)\n public void onConnect(AsyncPlayerPreLoginEvent event) {\n if(event.getLoginResult() == AsyncPlayerPreLoginEvent.Result.ALLOWED){\n UUIDManager.get().supplyInternUUID(event.getName(), event.getUniqueId());\n String result = Universal.get().callConnection(event.getName(), event.getAddress().getHostAddress());\n if (result != null) {\n event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, result);\n }\n }\n }\n\n @EventHandler\n public void onDisconnect(PlayerQuitEvent event){\n PunishmentManager.get().discard(event.getPlayer().getName());\n }\n\n @EventHandler\n public void onJoin(final PlayerJoinEvent event) {\n Universal.get().getMethods().scheduleAsync(() -> {\n if (event.getPlayer().getName().equalsIgnoreCase(\"Leoko\")) {\n Bukkit.getScheduler().runTaskLaterAsynchronously(BukkitMain.get(), () -> {\n if (Universal.get().broadcastLeoko()) {\n Bukkit.broadcastMessage(\"\");\n Bukkit.broadcastMessage(\"§c§lAdvancedBan §8§l» §7My creator §c§oLeoko §7just joined the game ^^\");\n Bukkit.broadcastMessage(\"\");\n } else {\n event.getPlayer().sendMessage(\"§c§lAdvancedBan v2 §8§l» §cHey Leoko we are using your Plugin (NO-BC)\");\n }\n }, 20);\n }\n }, 20);\n }\n\n\n}", "public class InternalListener implements Listener {\n \n @EventHandler\n public void onPunish(PunishmentEvent e) {\n BanList banlist;\n if (e.getPunishment().getType().equals(PunishmentType.BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_BAN)) {\n banlist = Bukkit.getBanList(BanList.Type.NAME);\n banlist.addBan(e.getPunishment().getName(), e.getPunishment().getReason(), new Date(e.getPunishment().getEnd()), e.getPunishment().getOperator());\n } else if (e.getPunishment().getType().equals(PunishmentType.IP_BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_IP_BAN)) {\n banlist = Bukkit.getBanList(BanList.Type.IP);\n banlist.addBan(e.getPunishment().getName(), e.getPunishment().getReason(), new Date(e.getPunishment().getEnd()), e.getPunishment().getOperator());\n }\n }\n \n @EventHandler\n public void onRevokePunishment(RevokePunishmentEvent e) {\n BanList banlist;\n if (e.getPunishment().getType().equals(PunishmentType.BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_BAN)) {\n banlist = Bukkit.getBanList(BanList.Type.NAME);\n banlist.pardon(e.getPunishment().getName());\n } else if (e.getPunishment().getType().equals(PunishmentType.IP_BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_IP_BAN)) {\n banlist = Bukkit.getBanList(BanList.Type.IP);\n banlist.pardon(e.getPunishment().getName());\n }\n }\n}" ]
import me.leoko.advancedban.Universal; import me.leoko.advancedban.bukkit.listener.ChatListener; import me.leoko.advancedban.bukkit.listener.CommandListener; import me.leoko.advancedban.bukkit.listener.ConnectionListener; import me.leoko.advancedban.bukkit.listener.InternalListener; import org.bukkit.Bukkit; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.plugin.java.JavaPlugin;
package me.leoko.advancedban.bukkit; public class BukkitMain extends JavaPlugin { private static BukkitMain instance; public static BukkitMain get() { return instance; } @Override public void onEnable() { instance = this; Universal.get().setup(new BukkitMethods());
ConnectionListener connListener = new ConnectionListener();
3
restsql/restsql
src/org/restsql/core/impl/AbstractSqlResourceMetaData.java
[ "public class Factory extends AbstractFactory {\n\n\t/** Creates request for child row with blank params. Configurable implementation class. */\n\tpublic static Request getChildRequest(final Request parentRequest) {\n\t\tfinal RequestFactory requestFactory = (RequestFactory) getInstance(Config.KEY_REQUEST_FACTORY,\n\t\t\t\tConfig.DEFAULT_REQUEST_FACTORY);\n\t\treturn requestFactory.getChildRequest(parentRequest);\n\t}\n\n\t/** Creates new column meta data object. Configurable implementation class. */\n\tpublic static ColumnMetaData getColumnMetaData() {\n\t\treturn (ColumnMetaData)newInstance(Config.KEY_COLUMN_METADATA, Config.DEFAULT_COLUMN_METADATA);\n\t}\n\n\t/** Returns connection. */\n\tpublic static Connection getConnection(final String defaultDatabase) throws SQLException {\n\t\treturn getConnectionFactory().getConnection(defaultDatabase);\n\t}\n\n\t/** Return connection factory. Useful for destroying it on app unload. Configurable implementation class. */\n\tpublic static ConnectionFactory getConnectionFactory() {\n\t\treturn (ConnectionFactory) getInstance(Config.KEY_CONNECTION_FACTORY,\n\t\t\t\tConfig.DEFAULT_CONNECTION_FACTORY);\n\t}\n\n\t/**\n\t * Creates HTTP request attributes. Configurable implementation class.\n\t * \n\t * @param client IP or host name\n\t * @param method HTTP method\n\t * @param uri request URI\n\t * @param requestBody request body, e.g. XML or JSON\n\t */\n\tpublic static HttpRequestAttributes getHttpRequestAttributes(final String client, final String method,\n\t\t\tfinal String uri, final String requestBody, final String requestContentType,\n\t\t\tfinal String responseContentType) {\n\t\tHttpRequestAttributes attributes = (HttpRequestAttributes) newInstance(\n\t\t\t\tConfig.KEY_HTTP_REQUEST_ATTRIBUTES, Config.DEFAULT_HTTP_REQUEST_ATTRIBUTES);\n\t\tattributes.setAttributes(client, method, uri, requestBody, requestContentType, responseContentType);\n\t\treturn attributes;\n\t}\n\n\t/**\n\t * Returns request object with pre-parsed data from the URI. Used by Java API clients.\n\t */\n\tpublic static Request getRequest(final Request.Type type, final String sqlResource,\n\t\t\tfinal List<RequestValue> resIds, final List<RequestValue> params,\n\t\t\tfinal List<List<RequestValue>> childrenParams, final RequestLogger requestLogger)\n\t\t\tthrows InvalidRequestException {\n\t\treturn getRequest(null, type, sqlResource, resIds, params, childrenParams, requestLogger);\n\t}\n\n\t/**\n\t * Returns request object with pre-parsed data from the URI. Used by service and Java API clients. Configurable\n\t * implementation class.\n\t */\n\tpublic static Request getRequest(final HttpRequestAttributes httpAttributes, final Request.Type type,\n\t\t\tfinal String sqlResource, final List<RequestValue> resIds, final List<RequestValue> params,\n\t\t\tfinal List<List<RequestValue>> childrenParams, final RequestLogger requestLogger)\n\t\t\tthrows InvalidRequestException {\n\t\tfinal RequestFactory requestFactory = (RequestFactory) getInstance(Config.KEY_REQUEST_FACTORY,\n\t\t\t\tConfig.DEFAULT_REQUEST_FACTORY);\n\t\treturn requestFactory.getRequest(httpAttributes, type, sqlResource, resIds, params, childrenParams,\n\t\t\t\trequestLogger);\n\t}\n\n\t/**\n\t * Builds request from URI. Assumes pattern\n\t * <code>res/{resourceName}/{resId1}/{resId2}?{param1}={value1}&amp;{param2}={value2}</code>. Used by the test harness,\n\t * Java API clients and perhaps a straight servlet implementation. Configurable implementation class.\n\t */\n\tpublic static Request getRequest(final HttpRequestAttributes httpAttributes)\n\t\t\tthrows InvalidRequestException, SqlResourceFactoryException, SqlResourceException {\n\t\tfinal RequestFactory requestFactory = (RequestFactory) getInstance(Config.KEY_REQUEST_FACTORY,\n\t\t\t\tConfig.DEFAULT_REQUEST_FACTORY);\n\t\treturn requestFactory.getRequest(httpAttributes);\n\t}\n\n\t/** Returns request logger. Configurable implementation class. */\n\tpublic static RequestLogger getRequestLogger() {\n\t\treturn (RequestLogger) newInstance(Config.KEY_REQUEST_LOGGER, Config.DEFAULT_REQUEST_LOGGER);\n\t}\n\n\t/**\n\t * Returns request deserializer. Configurable implementation class.\n\t * \n\t * @throws SqlResourceException if deserializer not found for media type\n\t */\n\tpublic static RequestDeserializer getRequestDeserializer(final String mediaType)\n\t\t\tthrows SqlResourceException {\n\t\tfinal RequestDeserializerFactory rdFactory = (RequestDeserializerFactory) getInstance(\n\t\t\t\tConfig.KEY_REQUEST_DESERIALIZER_FACTORY, Config.DEFAULT_REQUEST_DESERIALIZER_FACTORY);\n\t\treturn rdFactory.getRequestDeserializer(mediaType);\n\t}\n\n\t/**\n\t * Returns response serializer for media type. Configurable implementation class.\n\t * \n\t * @throws SqlResourceException if serializer not found for media type\n\t */\n\tpublic static ResponseSerializer getResponseSerializer(final String mediaType)\n\t\t\tthrows SqlResourceException {\n\t\tfinal ResponseSerializerFactory rsFactory = (ResponseSerializerFactory) getInstance(\n\t\t\t\tConfig.KEY_RESPONSE_SERIALIZER_FACTORY, Config.DEFAULT_RESPONSE_SERIALIZER_FACTORY);\n\t\treturn rsFactory.getResponseSerializer(mediaType);\n\t}\n\n\t/** Returns singleton SequenceManager. Configurable implementation class. */\n\tpublic static SequenceManager getSequenceManager() {\n\t\treturn (SequenceManager) getInstance(Config.KEY_SEQUENCE_MANAGER, Config.DEFAULT_SEQUENCE_MANAGER);\n\t}\n\n\t/** Returns existing singleton SqlBuilder. Configurable implementation. */\n\tpublic static SqlBuilder getSqlBuilder() {\n\t\treturn (SqlBuilder) getInstance(Config.KEY_SQL_BUILDER, Config.DEFAULT_SQL_BUILDER);\n\t}\n\n\t/**\n\t * Returns SQL Resource for named resource. Configurable implementation class.\n\t * \n\t * @param resName resource name\n\t * @return SQLResource object\n\t * @throws SqlResourceFactoryException if the definition could not be marshalled\n\t * @throws SqlResourceException if a database error occurs while collecting metadata\n\t */\n\tpublic static SqlResource getSqlResource(final String resName) throws SqlResourceFactoryException,\n\t\t\tSqlResourceException {\n\t\tfinal SqlResourceFactory sqlResourceFactory = (SqlResourceFactory) getInstance(\n\t\t\t\tConfig.KEY_SQL_RESOURCE_FACTORY, Config.DEFAULT_SQL_RESOURCE_FACTORY);\n\t\treturn sqlResourceFactory.getSqlResource(resName);\n\t}\n\n\t/**\n\t * Returns definition content as input stream. Configurable implementation class.\n\t */\n\tpublic static InputStream getSqlResourceDefinition(final String resName)\n\t\t\tthrows SqlResourceFactoryException {\n\t\tfinal SqlResourceFactory sqlResourceFactory = (SqlResourceFactory) getInstance(\n\t\t\t\tConfig.KEY_SQL_RESOURCE_FACTORY, Config.DEFAULT_SQL_RESOURCE_FACTORY);\n\t\treturn sqlResourceFactory.getSqlResourceDefinition(resName);\n\t}\n\n\t/**\n\t * Returns meta data object for definition. Configurable implementation class.\n\t * @param sqlBuilder db-specific SQL builder\n\t * \n\t * @throws SqlResourceException if a database access error occurs\n\t */\n\tpublic static SqlResourceMetaData getSqlResourceMetaData(final String resName,\n\t\t\tfinal SqlResourceDefinition definition, SqlBuilder sqlBuilder) throws SqlResourceException {\n\t\tfinal SqlResourceMetaData sqlResourceMetaData = (SqlResourceMetaData) newInstance(\n\t\t\t\tConfig.KEY_SQL_RESOURCE_METADATA, Config.DEFAULT_SQL_RESOURCE_METADATA);\n\t\tsqlResourceMetaData.init(resName, definition, sqlBuilder);\n\t\treturn sqlResourceMetaData;\n\t}\n\n\t/** Returns SQL resources directory using configured SqlResourceFactory. */\n\tpublic static String getSqlResourcesDir() {\n\t\tfinal SqlResourceFactory sqlResourceFactory = (SqlResourceFactory) getInstance(\n\t\t\t\tConfig.KEY_SQL_RESOURCE_FACTORY, Config.DEFAULT_SQL_RESOURCE_FACTORY);\n\t\treturn sqlResourceFactory.getSqlResourcesDir();\n\t}\n\n\t/**\n\t * Returns available SQL Resource names using configured SqlResourceFactory.\n\t * \n\t * @throws SqlResourceFactoryException if the configured directory does not exist\n\t */\n\tpublic static List<String> getSqlResourceNames() throws SqlResourceFactoryException {\n\t\tfinal SqlResourceFactory sqlResourceFactory = (SqlResourceFactory) getInstance(\n\t\t\t\tConfig.KEY_SQL_RESOURCE_FACTORY, Config.DEFAULT_SQL_RESOURCE_FACTORY);\n\t\treturn sqlResourceFactory.getSqlResourceNames();\n\t}\n\t\n\t/** Creates new table meta data object. Configurable implementation class. */\n\tpublic static TableMetaData getTableMetaData() {\n\t\treturn (TableMetaData)newInstance(Config.KEY_TABLE_METADATA, Config.DEFAULT_TABLE_METADATA);\n\t}\n\n\t/**\n\t * Reloads definition from the source using configured SqlResourceFactory. This operation is not thread safe and\n\t * should be run in development mode only.\n\t * \n\t * @param resName resource name\n\t * @throws SqlResourceFactoryException if the definition could not be marshalled\n\t * @throws SqlResourceException if a database error occurs while collecting metadata\n\t */\n\tpublic static void reloadSqlResource(final String resName) throws SqlResourceFactoryException,\n\t\t\tSqlResourceException {\n\t\tfinal SqlResourceFactory sqlResourceFactory = (SqlResourceFactory) getInstance(\n\t\t\t\tConfig.KEY_SQL_RESOURCE_FACTORY, Config.DEFAULT_SQL_RESOURCE_FACTORY);\n\t\tsqlResourceFactory.reloadSqlResource(resName);\n\t}\n\n\t// Factory Interfaces\n\n\t/** Creates JDBC connection objects. */\n\tpublic interface ConnectionFactory {\n\t\tpublic void destroy() throws SQLException;\n\n\t\tpublic Connection getConnection(String defaultDatabase) throws SQLException;\n\t}\n\n\t/** Creates Request objects. */\n\tpublic interface RequestFactory {\n\t\tpublic Request getChildRequest(final Request parentRequest);\n\n\t\tpublic Request getRequest(final HttpRequestAttributes httpAttributes) throws InvalidRequestException,\n\t\t\t\tSqlResourceFactoryException, SqlResourceException;\n\n\t\tpublic Request getRequest(final HttpRequestAttributes httpAttributes, final Type type,\n\t\t\t\tfinal String sqlResource, final List<RequestValue> resIds, final List<RequestValue> params,\n\t\t\t\tfinal List<List<RequestValue>> childrenParams, final RequestLogger requestLogger)\n\t\t\t\tthrows InvalidRequestException;\n\t}\n\n\t/** Creates RequestDeserializer objects. */\n\tpublic interface RequestDeserializerFactory {\n\t\tpublic RequestDeserializer getRequestDeserializer(final String mediaType) throws SqlResourceException;\n\t}\n\n\t/** Creates ResponseSerializer objects. */\n\tpublic interface ResponseSerializerFactory {\n\t\tpublic ResponseSerializer getResponseSerializer(final String mediaType) throws SqlResourceException;\n\t}\n\n\t/** Creates SQLResource objects. */\n\tpublic interface SqlResourceFactory {\n\t\tpublic SqlResource getSqlResource(final String resName) throws SqlResourceFactoryException,\n\t\t\t\tSqlResourceException;\n\n\t\tpublic InputStream getSqlResourceDefinition(String resName) throws SqlResourceFactoryException;\n\n\t\tpublic List<String> getSqlResourceNames() throws SqlResourceFactoryException;\n\n\t\tpublic String getSqlResourcesDir();\n\n\t\tpublic void reloadSqlResource(String resName) throws SqlResourceFactoryException,\n\t\t\t\tSqlResourceException;\n\t}\n\n\t/** Indicates an error in creating a SQL Resource object from a definition. */\n\tpublic static class SqlResourceFactoryException extends SqlResourceException {\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\tpublic SqlResourceFactoryException(final String message) {\n\t\t\tsuper(message);\n\t\t}\n\n\t\tpublic SqlResourceFactoryException(final Throwable cause) {\n\t\t\tsuper(cause);\n\t\t}\n\t}\n}", "public interface Request {\n\tpublic static final String PARAM_NAME_LIMIT = \"_limit\";\n\tpublic static final String PARAM_NAME_OFFSET = \"_offset\";\n\tpublic static final String PARAM_NAME_OUTPUT = \"_output\";\n\n\t/** Returns children CUD requests to a single parent for a hierarchical SQL Resource. */\n\tpublic List<List<RequestValue>> getChildrenParameters();\n\n\t/** Returns http request attributes. */\n\tpublic HttpRequestAttributes getHttpRequestAttributes();\n\n\t/** Returns request logger. */\n\tpublic RequestLogger getLogger();\n\n\t/** Returns ordered list of parameters, for example the selection filter for update request. */\n\tpublic List<RequestValue> getParameters();\n\n\t/** Returns parent, if any. */\n\tpublic Request getParent();\n\n\t/**\n\t * Returns ordered list of primary key values for a CRUD request on a single object (row). On a hierarchical SQL\n\t * Resource, this list identifies the parent and the children are identified by the children parameters.\n\t */\n\tpublic List<RequestValue> getResourceIdentifiers();\n\n\t/** Returns select row limit, if any. */\n\tpublic Integer getSelectLimit();\n\n\t/** Returns select row offset, if any. */\n\tpublic Integer getSelectOffset();\n\n\t/** Returns SQL Resource name. */\n\tpublic String getSqlResource();\n\n\t/** Returns request type. */\n\tpublic Type getType();\n\n\t/** Returns true if request has parameter with the given name. */\n\tpublic boolean hasParameter(String name);\n\n\t/** Sets parameters for request. Used for cloning requests on child objects. */\n\tpublic void setParameters(final List<RequestValue> params);\n\n\t/** Sets parent request. */\n\tpublic void setParent(Request parentRequest);\n\n\t/**\n\t * Sets select limit.\n\t */\n\tpublic void setSelectLimit(final Integer integer);\n\n\t/**\n\t * Sets select offset.\n\t */\n\tpublic void setSelectOffset(final Integer integer);\n\n\t/**\n\t * Extract limit and offset.\n\t * \n\t * @throws InvalidRequestException if request is invalid\n\t */\n\tpublic void extractParameters() throws InvalidRequestException;\n\n\t/**\n\t * Represents request types, mapping to CRUD operations.\n\t * \n\t * @author Mark Sawers\n\t */\n\tpublic enum Type {\n\t\tDELETE, INSERT, SELECT, UPDATE;\n\n\t\tpublic static Type fromHttpMethod(final String method) {\n\t\t\tType type;\n\t\t\tif (method.equals(\"DELETE\")) {\n\t\t\t\ttype = Type.DELETE;\n\t\t\t} else if (method.equals(\"GET\")) {\n\t\t\t\ttype = Type.SELECT;\n\t\t\t} else if (method.equals(\"POST\")) {\n\t\t\t\ttype = Type.INSERT;\n\t\t\t} else { // method.equals(\"PUT\")\n\t\t\t\ttype = Type.UPDATE;\n\t\t\t}\n\t\t\treturn type;\n\t\t}\n\t}\n}", "public enum Type {\n\tDELETE, INSERT, SELECT, UPDATE;\n\n\tpublic static Type fromHttpMethod(final String method) {\n\t\tType type;\n\t\tif (method.equals(\"DELETE\")) {\n\t\t\ttype = Type.DELETE;\n\t\t} else if (method.equals(\"GET\")) {\n\t\t\ttype = Type.SELECT;\n\t\t} else if (method.equals(\"POST\")) {\n\t\t\ttype = Type.INSERT;\n\t\t} else { // method.equals(\"PUT\")\n\t\t\ttype = Type.UPDATE;\n\t\t}\n\t\treturn type;\n\t}\n}", "public interface TableMetaData {\n\n\t/** Adds normal column. */\n\tpublic void addColumn(final ColumnMetaData column);\n\n\t/** Adds primary key column. */\n\tpublic void addPrimaryKey(final ColumnMetaData column);\n\n\t/** Returns map of column meta data, keyed by the column label (the alias if provided in the query, otherwise the name). */\n\tpublic Map<String, ColumnMetaData> getColumns();\n\n\t/** Returns database name. */\n\tpublic String getDatabaseName();\n\n\t/** Returns ordered list of columns that are primary keys. */\n\tpublic List<ColumnMetaData> getPrimaryKeys();\n\n\t/**\n\t * Returns fully qualified table name in database-specific form for use in SQL statements. MySQL uses the form\n\t * <code>database.table</code>, for example <code>sakila.film</code>. PostgreSQL uses the form\n\t * <code>database.schema.table</code>, for example <code>sakila.public.film</code>.\n\t */\n\tpublic String getQualifiedTableName();\n\n\t/** Returns row alias. */\n\tpublic String getRowAlias();\n\t\n\t/** Returns row set alias. */\n\tpublic String getRowSetAlias();\n\t\n\t/**\n\t * Returns row alias.\n\t * \n * @deprecated As of 0.8.11 use {@link #getRowAlias()}\n\t */\n\t@Deprecated\n\tpublic String getTableAlias();\n\n\t/** Returns table name. */\n\tpublic String getTableName();\n\n\t/** Returns role of table in the SQL Resource. */\n\tpublic TableRole getTableRole();\n\n\t/** Returns true if the SQL Resource role is child. */\n\tpublic boolean isChild();\n\n\t/** Returns true if the SQL Resource role is parent. */\n\tpublic boolean isParent();\n\n\t/** Sets all the row and row set aliases. */\n\tpublic void setAliases(final String alias, final String rowAlias, final String rowSetAlias);\n\n\t/** Sets attributes. */\n\tpublic void setAttributes(final String tableName, final String qualifedTableName,\n\t\t\tfinal String databaseName, final TableRole tableRole);\n\n\t/**\n\t * Sets table alias.\n\t * \n * @deprecated As of 0.8.11 use {@link #setAliases(String, String, String)}\n\t */\n\t@Deprecated\n\tpublic void setTableAlias(final String tableAlias);\n\t\n\t/** Represents all of the roles a table may plan in a SQL Resource. */\n\t@XmlType(namespace = \"http://restsql.org/schema\")\n\tpublic enum TableRole {\n\t\tChild, ChildExtension, Join, Parent, ParentExtension, Unknown;\n\t}\n}", "@XmlType(namespace = \"http://restsql.org/schema\")\npublic enum TableRole {\n\tChild, ChildExtension, Join, Parent, ParentExtension, Unknown;\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"Documentation\", propOrder = {\n \"resource\",\n \"columns\",\n \"examples\"\n})\npublic class Documentation {\n\n protected DocumentationResource resource;\n protected DocumentationColumns columns;\n protected DocumentationExamples examples;\n\n /**\n * Gets the value of the resource property.\n * \n * @return\n * possible object is\n * {@link DocumentationResource }\n * \n */\n public DocumentationResource 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 DocumentationResource }\n * \n */\n public void setResource(DocumentationResource value) {\n this.resource = value;\n }\n\n /**\n * Gets the value of the columns property.\n * \n * @return\n * possible object is\n * {@link DocumentationColumns }\n * \n */\n public DocumentationColumns getColumns() {\n return columns;\n }\n\n /**\n * Sets the value of the columns property.\n * \n * @param value\n * allowed object is\n * {@link DocumentationColumns }\n * \n */\n public void setColumns(DocumentationColumns value) {\n this.columns = value;\n }\n\n /**\n * Gets the value of the examples property.\n * \n * @return\n * possible object is\n * {@link DocumentationExamples }\n * \n */\n public DocumentationExamples getExamples() {\n return examples;\n }\n\n /**\n * Sets the value of the examples property.\n * \n * @param value\n * allowed object is\n * {@link DocumentationExamples }\n * \n */\n public void setExamples(DocumentationExamples value) {\n this.examples = value;\n }\n\n}", "@XmlRootElement(name = \"sqlResource\", namespace = \"http://restsql.org/schema\")\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"SqlResource\", propOrder = {\n \"query\",\n \"metadata\",\n \"validatedAttribute\",\n \"http\",\n \"documentation\"\n})\npublic class SqlResourceDefinition {\n\n @XmlElement(required = true)\n protected Query query;\n @XmlElement(required = true)\n protected MetaData metadata;\n protected List<ValidatedAttribute> validatedAttribute;\n protected HttpConfig http;\n protected Documentation documentation;\n\n /**\n * Gets the value of the query property.\n * \n * @return\n * possible object is\n * {@link Query }\n * \n */\n public Query getQuery() {\n return query;\n }\n\n /**\n * Sets the value of the query property.\n * \n * @param value\n * allowed object is\n * {@link Query }\n * \n */\n public void setQuery(Query value) {\n this.query = value;\n }\n\n /**\n * Gets the value of the metadata property.\n * \n * @return\n * possible object is\n * {@link MetaData }\n * \n */\n public MetaData getMetadata() {\n return metadata;\n }\n\n /**\n * Sets the value of the metadata property.\n * \n * @param value\n * allowed object is\n * {@link MetaData }\n * \n */\n public void setMetadata(MetaData value) {\n this.metadata = value;\n }\n\n /**\n * Gets the value of the validatedAttribute 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 validatedAttribute property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getValidatedAttribute().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link ValidatedAttribute }\n * \n * \n */\n public List<ValidatedAttribute> getValidatedAttribute() {\n if (validatedAttribute == null) {\n validatedAttribute = new ArrayList<ValidatedAttribute>();\n }\n return this.validatedAttribute;\n }\n\n /**\n * Gets the value of the http property.\n * \n * @return\n * possible object is\n * {@link HttpConfig }\n * \n */\n public HttpConfig getHttp() {\n return http;\n }\n\n /**\n * Sets the value of the http property.\n * \n * @param value\n * allowed object is\n * {@link HttpConfig }\n * \n */\n public void setHttp(HttpConfig value) {\n this.http = value;\n }\n\n /**\n * Gets the value of the documentation property.\n * \n * @return\n * possible object is\n * {@link Documentation }\n * \n */\n public Documentation getDocumentation() {\n return documentation;\n }\n\n /**\n * Sets the value of the documentation property.\n * \n * @param value\n * allowed object is\n * {@link Documentation }\n * \n */\n public void setDocumentation(Documentation value) {\n this.documentation = value;\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"Table\")\npublic class Table {\n\n @XmlAttribute(name = \"name\", required = true)\n protected String name;\n @XmlAttribute(name = \"alias\")\n protected String alias;\n @XmlAttribute(name = \"rowAlias\")\n protected String rowAlias;\n @XmlAttribute(name = \"rowSetAlias\")\n protected String rowSetAlias;\n @XmlAttribute(name = \"role\", required = true)\n protected String role;\n\n /**\n * Gets the value of the name property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getName() {\n return name;\n }\n\n /**\n * Sets the value of the name property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setName(String value) {\n this.name = value;\n }\n\n /**\n * Gets the value of the alias property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getAlias() {\n return alias;\n }\n\n /**\n * Sets the value of the alias property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setAlias(String value) {\n this.alias = value;\n }\n\n /**\n * Gets the value of the rowAlias property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRowAlias() {\n return rowAlias;\n }\n\n /**\n * Sets the value of the rowAlias property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRowAlias(String value) {\n this.rowAlias = value;\n }\n\n /**\n * Gets the value of the rowSetAlias property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRowSetAlias() {\n return rowSetAlias;\n }\n\n /**\n * Sets the value of the rowSetAlias property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRowSetAlias(String value) {\n this.rowSetAlias = value;\n }\n\n /**\n * Gets the value of the role property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRole() {\n return role;\n }\n\n /**\n * Sets the value of the role property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRole(String value) {\n this.role = value;\n }\n\n}" ]
import java.io.StringWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.restsql.core.ColumnMetaData; import org.restsql.core.Config; import org.restsql.core.Factory; import org.restsql.core.InvalidRequestException; import org.restsql.core.Request; import org.restsql.core.Request.Type; import org.restsql.core.SqlBuilder; import org.restsql.core.SqlResourceException; import org.restsql.core.SqlResourceMetaData; import org.restsql.core.TableMetaData; import org.restsql.core.TableMetaData.TableRole; import org.restsql.core.sqlresource.Documentation; import org.restsql.core.sqlresource.SqlResourceDefinition; import org.restsql.core.sqlresource.SqlResourceDefinitionUtils; import org.restsql.core.sqlresource.Table;
* @throws InvalidRequestException if main query is invalid */ protected String getSqlMainQuery(final SqlResourceDefinition definition, final SqlBuilder sqlBuilder) throws InvalidRequestException { final Request request = Factory.getRequest(Type.SELECT, resName, null, null, null, null); request.setSelectLimit(new Integer(1)); request.setSelectOffset(new Integer(0)); return sqlBuilder.buildSelectSql(this, definition.getQuery().getValue(), request).getStatement(); } /** * Retrieves sql for querying primary keys. Hook method for buildPrimaryKeys allows database-specific overrides. */ protected abstract String getSqlPkQuery(); /** * Return whether a column in the given result set is read-only. The default implementation just calls isReadOnly() * on the result set, database specific implementations can override this behavior. Contributed by <a * href="https://github.com/rhuitl">rhuitl</a>. * * @param resultSetMetaData Result set metadata * @param colNumber Column number (1..N) * @throws SQLException if a database access error occurs */ protected boolean isColumnReadOnly(final ResultSetMetaData resultSetMetaData, final int colNumber) throws SQLException { return resultSetMetaData.isReadOnly(colNumber); } /** * Returns true if db metadata, e.g. database/owner, table and column names are stored as upper case, and therefore * lookups should be forced to upper. Database specific implementation can override this response. */ protected boolean isDbMetaDataUpperCase() { return false; } /** * Sets sequence metadata for a column with the columns query result set. * * @throws SQLException when a database error occurs */ protected abstract void setSequenceMetaData(ColumnMetaDataImpl column, ResultSet resultSet) throws SQLException; /** Build extended metadata for serialization if first time through. */ private void buildExtendedMetadata() { if (!extendedMetadataIsBuilt) { parentTableName = getQualifiedTableName(parentTable); childTableName = getQualifiedTableName(childTable); joinTableName = getQualifiedTableName(joinTable); parentPlusExtTableNames = getQualifiedTableNames(parentPlusExtTables); childPlusExtTableNames = getQualifiedTableNames(childPlusExtTables); allReadColumnNames = getQualifiedColumnNames(allReadColumns); childReadColumnNames = getQualifiedColumnNames(childReadColumns); parentReadColumnNames = getQualifiedColumnNames(parentReadColumns); extendedMetadataIsBuilt = true; } } // Private methods private void buildInvisibleForeignKeys(final Connection connection) throws SQLException { final PreparedStatement statement = connection.prepareStatement(getSqlColumnsQuery()); ResultSet resultSet = null; try { for (final TableMetaData table : tables) { if (!table.isParent()) { statement.setString(1, isDbMetaDataUpperCase() ? table.getDatabaseName().toUpperCase() : table.getDatabaseName()); statement.setString(2, isDbMetaDataUpperCase() ? table.getTableName().toUpperCase() : table.getTableName()); resultSet = statement.executeQuery(); while (resultSet.next()) { final String columnName = resultSet.getString(1); if (!table.getColumns().containsKey(columnName)) { TableMetaData mainTable; switch (table.getTableRole()) { case ChildExtension: mainTable = childTable; break; default: // Child, ParentExtension, Unknown mainTable = parentTable; } // Look for a pk on the main table with the same name for (final ColumnMetaData pk : mainTable.getPrimaryKeys()) { if (columnName.equals(pk.getColumnName())) { final ColumnMetaData fkColumn = Factory.getColumnMetaData(); fkColumn.setAttributes( table.getDatabaseName(), table.getQualifiedTableName(), table.getTableName(), table.getTableRole(), columnName, getQualifiedColumnName(table.getTableName(), table.getQualifiedTableName(), false, columnName), pk.getColumnLabel(), getQualifiedColumnLabel(table.getTableName(), table.getQualifiedTableName(), false, pk.getColumnLabel()), resultSet.getString(2)); ((TableMetaDataImpl) table).addColumn(fkColumn); } } } } } } } catch (final SQLException exception) { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } throw exception; } } private void buildJoinTableMetadata(final Connection connection) throws SQLException { // Join table could have been identified in buildTablesAndColumns(), but not always
final Table joinDef = SqlResourceDefinitionUtils.getTable(definition, TableRole.Join);
4
alexmojaki/boxes
src/main/java/alex/mojaki/boxes/View.java
[ "public class BoxParticipantException extends RuntimeException {\n\n public Box<ParticipationDetails> details = box();\n\n public BoxParticipantException(String message, Exception cause) {\n super(message, cause);\n }\n\n public BoxParticipantException withDetails(ParticipationDetails details) {\n this.details.set(details);\n return this;\n }\n}", "public interface ChangeMiddleware<T> {\n\n /**\n * Return the given {@code currentValue} or some transformation of it.\n * Called during {@link PowerBox#set(Object)} for zero or more of these objects before applying the list of\n * {@link ChangeObserver}s.\n *\n * @param box the {@code PowerBox} whose value is being {@code set}.\n * @param originalValue the value the box contained before it was set.\n * @param currentValue for the first middleware in the sequence, this is the same as {@code requestedValue}.\n * For subsequent middleware, this is the return value of the previous middleware.\n * @param requestedValue the parameter of {@link PowerBox#set(Object)}.\n * @return the final value to be stored in the box and the parameter {@code finalValue} in the\n * {@link ChangeObserver#onChange(PowerBox, Object, Object, Object)} method for any {@code ChangeObserver}s this\n * box has.\n */\n T onChange(PowerBox<T> box, T originalValue, T currentValue, T requestedValue);\n}", "public interface GetMiddleware<T> {\n\n /**\n * Return the given {@code currentValue} or some transformation of it.\n * Called during {@link PowerBox#get()} for zero or more of these objects before applying the list of\n * {@link GetObserver}s.\n *\n * @param box the {@code PowerBox} whose value is being obtained by {@code get}.\n * @param originalValue the value the box contained before any middleware was applied.\n * @param currentValue for the first middleware in the sequence, this is the same as {@code originalValue}.\n * For subsequent middleware, this is the return value of the previous middleware.\n * @return the final value to be returned to the user and the parameter {@code finalValue} in the\n * {@link GetObserver#onGet(PowerBox, Object, Object)} method for any {@code GetObserver}s this\n * box has.\n */\n T onGet(PowerBox<T> box, T originalValue, T currentValue);\n}", "public interface ChangeObserver<T> {\n\n /**\n * Take some action based on the values involved in the change.\n * Called when the value of a {@code PowerBox} changes for zero or more of these objects.\n *\n * @param box the {@code PowerBox} whose value changed.\n * @param originalValue the value the box contained before the change.\n * @param finalValue the new value the box will have. In the case of {@link PowerBox#set(Object)},\n * this is the final result of applying all {@link ChangeMiddleware}.\n * @param requestedValue the parameter of {@link PowerBox#set(Object)}, or just the same as {@code originalValue}\n * in the case of a mutation to a {@code WrapperBox}.\n */\n void onChange(PowerBox<T> box, T originalValue, T finalValue, T requestedValue);\n}", "public abstract class TargetedChangeObserver<T, V> implements ChangeObserver<T> {\n\n private final WeakConcurrentMultiMap<PowerBox, V> map = new WeakConcurrentMultiMap<PowerBox, V>();\n\n @Override\n public void onChange(PowerBox<T> box, T originalValue, T finalValue, T requestedValue) {\n List<V> targets = map.get(box);\n int size = targets.size();\n // Don't want to create an iterator object to iterate through a tiny (likely singleton) list\n //noinspection ForLoopReplaceableByForEach\n for (int i = 0; i < size; i++) {\n onChange(box, originalValue, finalValue, requestedValue, targets.get(i));\n }\n }\n\n /**\n * Create an association between {@code box} and {@code target}, and add this observer to {@code box}.\n * When {@code box} changes, this observer's special\n * {@link TargetedChangeObserver#onChange(PowerBox, Object, Object, Object, Object)} method will be called\n * with {@code target} as the last argument.\n */\n public void register(PowerBox<T> box, V target) {\n map.put(box, target);\n box.addChangeObserver(this);\n }\n\n /**\n * Similar to the normal {@link ChangeObserver#onChange(PowerBox, Object, Object, Object)} method, except that\n * when {@code box} changes, this method is called once for every value of {@code target} that was associated\n * with {@code box} via the {@link TargetedChangeObserver#register(PowerBox, Object)} method.\n */\n public abstract void onChange(PowerBox<T> box, T originalValue, T finalValue, T requestedValue, V target);\n\n}", "public interface GetObserver<T> {\n\n /**\n * Take some action based on the values involved in the get.\n * Called during {@link PowerBox#get()} for zero or more of these objects\n *\n * @param box the {@code PowerBox} whose value is being obtained.\n * @param originalValue the value the box contained before the change.\n * @param finalValue the new value the box will have.\n * This is the final result of applying all {@link GetMiddleware}.\n */\n void onGet(PowerBox<T> box, T originalValue, T finalValue);\n}" ]
import alex.mojaki.boxes.exceptions.BoxParticipantException; import alex.mojaki.boxes.middleware.change.ChangeMiddleware; import alex.mojaki.boxes.middleware.get.GetMiddleware; import alex.mojaki.boxes.observers.change.ChangeObserver; import alex.mojaki.boxes.observers.change.TargetedChangeObserver; import alex.mojaki.boxes.observers.get.GetObserver;
package alex.mojaki.boxes; /** * A {@link PowerBox} whose value is calculated based on the values of other {@code PowerBox}es and knows when those * boxes change, allowing it to safely cache its own value to save computation and notify {@link ChangeObserver}s * that the result of its calculation is now different. * <p> * Note that views have some base performance overhead and writing your code to use a view for caching wherever * possible will not necessarily speed up your program - it may even slow it down. You should use views for caching * only when the computation is slow or expensive. * <p> * The {@link PowerBox#set(Object)} method and the use of {@link ChangeMiddleware} are unsupported. * * @param <T> the type of the calculated value */ public abstract class View<T> extends CommonBox<T> { private static final TargetedChangeObserver<Object, View> TARGETED_CHANGE_OBSERVER = new TargetedChangeObserver<Object, View>() { @Override public void onChange(PowerBox box, Object originalValue, Object finalValue, Object requestedValue, View target) { target.update(); } }; private boolean cacheValid = false; /** * Construct a view with the given family and whose value depends on the given boxes */ public View(BoxFamily family, PowerBox... boxes) { super(family); construct(boxes); } /** * Construct a view by looking up a family with the given class and name and whose value depends on the given boxes. */ public View(Class<?> clazz, String name, PowerBox... boxes) { super(clazz, name); construct(boxes); } private void construct(PowerBox[] boxes) { addBoxes(boxes); getFamily().getChangeMiddlewares().disable(); } /** * Indicate that the value of this view depends on the given boxes in addition to any previously added boxes or * boxes given in the constructor. */ public void addBoxes(PowerBox... boxes) { for (PowerBox box : boxes) { //noinspection unchecked TARGETED_CHANGE_OBSERVER.register(box, this); } } /** * Indicate that one of the boxes that this view depends on has changed in value, meaning that this view has likely * changed its value as well. If this view has any {@code ChangeObserver}s they will be notified immediately * with a new value from the {@link View#calculate()} method. * Since there is no middleware involved, the last two parameters of * {@link ChangeObserver#onChange(PowerBox, Object, Object, Object)} will be the same. * If a new value is successfully calculated, the cache will now be valid. Otherwise it will now be invalid. */ private void update() { if (!getFamily().getChangeObservers().isEmpty()) { T oldValue = value; calculateAndCache(); try { notifyChangeObservers(oldValue, value, value); } catch (BoxParticipantException e) { value = oldValue; cacheValid = false; throw e; } } else { cacheValid = false; } } // @formatter:off /** * Return the value of this view as derived from the boxes it depends on. For the view to function properly, it is * essential that: * <ol> * <li>The result of this method is a deterministic function of the boxes the view depends on, meaning that: * <ol> * <li>The method does not depend on any other values of any kind, so add all appropriate boxes in * the constructor and/or the {@link View#addBoxes(PowerBox[])} * method and do not rely on any variables not found in boxes.</li> * <li>Separate calls to this method return the same results if the boxes haven't changed, i.e. * there is no randomness or internal, invisible state involved.</li> * </ol></li> * <li>The values of the boxes cannot change without notifying their {@code ChangeObserver}s * and thus this view. If the {@code set} method is called on a box its observers will certainly be * notified, so it remains to ensure that the state of an object cannot change in such a way that * the result of this method would change without notifying observers. Thus each box must either: * <ol> * <li>Contain an immutable type such as {@code Integer} or {@code String}, or</li> * <li>Intercept any calls that change the value of the box with respect to this method, typically * by being a {@link WrapperBox}.</li> * </ol></li> * </ol> * <p> * When {@link PowerBox#get()} is called, {@code calculate()} will be called only if a box has changed its value * since the previous call to {@code calculate()}. In addition, if the view has any {@code ChangeObserver}s added, * {@code calculate()} is called every time one of the boxes changes, i.e. the value of view might change. */ // @formatter:on public abstract T calculate(); @Override protected T rawGet() { if (cacheValid) { return value; } calculateAndCache(); return value; } private void calculateAndCache() { value = calculate(); cacheValid = true; } @Override public AbstractPowerBox<T> set(T value) { throw new UnsupportedOperationException("You cannot set a value on a view. It must be calculated."); } // Specifying the return type for chaining @Override
public View<T> addChangeObserver(ChangeObserver... observers) {
3
6thsolution/ApexNLP
english-nlp/src/main/java/com/sixthsolution/apex/nlp/english/DateDetector.java
[ "public class DateDetectionFilter extends ChunkDetectionFilter {\n @Override\n public boolean accept(Label label, TaggedWords taggedWords, int startIndex, int endIndex) {\n switch (label) {\n case FORMAL_DATE:\n case RELAX_DATE:\n case FOREVER_DATE:\n case GLOBAL_DATE:\n case RELATIVE_DATE:\n case LIMITED_DATE:\n case EXPLICIT_RELATIVE_DATE:\n return true;\n }\n return false;\n }\n}", "public enum Entity {\n TIME, DATE, LOCATION, NONE\n}", "public enum Label {\n NONE, DATE, TIME, LOCATION, TITLE,\n FIXED_TIME,\n RELATIVE_TIME,\n RANGE_TIME,\n /**\n * Formal dates are those in which the month, day, and year are represented as integers\n * separated by a common separator character. The year is optional and may proceed the month or\n * succeed the day of month. If a two-digit year is given, it must succeed the day of month.\n */\n FORMAL_DATE,\n RELAX_DATE,\n RELATIVE_DATE,\n EXPLICIT_RELATIVE_DATE,\n GLOBAL_DATE,\n FOREVER_DATE,\n LIMITED_DATE,\n DATE_RULES,\n RECURRENCE,\n\n\n}", "public abstract class ChunkDetectionFilter {\n\n public abstract boolean accept(Label label, TaggedWords taggedWords, int startIndex, int endIndex);\n}", "public abstract class ChunkDetector {\n\n protected final DfaState<Label> state;\n protected final List<? extends ChunkDetectionFilter> filters;\n\n public ChunkDetector() {\n filters = getFilters();\n state = createDFA();\n }\n\n private DfaState<Label> createDFA() {\n DfaBuilder<Label> builder = new DfaBuilder<>();\n for (Pair<Label, Pattern> pair : getPatterns()) {\n builder.addPattern(pair.second, pair.first);\n }\n return builder.build(null);\n }\n\n public ChunkedPart detect(TaggedWords taggedWords) {\n String sentence = convertTaggedWordsToCharSequence(taggedWords);\n StringMatcher matcher = new StringMatcher(sentence);\n Label result;\n while ((result = matcher.findNext(state)) != null) {\n int startIndex = matcher.getLastMatchStart();\n int endIndex = matcher.getLastMatchEnd();\n if (filters != null) {\n for (ChunkDetectionFilter filter : filters) {\n if (filter.accept(result, taggedWords, startIndex, endIndex)) {\n return createChunkedPart(taggedWords, startIndex, endIndex, result);\n }\n }\n } else {\n return createChunkedPart(taggedWords, startIndex, endIndex, result);\n }\n }\n return null;\n }\n\n private ChunkedPart createChunkedPart(TaggedWords taggedWords, int startIndex, int endIndex,\n Label label) {\n ChunkedPart chunkedPart = new ChunkedPart(getEntity(), label,\n taggedWords.newSubList(startIndex, endIndex));\n taggedWords.removeRange(startIndex, endIndex);\n return chunkedPart;\n }\n\n private String convertTaggedWordsToCharSequence(TaggedWords taggedWords) {\n StringBuilder sb = new StringBuilder();\n for (TaggedWord taggedWord : taggedWords) {\n Tag tag = getNearestTag(taggedWord.getTags());\n sb.append((char) tag.id);\n }\n return sb.toString();\n }\n\n private Tag getNearestTag(Tags tags) {\n TagValue tagValue = tags.getTagByEntity(getEntity());\n if (tagValue != null) {\n return tagValue.tag;\n }\n if (tags.containsTag(NUMBER)) {\n return Tag.NUMBER;\n }\n if (!tags.containsTag(NONE)) {\n return tags.get(0).tag;\n }\n return Tag.NONE;\n }\n\n protected abstract List<Pair<Label, Pattern>> getPatterns();\n\n protected abstract List<? extends ChunkDetectionFilter> getFilters();\n\n protected abstract Entity getEntity();\n\n public static Pair<Label, Pattern> newPattern(Label label, Pattern pattern) {\n return new Pair<>(label, pattern);\n }\n}", "public class Pair<F, S> {\n public final F first;\n public final S second;\n\n public Pair(F first, S second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public String toString() {\n return \"[\" + first + \",\" + second + \"]\";\n }\n}", "public enum Tag {\n NONE(97),\n NUMBER(98),\n PREPOSITION(99),\n RELATIVE_PREPOSITION(100),\n RELATIVE_SUFFIX(101),\n //LOCATION\n LOCATION_PREFIX(102),\n LOCATION_SUFFIX(103),\n LOCATION_NAME(137),\n //TIME\n TIME_PREFIX(104), //e.g. at, in ,the\n TIME_START_RANGE(105), //e.g. from\n TIME_RANGE(106),\n TIME_RELATIVE_PREFIX(107), //e.g. for\n TIME_RELATIVE(108), //e.g. morning\n TIME_RELATIVE_INDICATOR(109), //e.g. before,after\n TIME_HOUR(110), //e.g. hour\n TIME_MIN(111), //e.g. minutes\n TIME_SEC(112), //e.g. seconds\n TIME_MERIDIEM(113), //e.g am, pm\n TIME_SEPARATOR(114), //e.g :, .\n //DATE\n DATE_PREPOSITION(115),\n DATE_SEEKBY(116),\n DATE_START_RANGE(117),\n DATE_SUFFIX(118),\n DATE_DURATION_SUFFIX(119),\n DATE_SEPARATOR(120),\n WEEK_DAY(121),\n MONTH_NAME(122),\n SEASON(123),\n DATE_PREFIX(124),\n //RECURRENCE\n REC_WEEK_DAYS(125),\n NAMED_DATE(126),\n GLOBAL_PREPOSITION(127),\n DATE_RECURRENCE(128),\n DATE_RANGE(129),\n DATE_FOREVER_KEY(130),\n THE_PREFIX(131),\n DATE_BAND(132),\n YEAR_SEEK(133),\n MONTH_SEEK(134),\n WEEK_SEEK(135),\n DAY_SEEK(136),\n CURRENT(138);\n\n public int id;\n\n Tag(int id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return String.valueOf((char) id);\n }\n}", "public enum Label {\n NONE, DATE, TIME, LOCATION, TITLE,\n FIXED_TIME,\n RELATIVE_TIME,\n RANGE_TIME,\n /**\n * Formal dates are those in which the month, day, and year are represented as integers\n * separated by a common separator character. The year is optional and may proceed the month or\n * succeed the day of month. If a two-digit year is given, it must succeed the day of month.\n */\n FORMAL_DATE,\n RELAX_DATE,\n RELATIVE_DATE,\n EXPLICIT_RELATIVE_DATE,\n GLOBAL_DATE,\n FOREVER_DATE,\n LIMITED_DATE,\n DATE_RULES,\n RECURRENCE,\n\n\n}" ]
import com.nobigsoftware.dfalex.Pattern; import com.sixthsolution.apex.nlp.english.filter.DateDetectionFilter; import com.sixthsolution.apex.nlp.ner.Entity; import com.sixthsolution.apex.nlp.ner.Label; import com.sixthsolution.apex.nlp.ner.regex.ChunkDetectionFilter; import com.sixthsolution.apex.nlp.ner.regex.ChunkDetector; import com.sixthsolution.apex.nlp.util.Pair; import java.util.Arrays; import java.util.List; import static com.nobigsoftware.dfalex.Pattern.*; import static com.sixthsolution.apex.nlp.dict.Tag.*; import static com.sixthsolution.apex.nlp.ner.Entity.DATE; import static com.sixthsolution.apex.nlp.ner.Label.*;
private static Pattern limited_date() { return match(maybe(DATE_START_RANGE.toString()).then(maybe(anyOf(relax_date(), relative_date(), formal_date()))).then(DATE_RANGE.toString()).then(anyOf(relax_date(), relative_date(), formal_date()))); } /** * @return now, this year, today, current year, the year, ... */ private static Pattern year_part_current() { return match(anyOf(match(CURRENT.toString()), match(THE_PREFIX.toString())).then(DATE_SEEKBY.toString())); } /** * @return next year, 2001, the year before 2025, year after next year, year before year 2013, year, ... */ private static Pattern year_part() { return match(anyOf(match(RELATIVE_PREPOSITION.toString()).then(DATE_SEEKBY.toString()), maybe(THE_PREFIX.toString()).thenMaybe(DATE_SEEKBY.toString()).then(NUMBER.toString()), year_part_relative(), year_part_current(), match(DATE_SEEKBY.toString()))); } private static Pattern year_part_exact() { return match(anyOf(match(RELATIVE_PREPOSITION.toString()).thenMaybe(DATE_SEEKBY.toString()), maybe(THE_PREFIX.toString()) .thenMaybe(DATE_SEEKBY.toString()).then(NUMBER.toString()), year_part_current(), match(DATE_SEEKBY.toString()))); } /** * @return year after next, after 2001, year before 2025, three years after next year, the year before year 2013, 4 years from today */ private static Pattern year_part_relative() { return match(maybe(anyOf(match(NUMBER.toString()), match(THE_PREFIX.toString()))).then(DATE_SEEKBY.toString()) .then(anyOf(match(GLOBAL_PREPOSITION.toString()), match(DATE_START_RANGE.toString()))).then(year_part_exact())); } /** * @return now, this month, today, current month, the month, ... */ private static Pattern month_part_current() { return match(anyOf(match(CURRENT.toString()), match(THE_PREFIX.toString()).then(DATE_SEEKBY.toString()))); } private static Pattern month_part_explicit() { return match(anyOf(match(NUMBER.toString()).then(DATE_SEEKBY.toString()), match(MONTH_NAME.toString())).thenMaybe(match(DATE_PREFIX.toString()).then(year_part()))); } static Pattern month_part_exact() { return match(anyOf(month_part_current(), maybe(THE_PREFIX.toString()).then(anyOf(month_part_explicit())))); } /** * @return two months from june(month part), 3rd month after today, 3rd april from now, ... */ private static Pattern month_part_relative() { return match(NUMBER.toString()).then(anyOf(match(DATE_SEEKBY.toString()), match(MONTH_NAME.toString())) .thenMaybe(anyOf(match(GLOBAL_PREPOSITION.toString()), match(DATE_START_RANGE.toString())).then(month_part_exact()))); } static Pattern month_part() { return match(anyOf(match(RELATIVE_PREPOSITION.toString()).then(DATE_SEEKBY.toString()), month_part_current(), maybe(THE_PREFIX.toString()).then(anyOf(month_part_explicit(), month_part_relative())))); } /** * @return now, this week, today, current week, the week, ... */ private static Pattern week_part_current() { return match(anyOf(match(CURRENT.toString()), match(THE_PREFIX.toString()).then(DATE_SEEKBY.toString()))); } private static Pattern week_part_explicit() { return match(NUMBER.toString()).then(DATE_SEEKBY.toString()).then(DATE_PREFIX.toString()).then(anyOf(year_part(), month_part())); } private static Pattern week_part_exact() { return maybe(THE_PREFIX.toString()).then(anyOf(week_part_current(), week_part_explicit())); } /** * @return two weeks from first week of next year(week part), 3rd week after today, ... */ private static Pattern week_part_relative() { return match(NUMBER.toString()).then(anyOf(match(GLOBAL_PREPOSITION.toString()), match(DATE_START_RANGE.toString()))).then(week_part_exact()); } private static Pattern week_part() { return maybe(THE_PREFIX.toString()).then(anyOf(week_part_current(), week_part_explicit(), week_part_relative())); } private static Pattern start_with_number() { return maybe(THE_PREFIX.toString()).then(NUMBER.toString()).thenMaybe(DATE_SUFFIX.toString()).then(DATE_SEEKBY.toString()) .then(DATE_PREFIX.toString()).then(anyOf(year_part(), month_part(), week_part())); } private static Pattern start_with_day_band() { return match(DATE_BAND.toString()).thenMaybe(anyOf(match(DATE_SEEKBY.toString()), match(WEEK_DAY.toString()), match(MONTH_NAME.toString()))) .then(DATE_PREFIX.toString()).then(anyOf(year_part(), month_part(), week_part())); } private static Pattern start_with_day_of_week() { return match(WEEK_DAY.toString()).then(DATE_PREFIX.toString()).then(anyOf(week_part(), year_part(), month_part())); } private static Pattern explicit_relative_date() { return match(anyOf(start_with_day_band(), start_with_day_of_week(), start_with_number())); } @Override protected List<Pair<Label, Pattern>> getPatterns() { return Arrays.asList( newPattern(FORMAL_DATE, formal_date()) , newPattern(RELAX_DATE, relax_date()) , newPattern(RELATIVE_DATE, relative_date()) ,newPattern(EXPLICIT_RELATIVE_DATE,explicit_relative_date()) , newPattern(GLOBAL_DATE, global_date()) , newPattern(FOREVER_DATE, forever_date()) , newPattern(LIMITED_DATE, limited_date()) ); } @Override
protected List<? extends ChunkDetectionFilter> getFilters() {
3
idega/com.idega.documentmanager
src/java/com/idega/documentmanager/component/impl/FormComponentMultiUploadDescriptionImpl.java
[ "public interface ComponentMultiUploadDescription extends Component {\n \n public abstract PropertiesMultiUploadDescription getProperties();\n \n}", "public interface PropertiesMultiUploadDescription extends PropertiesComponent{\n \n public abstract LocalizedStringBean getRemoveButtonLabel();\n\n public abstract void setRemoveButtonLabel(LocalizedStringBean removeButtonLabel);\n \n public abstract LocalizedStringBean getAddButtonLabel();\n\n public abstract void setAddButtonLabel(LocalizedStringBean addButtonLabel);\n \n public abstract LocalizedStringBean getDescriptionLabel();\n\n public abstract void setDescriptionLabel(LocalizedStringBean addButtonLabel);\n \n public abstract LocalizedStringBean getUploadingFileDescription();\n\n public abstract void setUploadingFileDescription(LocalizedStringBean addButtonLabel);\n \n \n}", "public class ComponentPropertiesMultiUploadDescription extends ComponentProperties implements PropertiesMultiUploadDescription{\n \n private LocalizedStringBean addButtonLabel;\n private LocalizedStringBean removeButtonLabel;\n private LocalizedStringBean descriptionLabel;\n private LocalizedStringBean uploadingFileDesc;\n \n public LocalizedStringBean getAddButtonLabel() {\n\treturn addButtonLabel;\n }\n\n public void setAddButtonLabel(LocalizedStringBean addButtonLabel) {\n\tthis.addButtonLabel = addButtonLabel;\n\tcomponent.update(ConstUpdateType.ADD_BUTTON_LABEL);\n }\n\n public LocalizedStringBean getRemoveButtonLabel() {\n\treturn removeButtonLabel;\n }\n\n public void setRemoveButtonLabel(LocalizedStringBean removeButtonLabel) {\n\tthis.removeButtonLabel = removeButtonLabel;\n\tcomponent.update(ConstUpdateType.REMOVE_BUTTON_LABEL);\n }\n \n public void setPlainRemoveButtonLabel(LocalizedStringBean removeButtonLabel) {\n\tthis.removeButtonLabel = removeButtonLabel;\n\t\n }\n \n public void setPlainAddButtonLabel(LocalizedStringBean addButtonLabel) {\n\tthis.addButtonLabel = addButtonLabel;\n }\n \n public void setPlainDescriptionButtonLabel(LocalizedStringBean descriptionButtonLabel) {\n\tthis.descriptionLabel = descriptionButtonLabel;\n\t\n }\n \n public LocalizedStringBean getDescriptionLabel() {\n\treturn descriptionLabel;\n }\n\n public void setDescriptionLabel(LocalizedStringBean descriptionButtonLabel) {\n\tthis.descriptionLabel = descriptionButtonLabel;\n\tcomponent.update(ConstUpdateType.DESCRIPTION_BUTTON_LABEL);\n\t\n }\n \n public LocalizedStringBean getUploadingFileDescription() {\n\treturn uploadingFileDesc;\n }\n\n public void setUploadingFileDescription(LocalizedStringBean uploadingFileDesc) {\n\tthis.uploadingFileDesc = uploadingFileDesc;\n\tcomponent.update(ConstUpdateType.UPLOADING_FILE_DESC);\n }\n \n public void setPlainUploadingFileDescription(LocalizedStringBean uploadingFileDesc) {\n\tthis.uploadingFileDesc = uploadingFileDesc;\n }\n \n\n}", "public enum ConstUpdateType {\n\t\n\tLABEL,\n\tCONSTRAINT_REQUIRED,\n\tERROR_MSG,\n\tP3P_TYPE,\n\tITEMSET,\n\tEXTERNAL_DATA_SRC,\n\tTHANKYOU_TEXT,\n\tAUTOFILL_KEY,\n\tHELP_TEXT,\n\tREAD_ONLY,\n\tTEXT,\n\tSTEPS_VISUALIZATION_USED,\n\tSUBMISSION_ACTION,\n\tVARIABLE_NAME,\n\tBUTTON_REFER_TO_ACTION,\n\tDATA_SRC_USED,\n\tADD_BUTTON_LABEL,\n\tREMOVE_BUTTON_LABEL,\n\tDESCRIPTION_BUTTON_LABEL,\n\tUPLOADING_FILE_DESC,\n\tVALIDATION;\n}", "public interface XFormsManagerMultiUploadDescription extends XFormsManager{\n\t\n\tpublic abstract void loadXFormsComponentByTypeFromComponentsXForm(FormComponent component,\n\t\t\tString componentType) throws NullPointerException;\n\n\tpublic abstract void addComponentToDocument(FormComponent component);\n\t\n\tpublic abstract LocalizedStringBean getRemoveButtonLabel(FormComponent component);\n\t\n\tpublic abstract LocalizedStringBean getAddButtonLabel(FormComponent component);\n\t\n\tpublic abstract LocalizedStringBean getDescriptionButtonLabel(FormComponent component);\n\t\n\tpublic abstract LocalizedStringBean getUploadingFileDescription(FormComponent component);\n\t\n\tpublic abstract void update(FormComponent component, ConstUpdateType what);\n}", "public class FormManagerUtil {\n\t\n\tpublic static final String model_tag = \"xf:model\";\n\tpublic static final String label_tag = \"xf:label\";\n\tpublic static final String alert_tag = \"xf:alert\";\n\tpublic static final String help_tag = \"xf:help\";\n\tpublic static final String head_tag = \"head\";\n\tpublic static final String id_att = \"id\";\n\tpublic static final String at_att = \"at\";\n\tpublic static final String type_att = \"type\";\n\tpublic static final String slash = \"/\";\n\tpublic static final String fb_ = \"fb_\";\n\tpublic static final String loc_ref_part1 = \"instance('localized_strings')/\";\n\tpublic static final String loc_ref_part2 = \"[@lang=instance('localized_strings')/current_language]\";\n\tpublic static final String inst_start = \"instance('\";\n\tpublic static final String inst_end = \"')\";\n\tpublic static final String data_mod = \"data_model\";\n\tpublic static final String loc_tag = \"localized_strings\";\n\tpublic static final String output_tag = \"xf:output\";\n\tpublic static final String ref_s_att = \"ref\";\n\tpublic static final String lang_att = \"lang\";\n\tpublic static final String CTID = XFormsUtil.CTID;\n\tpublic static final String localized_entries = \"localizedEntries\";\n\tpublic static final String body_tag = \"body\";\n\tpublic static final String bind_att = \"bind\";\n\tpublic static final String bind_tag = \"xf:bind\";\n\tpublic static final String name_att = \"name\";\n\tpublic static final String schema_tag = \"xs:schema\";\n\tpublic static final String form_id = \"form_id\";\n\tpublic static final String title_tag = \"title\";\n\tpublic static final String nodeset_att = \"nodeset\";\n\tpublic static final String group_tag = \"xf:group\";\n\tpublic static final String switch_tag = \"xf:switch\";\n//\tTODO enabled xf:case and xf:switch\n\tpublic static final String case_tag = \"xf:case\";\n\tpublic static final String idegans_switch_tag = \"idega:switch\";\n\tpublic static final String idegans_case_tag = \"idega:case\";\n\tpublic static final String submit_tag = \"xf:submit\";\n\tpublic static final String itemset_tag = \"xf:itemset\";\n\tpublic static final String item_tag = \"xf:item\";\n\tpublic static final String model_att = \"model\";\n\tpublic static final String src_att = \"src\";\n\tpublic static final String context_att_pref = \"context:\";\n\tpublic static final String item_label_tag = \"itemLabel\";\n\tpublic static final String item_value_tag = \"itemValue\";\n\tpublic static final String localized_entries_tag = \"localizedEntries\";\n\tpublic static final String default_language_tag = \"default_language\";\n\tpublic static final String current_language_tag = \"current_language\";\n\tpublic static final String form_id_tag = \"form_id\";\n\tpublic static final String submission_tag = \"xf:submission\";\n\tpublic static final String page_tag = \"page\";\n\tpublic static final String toggle_tag = \"xf:toggle\";\n\tpublic static final String number_att = \"number\";\n\tpublic static final String case_att = \"case\";\n\tpublic static final String p3ptype_att = \"p3ptype\";\n\tpublic static final String instance_tag = \"xf:instance\";\n\tpublic static final String setvalue_tag = \"xf:setvalue\";\n\tpublic static final String div_tag = \"div\";\n\tpublic static final String trigger_tag = \"xf:trigger\";\n\tpublic static final String preview = \"preview\";\n\tpublic static final String component_tag = \"component\";\n\tpublic static final String component_id_att = \"component_id\";\n\tpublic static final String autofill_model_id = \"x-autofill-model\";\n\tpublic static final String xmlns_att = \"xmlns\";\n\tpublic static final String relevant_att = \"relevant\";\n\tpublic static final String autofill_instance_ending = \"_autofill-instance\";\n\tpublic static final String autofill_setvalue_ending = \"-autofill-setvalue\";\n\tpublic static final String value_att = \"value\";\n\tpublic static final String autofill_key_prefix = \"fb-afk-\";\n\tpublic static final String refresh_tag = \"xf:refresh\";\n\tpublic static final String sections_visualization_id = \"sections_visualization\";\n\tpublic static final String sections_visualization_instance_id = \"sections_visualization_instance\";\n\tpublic static final String section_item = \"section_item\";\n\tpublic static final String sections_visualization_instance_item = \"sections_visualization_instance_item\";\n\tpublic static final String sections_visualization_item = \"sections_visualization_item\";\n\tpublic static final String set_section_vis_cur = \"_set_section_vis_cur\";\n\tpublic static final String set_section_vis_rel = \"_set_section_vis_rel\";\n\tpublic static final String event_att = \"ev:event\";\n\tpublic static final String DOMActivate_att_val = \"DOMActivate\";\n\tpublic static final String xforms_namespace_uri = \"http://www.w3.org/2002/xforms\";\n\tpublic static final String event_namespace_uri = \"http://www.w3.org/2001/xml-events\";\n\tpublic static final String idega_namespace = \"http://idega.com/xforms\";\n\tpublic static final String mapping_att = \"mapping\";\n\tpublic static final String action_att = \"action\";\n\tpublic static final String required_att = \"required\";\n\tpublic static final String readonly_att = \"readonly\";\n\tpublic static final String xpath_true = \"true()\";\n\tpublic static final String true_string = \"true\";\n\tpublic static final String false_string = \"false\";\n\tpublic static final String xpath_false = \"false()\";\n\tpublic static final String datatype_tag = \"datatype\";\n\tpublic static final String accessSupport_att = \"accessSupport\";\n\tpublic static final String submission_model = \"submission_model\";\n\tpublic static final String nodeTypeAtt = \"nodeType\";\n\tpublic static final String controlInstanceID = \"control-instance\";\n\t\n\tprivate static final String line_sep = \"line.separator\";\n\tprivate static final String xml_mediatype = \"text/html\";\n\tprivate static final String utf_8_encoding = \"UTF-8\";\n\t\n\tprivate static OutputFormat output_format;\n\tprivate static Pattern non_xml_pattern = Pattern.compile(\"[a-zA-Z0-9{-}{_}]\");\n\t\n\t\n\tprivate static XPathUtil formInstanceModelElementXPath = new XPathUtil(\".//xf:model[xf:instance/@id='data-instance']\");\n\tprivate static XPathUtil defaultFormModelElementXPath = new XPathUtil(\".//xf:model\");\n\tprivate static XPathUtil formModelElementXPath = new XPathUtil(\".//xf:model[@id=$modelId]\");\n\tprivate static XPathUtil formSubmissionInstanceElementXPath = new XPathUtil(\".//xf:instance[@id='data-instance']\");\n\tprivate static XPathUtil instanceElementXPath = new XPathUtil(\".//xf:instance\");\n\tprivate static XPathUtil submissionElementXPath = new XPathUtil(\".//xf:submission[@id='submit_data_submission']\");\n\tprivate static XPathUtil formTitleOutputElementXPath = new XPathUtil(\".//h:title/xf:output\");\n\tprivate static XPathUtil instanceElementByIdXPath = new XPathUtil(\".//xf:instance[@id=$instanceId]\");\n\tprivate static XPathUtil formSubmissionInstanceDataElementXPath = new XPathUtil(\".//xf:instance[@id='data-instance']/data\");\n\tprivate static XPathUtil localizedStringElementXPath = new XPathUtil(\".//xf:instance[@id='localized_strings']/localized_strings\");\n\tprivate static XPathUtil elementByIdXPath = new XPathUtil(\".//*[@id=$id]\");\n\tprivate static XPathUtil elementsContainingAttributeXPath = new XPathUtil(\".//*[($elementName = '*' or name(.) = $elementName) and ($attributeName = '*' or attribute::*[name(.) = $attributeName])]\");\n\tprivate static XPathUtil localizaionSetValueElement = new XPathUtil(\".//xf:setvalue[@model='data_model']\");\n\tprivate static XPathUtil formErrorMessageXPath = new XPathUtil(\".//xf:action[@id='submission-error']/xf:message\");\n\tprivate static XPathUtil formParamsXPath = new XPathUtil(\".//*[@nodeType='formParams']\");\n\t\n\tprivate final static String elementNameVariable = \"elementName\";\n\tprivate final static String attributeNameVariable = \"attributeName\";\n\t\n\tprivate FormManagerUtil() { }\n\t\n\t/**\n\t * \n\t * @param doc - document, to search for an element\n\t * @param start_tag - where to start. Could be just null, then document root element is taken.\n\t * @param id_value\n\t * @return - <b>reference</b> to element in document\n\t */\n\tpublic static Element getElementByIdFromDocument(Document doc, String start_tag, String id_value) {\n\t\t\n\t\treturn getElementByAttributeFromDocument(doc, start_tag, id_att, id_value);\n\t}\n\t\n\t/**\n\t * \n\t * @param doc - document, to search for an element\n\t * @param start_tag - where to start. Could be just null, then document root element is taken.\n\t * @param attribute_name - what name attribute should be searched for\n\t * @param attribute_value\n\t * @return - Reference to element in document\n\t */\n\tpublic static Element getElementByAttributeFromDocument(Document doc, String start_tag, String attribute_name, String attribute_value) {\n\t\t\n\t\tElement start_element;\n\t\t\n\t\tif(start_tag != null)\n\t\t\tstart_element = (Element)doc.getElementsByTagName(start_tag).item(0);\n\t\telse\n\t\t\tstart_element = doc.getDocumentElement();\n\t\t\n\t\treturn DOMUtil.getElementByAttributeValue(start_element, CoreConstants.STAR, attribute_name, attribute_value);\n\t}\n\t\n\tpublic static void insertNodesetElement(Document form_xforms, Element new_nodeset_element) {\n\t\t\n\t\tElement container = \n\t\t\t(Element)((Element)form_xforms\n\t\t\t\t\t.getElementsByTagName(instance_tag).item(0))\n\t\t\t\t\t.getElementsByTagName(\"data\").item(0);\n\t\tcontainer.appendChild(new_nodeset_element);\n\t}\n\t\n\t/**\n\t * Puts localized text on element. Localization is saved on the xforms document.\n\t * \n\t * @param key - new localization message key\n\t * @param oldKey - old key, if provided, is used for replacing with new_key\n\t * @param element - element, to change or put localization message\n\t * @param xform - xforms document\n\t * @param localizedStr - localized message\n\t * @throws NullPointerException - something necessary not provided\n\t */\n\tpublic static void putLocalizedText(String key, String oldKey, Element element, Document xform, LocalizedStringBean localizedStr) throws NullPointerException {\n\t\n\t\tString ref = element.getAttribute(ref_s_att);\n\t\t\n\t\tif(FormManagerUtil.isEmpty(ref) && FormManagerUtil.isEmpty(key))\n\t\t\tthrow new NullPointerException(\"Localization to element not initialized and key for new localization string not presented.\");\n\t\t\n\t\tif(key != null) {\n//\t\t\tcreating new key\n\t\t\t\n\t\t\tref = new StringBuffer(loc_ref_part1)\n\t\t\t.append(key)\n\t\t\t.append(loc_ref_part2)\n\t\t\t.toString();\n\t\t\t\n\t\t\telement.setAttribute(ref_s_att, ref);\n\t\t\t\n\t\t} else if(isRefFormCorrect(ref)) {\n//\t\t\tget key from ref\n\t\t\tkey = getKeyFromRef(ref);\n\t\t\t\n\t\t} else\n\t\t\tthrow new NullPointerException(\"Ref and key not specified or ref has incorrect format. Ref: \"+ref);\n\t\t\n\t\tElement localizationStringsElement = FormManagerUtil.getLocalizedStringElement(xform);\n\t\t\n\t\tif(oldKey != null) {\n\t\t\t\n\t\t\tNodeList oldLocalizationTags = localizationStringsElement.getElementsByTagName(oldKey);\n\t\t\t\n//\t\t\tfind and rename those elements\n\t\t\tfor (int i = 0; i < oldLocalizationTags.getLength(); i++) {\n\t\t\t\t\n\t\t\t\tElement localizationTag = (Element)oldLocalizationTags.item(i);\n\t\t\t\txform.renameNode(localizationTag, localizationTag.getNamespaceURI(), key);\n\t\t\t}\n\t\t}\n\t\t\n\t\tNodeList localizationTags = localizationStringsElement.getElementsByTagName(key);\n\t\t\n\t\tList<String> locales = new ArrayList<String>();\n\t\t\n\t\tfor (Locale locale : localizedStr.getLanguagesKeySet())\n\t\t\tlocales.add(locale.toString());\n\t\t\n\t\t\n//\t\tremoving elements that correspond to locale, which we don't need (anymore)\n\t\tList<Node> nodesToRemove = new ArrayList<Node>();\n\t\t\n\t\tfor (int i = 0; i < localizationTags.getLength(); i++) {\n\t\t\t\n\t\t\tElement localizationTag = (Element)localizationTags.item(i);\n\t\t\t\n\t\t\tif(!locales.contains(localizationTag.getAttribute(lang_att)))\n\t\t\t\tnodesToRemove.add(localizationTag);\n\t\t}\n\t\t\n\t\tfor (Node node : nodesToRemove)\n\t\t\tnode.getParentNode().removeChild(node);\n\t\t\n\t\tlocalizationTags = localizationStringsElement.getElementsByTagName(key);\n\t\t\n\t\tfor (Locale locale : localizedStr.getLanguagesKeySet()) {\n\t\t\t\n\t\t\tboolean valueSet = false;\n\t\t\t\n\t\t\tif(localizationTags != null) {\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < localizationTags.getLength(); i++) {\n\t\t\t\t\t\n\t\t\t\t\tElement localizationTag = (Element)localizationTags.item(i);\n\t\t\t\t\t\n\t\t\t\t\tif(localizationTag.getAttribute(lang_att).equals(locale.toString())) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(localizedStr.getString(locale) != null)\n\t\t\t\t\t\t\tsetElementsTextNodeValue(localizationTag, localizedStr.getString(locale));\n\t\t\t\t\t\t\n\t\t\t\t\t\tvalueSet = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(localizationTags == null || !valueSet) {\n\t\t\t\t\n//\t\t\t\tcreate new localization element\n\t\t\t\tElement localizationElement = xform.createElement(key);\n\t\t\t\tlocalizationElement.setAttribute(lang_att, locale.toString());\n\t\t\t\tlocalizationElement.setTextContent(localizedStr.getString(locale) == null ? CoreConstants.EMPTY : localizedStr.getString(locale));\n\t\t\t\tlocalizationStringsElement.appendChild(localizationElement);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static String getComponentLocalizationKey(String componentId, String localizationKey) {\n\t\t\n\t\tif(!isLocalizationKeyCorrect(localizationKey))\n\t\t\treturn null;\n\t\t\n\t\treturn new StringBuilder(componentId)\n\t\t.append(localizationKey.contains(CoreConstants.DOT) ? localizationKey.substring(localizationKey.lastIndexOf(CoreConstants.DOT)) : CoreConstants.EMPTY)\n\t\t.toString();\n\t}\n\t\n\tpublic static String getKeyFromRef(String ref) {\n\t\treturn ref.substring(ref.indexOf(slash)+1, ref.indexOf(\"[\"));\n\t}\n\t\n\tpublic static boolean isRefFormCorrect(String ref) {\n\n\t\treturn ref != null && ref.startsWith(loc_ref_part1) && ref.endsWith(loc_ref_part2) && !ref.contains(CoreConstants.SPACE); \n\t}\n\t\n\tpublic static LocalizedStringBean getLocalizedStrings(String key, Document xformsDoc) {\n\n\t\tElement locModel = getElementByIdFromDocument(xformsDoc, head_tag, data_mod);\n\t\tElement locStrings = (Element)locModel.getElementsByTagName(loc_tag).item(0);\n\t\t\n\t\tNodeList keyElements = locStrings.getElementsByTagName(key);\n\t\tLocalizedStringBean locStrBean = new LocalizedStringBean();\n\t\t\n\t\tfor (int i = 0; i < keyElements.getLength(); i++) {\n\t\t\t\n\t\t\tElement keyElement = (Element)keyElements.item(i);\n\t\t\t\n\t\t\tString langCode = keyElement.getAttribute(lang_att);\n\t\t\t\n\t\t\tif(langCode != null) {\n\t\t\t\t\n\t\t\t\tString content = getElementsTextNodeValue(keyElement);\t\n\t\t\t\tlocStrBean.setString(LocaleUtil.getLocale(langCode), content == null ? CoreConstants.EMPTY : content);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn locStrBean;\n\t}\n\t\n\tpublic static LocalizedStringBean getLabelLocalizedStrings(Element component, Document xforms_doc) {\n\t\t\n\t\tNodeList labels = component.getElementsByTagName(FormManagerUtil.label_tag);\n\t\t\n\t\tif(labels == null || labels.getLength() == 0)\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tElement label = (Element)labels.item(0);\n\t\t\n\t\treturn getElementLocalizedStrings(label, xforms_doc);\n\t}\n\t\n\tpublic static LocalizedStringBean getElementLocalizedStrings(Element element, Document xforms_doc) {\n\t\t\n\t\t//DOMUtil.prettyPrintDOM(xforms_doc);\n\t\t\n\t\tString ref = element.getAttribute(FormManagerUtil.ref_s_att);\n\t\t\n\t\tif(!isRefFormCorrect(ref))\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tString key = getKeyFromRef(ref);\n\t\t\n\t\treturn getLocalizedStrings(key, xforms_doc);\n\t}\n\t\n\tpublic static void clearLocalizedMessagesFromDocument(Document doc) {\n\t\t\n\t\tElement loc_model = getElementByIdFromDocument(doc, head_tag, data_mod);\n\t\tElement loc_strings = (Element)loc_model.getElementsByTagName(loc_tag).item(0);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Element> loc_elements = DOMUtil.getChildElements(loc_strings);\n\t\t\n\t\tfor (Iterator<Element> iter = loc_elements.iterator(); iter.hasNext();)\n\t\t\tFormManagerUtil.removeTextNodes(iter.next());\n\t}\n\t\n\tpublic static Locale getDefaultFormLocale(Document xformsDoc) {\n\t\t\n\t\tElement locModel = getElementByIdFromDocument(xformsDoc, head_tag, data_mod);\n\t\tElement locStrings = (Element)locModel.getElementsByTagName(loc_tag).item(0);\n\t\tNodeList defaultLanguages = locStrings.getElementsByTagName(default_language_tag);\n\t\t\n\t\tString langCode = null;\n\t\t\n\t\tif(defaultLanguages != null && defaultLanguages.getLength() != 0) {\n\t\t\tlangCode = getElementsTextNodeValue(defaultLanguages.item(0));\n\t\t}\t\t\n\t\tif(langCode == null)\n\t\t\tlangCode = \"en\";\t\t\t\n\t\t\n\t\treturn LocaleUtil.getLocale(langCode);\n\t}\n\t\n\tpublic static void setCurrentFormLocale(Document form_xforms, Locale locale) {\n\t\tElement loc_model = getElementByIdFromDocument(form_xforms, head_tag, data_mod);\n\t\tElement loc_strings = (Element)loc_model.getElementsByTagName(loc_tag).item(0);\n\t\tNodeList current_language_node_list = loc_strings.getElementsByTagName(current_language_tag);\n\t\t\n\t\tif(current_language_node_list != null && current_language_node_list.getLength() != 0) {\n\t\t\t//String localeStr = locale.toString().toLowerCase();\n\t\t\tString localeStr = locale.toString();\n\t\t\tsetElementsTextNodeValue(current_language_node_list.item(0), localeStr);\n\t\t}\t\t\n\t}\n\t//TODO set default language tmp soliution\n\tpublic static void setDefaultFormLocale(Document form_xforms, Locale locale) {\n\t\tElement loc_model = getElementByIdFromDocument(form_xforms, head_tag, data_mod);\n\t\tElement loc_strings = (Element)loc_model.getElementsByTagName(loc_tag).item(0);\n\t\tNodeList current_language_node_list = loc_strings.getElementsByTagName(default_language_tag);\n\t\t\n\t\tif(current_language_node_list != null && current_language_node_list.getLength() != 0) {\n\t\t\t//String localeStr = locale.toString().toLowerCase();\n\t\t\tString localeStr = locale.toString();\n\t\t\tsetElementsTextNodeValue(current_language_node_list.item(0), localeStr);\n\t\t}\t\t\n\t}\n\t\n\tpublic static LocalizedStringBean getErrorLabelLocalizedStrings(Element component, Document xforms_doc) {\n\t\t\n\t\tNodeList alerts = component.getElementsByTagName(FormManagerUtil.alert_tag);\n\t\t\n\t\tif(alerts == null || alerts.getLength() == 0)\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tElement alert = (Element)alerts.item(0);\n\t\tString ref = alert.getAttribute(ref_s_att);\n\t\t\n\t\tif(!isRefFormCorrect(ref))\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tString key = getKeyFromRef(ref);\n\t\t\n\t\treturn getLocalizedStrings(key, xforms_doc);\n\t}\n\t\n\tpublic static LocalizedStringBean getHelpTextLocalizedStrings(Element component, Document xforms_doc) {\n\t\t\n\t\tNodeList helps = component.getElementsByTagName(FormManagerUtil.help_tag);\n\t\t\n\t\tif(helps == null || helps.getLength() == 0)\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tElement help = (Element)helps.item(0);\n\t\t\n\t\tXPathUtil outputXPUT= new XPathUtil(\".//xf:output[@helptype='helptext']\");\n\n\t\tElement output = (Element) outputXPUT.getNode(help);\n\t\t \n\t\tif (output == null || !output.hasAttribute(FormManagerUtil.ref_s_att))\n\t\t return new LocalizedStringBean();\n\t\t\t\n\t\tString ref = output.getAttribute(ref_s_att);\n\t\t\t\t\n\t\tif(!isRefFormCorrect(ref))\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tString key = getKeyFromRef(ref);\n\t\t\n\t\treturn getLocalizedStrings(key, xforms_doc);\n\t}\n\n\tpublic static LocalizedStringBean getValidationTextLocalizedStrings(Element component, Document xforms_doc) {\n\n\t \tNodeList helps = component.getElementsByTagName(FormManagerUtil.help_tag);\n\t\t\n\t\tif(helps == null || helps.getLength() == 0)\n\t\t return new LocalizedStringBean();\n\n\t\tElement help = (Element)helps.item(0);\n\t\t\n\t\tXPathUtil outputXPUT= new XPathUtil(\".//xf:output[@helptype='validationtext']\");\n\t\tElement output = (Element) outputXPUT.getNode(help);\n\t\t \n\t\tif (output == null || !output.hasAttribute(FormManagerUtil.ref_s_att))\n\t\t\treturn new LocalizedStringBean();\n\t\t\t\n\t\tString ref = output.getAttribute(ref_s_att);\n\t\t\n\t\tif(!isRefFormCorrect(ref))\n\t\t\treturn new LocalizedStringBean();\n\t\t\n\t\tString key = getKeyFromRef(ref);\n\t\t\n\t\treturn getLocalizedStrings(key, xforms_doc);\n\t}\n\t\n\tpublic static boolean isLocalizationKeyCorrect(String loc_key) {\n\t\treturn !isEmpty(loc_key) && !loc_key.contains(CoreConstants.SPACE);\n\t}\n\t\n\tpublic static String getElementsTextNodeValue(Node element) {\n\t\t\n\t\tNodeList children = element.getChildNodes();\n\t\tStringBuffer text_value = new StringBuffer();\n\t\t\n\t\tfor (int i = 0; i < children.getLength(); i++) {\n\t\t\t\n\t\t\tNode child = children.item(i);\n\t\t\t\n\t\t\tif(child != null && child.getNodeType() == Node.TEXT_NODE) {\n\t\t\t\tString node_value = child.getNodeValue();\n\t\t\t\t\n\t\t\t\tif(node_value != null && node_value.length() > 0)\n\t\t\t\t\ttext_value.append(node_value);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn text_value.toString();\n\t}\n\t\n\tpublic static void setElementsTextNodeValue(Node element, String value) {\n\t\t\n\t\tNodeList children = element.getChildNodes();\n\t\tList<Node> childs_to_remove = new ArrayList<Node>();\n\t\t\n\t\tfor (int i = 0; i < children.getLength(); i++) {\n\t\t\t\n\t\t\tNode child = children.item(i);\n\t\t\t\n\t\t\tif(child != null && child.getNodeType() == Node.TEXT_NODE)\n\t\t\t\tchilds_to_remove.add(child);\n\t\t}\n\t\t\n\t\tfor (Iterator<Node> iter = childs_to_remove.iterator(); iter.hasNext();)\n\t\t\telement.removeChild(iter.next());\n\t\t\n\t\tNode text_node = element.getOwnerDocument().createTextNode(value);\n\t\telement.appendChild(text_node);\n\t}\n\t\n\t/**\n\t * <p>\n\t * @param components_xml - components xml document, which passes the structure described:\n\t * <p>\n\t * optional document root name - form_components\n\t * </p>\n\t * <p>\n\t * Component is encapsulated into div tag, which contains tag id as component type.\n\t * Every component div container is child of root.\n\t * </p>\n\t * <p>\n\t * Component type starts with \"fbc_\"\n\t * </p>\n\t * <p>\n\t * example:\n\t * </p>\n\t * <p>\n\t * &lt;form_components&gt;<br />\n\t\t&lt;div class=\"input\" id=\"fbc_text\"&gt;<br />\n\t\t\t&lt;label class=\"label\" for=\"fbc_text-value\" id=\"fbc_text-label\"&gt;\t\t\tSingle Line Field\t\t&lt;/label&gt;<br />\n\t\t\t&lt;input class=\"value\" id=\"fbc_text-value\" name=\"d_fbc_text\"\ttype=\"text\" value=\"\" /&gt;<br />\n\t\t&lt;/div&gt;<br />\n\t&lt;/form_components&gt;\n\t * </p>\n\t * </p>\n\t * \n\t * IMPORTANT: types should be unique\n\t * \n\t * @return List of components types (Strings)\n\t */\n\tpublic static List<String> gatherAvailableComponentsTypes(Document components_xml) {\n\t\t\n\t\tElement root = components_xml.getDocumentElement();\n\t\t\n\t\tif(!root.hasChildNodes())\n\t\t\treturn null;\n\t\t\n\t\tNodeList children = root.getChildNodes();\n\t\tList<String> components_types = new ArrayList<String>();\n\t\t\n\t\tfor (int i = 0; i < children.getLength(); i++) {\n\t\t\t\n\t\t\tNode child = children.item(i);\n\t\t\t\n\t\t\tif(child.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\n\t\t\t\tString element_id = ((Element)child).getAttribute(FormManagerUtil.id_att);\n\t\t\t\t\n\t\t\t\tif(element_id != null && \n\t\t\t\t\t\telement_id.startsWith(FormManagerUtil.CTID) &&\n\t\t\t\t\t\t!components_types.contains(element_id)\n\t\t\t\t)\n\t\t\t\t\tcomponents_types.add(element_id);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn components_types;\n\t}\n\t\n\tpublic static Element getItemElementById(Document item_doc, String item_id) {\n\t\t\n\t\tElement item = FormManagerUtil.getElementByIdFromDocument(item_doc, head_tag, item_id);\n\t\tif(item == null)\n\t\t\treturn null;\n\t\t\n\t\treturn DOMUtil.getFirstChildElement(item);\n\t}\n\t\n\tpublic static void removeTextNodes(Node node) {\n\t\t\n\t\tNodeList children = node.getChildNodes();\n\t\tList<Node> childs_to_remove = new ArrayList<Node>();\n\t\t\n\t\tfor (int i = 0; i < children.getLength(); i++) {\n\t\t\t\n\t\t\tNode child = children.item(i);\n\t\t\t\n\t\t\tif(child.getNodeType() == Node.TEXT_NODE) {\n\t\t\t\t\n\t\t\t\tchilds_to_remove.add(child);\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tif(child.hasChildNodes())\n\t\t\t\t\tremoveTextNodes(child);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (Iterator<Node> iter = childs_to_remove.iterator(); iter.hasNext();) {\n\t\t\tnode.removeChild(iter.next());\n\t\t}\n\t}\n\t\n\t/*\n\tpublic static List<String[]> getComponentsTagNamesAndIds(Document xforms_doc) {\n\t\t\n\t\tElement body_element = (Element)xforms_doc.getElementsByTagName(body_tag).item(0);\n\t\tElement switch_element = (Element)body_element.getElementsByTagName(switch_tag).item(0);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Element> components_elements = DOMUtil.getChildElements(switch_element);\n\t\tList<String[]> components_tag_names_and_ids = new ArrayList<String[]>();\n\t\t\n\t\tfor (Iterator<Element> iter = components_elements.iterator(); iter.hasNext();) {\n\t\t\t\n\t\t\tElement component_element = iter.next();\n\t\t\tString[] tag_name_and_id = new String[2];\n\t\t\ttag_name_and_id[0] = component_element.getTagName();\n\t\t\ttag_name_and_id[1] = component_element.getAttribute(id_att);\n\t\t\t\n\t\t\tcomponents_tag_names_and_ids.add(tag_name_and_id);\n\t\t}\n\t\t\n\t\treturn components_tag_names_and_ids;\n\t}\n\t*/\n\t\n\tprivate static OutputFormat getOutputFormat() {\n\t\t\n\t\tif(output_format == null) {\n\t\t\t\n\t\t\tOutputFormat output_format = new OutputFormat();\n\t\t\toutput_format.setOmitXMLDeclaration(true);\n\t\t\toutput_format.setLineSeparator(System.getProperty(line_sep));\n\t\t\toutput_format.setIndent(4);\n\t\t\toutput_format.setIndenting(true);\n\t\t\toutput_format.setMediaType(xml_mediatype);\n\t\t\toutput_format.setEncoding(utf_8_encoding);\n\t\t\tFormManagerUtil.output_format = output_format;\n\t\t}\n\t\t\n\t\treturn output_format;\n\t}\n\t\n\tpublic static String serializeDocument(Document document) throws IOException {\n\t\t\n\t\tStringWriter writer = new StringWriter();\n\t\tXMLSerializer serializer = new XMLSerializer(writer, getOutputFormat());\n\t\tserializer.asDOMSerializer();\n\t\tserializer.serialize(document.getDocumentElement());\n\t\t\n\t\treturn writer.toString();\n\t}\n\t\n\tpublic static String escapeNonXmlTagSymbols(String string) {\n\t\t\n\t\tStringBuffer result = new StringBuffer();\n\n\t StringCharacterIterator iterator = new StringCharacterIterator(string);\n\t \n\t Character character = iterator.current();\n\t \n\t while (character != CharacterIterator.DONE ) {\n\t \t\n\t \tif(non_xml_pattern.matcher(character.toString()).matches())\n\t \t\tresult.append(character);\n\t \n\t character = iterator.next();\n\t }\n\t \n\t return result.toString();\n\t}\n\t\t\n\tpublic static int parseIdNumber(String id) {\n\t\t\n\t\tif(id == null)\n\t\t\treturn 0;\n\t\t\n\t\treturn Integer.parseInt(id.substring(CTID.length()));\n\t}\n\t\n\tprivate static XPathUtil componentsContainerElementXPath \n\t\t= new XPathUtil(\".//h:body//idega:switch\", new Prefix(\"idega\", idega_namespace));\n\t\n\tpublic static Element getComponentsContainerElement(Document xform) {\n\n\t\tElement container = componentsContainerElementXPath.getNode(xform);\n\t\t\n\t\tif(container == null) {\n\t\t\tXPathUtil xu = new XPathUtil(\".//h:body//xf:switch\");\n\t\t\tcontainer = xu.getNode(xform);\n\t\t}\n\t\t\n\t\treturn container;\n\t\t/*\n\t\tElement bodyElement = (Element)xform.getElementsByTagName(body_tag).item(0);\n\t\tElement compElement = (Element)bodyElement.getElementsByTagName(switch_tag).item(0);\n\t\tif (compElement == null) {\n\t\t\tcompElement = (Element)bodyElement.getElementsByTagName(\"idega:switch\").item(0);\n\t\t}\n\t\t\n\t\treturn compElement;\n\t\t*/\n\t}\n\t\n\tpublic static void main(String[] args) {\n\n\t\ttry {\n\t\t\t\n\t\t\tDocumentBuilder db = XmlUtil.getDocumentBuilder();\n\t\t\tDocument d = db.parse(new File(\"/Users/civilis/dev/workspace/eplatform-4-bpm/is.idega.idegaweb.egov.impra/resources/processes/EntrepreneurSupport/forms/entrepreneurSupport.xhtml\"));\n\t\t\t\n\t\t\tElement e = getComponentsContainerElement(d);\n\t\t\t\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static boolean isEmpty(String str) {\n\t\treturn str == null || CoreConstants.EMPTY.equals(str);\n\t}\n\t\n\tpublic static void modifyFormForLocalisationInFormbuilder(Document xforms_doc) {\n\t\tElement setvalue_element = getDataModelSetValueElement(xforms_doc);\n\n\t\tsetvalue_element.getParentNode().removeChild(setvalue_element);\n\t}\n\t\t\n\tpublic static void modifyXFormsDocumentForViewing(Document xforms_doc) {\n\t\t\n//\t\tTODO: use better way. probably just xforms property, as it is done when viewing form in pdf mode\n//\t\tthe idea here seems that all pages need to be visible (as with pdf)\n//\t\tTODO added xf:switch tmp soliution\n\t\tNodeList tags = xforms_doc.getElementsByTagName(idegans_case_tag);\n\t\tElement switch_element = (Element)xforms_doc.getElementsByTagName(idegans_switch_tag).item(0);\n\t\tif (switch_element == null){\n\t\t\ttags = xforms_doc.getElementsByTagName(case_tag);\n\t\t\tswitch_element = (Element)xforms_doc.getElementsByTagName(switch_tag).item(0);\n\t\t}\n\n\t\tElement switch_parent = (Element)switch_element.getParentNode();\n\t\t\n\t\tfor (int i = 0; i < tags.getLength(); i++) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tList<Element> case_children = DOMUtil.getChildElements(tags.item(i));\n\t\t\tfor (Element case_child : case_children) {\n\t\t\t\tswitch_parent.appendChild(case_child);\n\t\t\t}\n\t\t}\n\t\t\n\t\tswitch_element.getParentNode().removeChild(switch_element);\n\t}\n\t\n\tpublic static Map<String, List<String>> getCategorizedComponentsTypes(Document form_components_doc) {\n\t\t\n\t\tElement instance_element = getElementByIdFromDocument(form_components_doc, head_tag, \"component_categories\");\n\t\tNodeList categories = instance_element.getElementsByTagName(\"category\");\n\t\tMap<String, List<String>> categorized_types = new HashMap<String, List<String>>();\n\t\t\n\t\tfor (int i = 0; i < categories.getLength(); i++) {\n\t\t\t\n\t\t\tElement category = (Element)categories.item(i);\n\t\t\tNodeList components = category.getElementsByTagName(component_tag);\n\t\t\tList<String> component_types = new ArrayList<String>();\n\n\t\t\tfor (int j = 0; j < components.getLength(); j++) {\n\t\t\t\t\n\t\t\t\tElement component = (Element)components.item(j);\n\t\t\t\tcomponent_types.add(component.getAttribute(component_id_att));\n\t\t\t}\n\t\t\t\n\t\t\tString category_name = category.getAttribute(name_att);\n\t\t\tcategorized_types.put(category_name, component_types);\n\t\t}\n\t\t\n\t\treturn categorized_types;\n\t}\n\t\n\tpublic static Element createAutofillInstance(Document xforms_doc) {\n\t\t\n\t\tElement inst_el = xforms_doc.createElement(instance_tag);\n\t\tinst_el.setAttribute(xmlns_att, \"\");\n\t\tinst_el.setAttribute(relevant_att, xpath_false);\n\t\t\n\t\treturn inst_el;\n\t}\n\t\n\tpublic static void setFormTitle(Document xformsXmlDoc, LocalizedStringBean formTitle) {\n\t \n\t\tElement output = getFormTitleOutputElement(xformsXmlDoc);\n\t\tputLocalizedText(null, null, output, xformsXmlDoc, formTitle);\n\t}\n\t\n\tpublic static LocalizedStringBean getFormTitle(Document xformsDoc) {\n\t\t\n\t\tElement output = getFormTitleOutputElement(xformsDoc);\n\t\treturn getElementLocalizedStrings(output, xformsDoc);\n\t}\n\n\tpublic static void setFormErrorMsg(Document xformsXmlDoc, LocalizedStringBean formError) {\n\t\t\n\t\tElement message = getFormErrorMessageElement(xformsXmlDoc);\n\t\t\n\t\tmessage.removeAttribute(FormManagerUtil.model_att);\n\t\t\n\t\tputLocalizedText(null, null, message, xformsXmlDoc, formError);\n\t}\n\n\tpublic static LocalizedStringBean getFormErrorMsg(Document xformsDoc) {\n\t\t\n\t\tElement message = getFormErrorMessageElement(xformsDoc);\n\t\treturn getElementLocalizedStrings(message, xformsDoc);\n\t}\n\t\n\tpublic static Element getFormInstanceModelElement(Document context) {\n\t\t\n\t\treturn formInstanceModelElementXPath.getNode(context);\n\t}\n\t\n\tpublic static Element getDefaultFormModelElement(Document context) {\n\t\t\n\t\treturn defaultFormModelElementXPath.getNode(context);\n\t}\n\t\n\tpublic static XPathUtil getFormModelElementByIdXPath() {\n\t\t\n\t\treturn formModelElementXPath;\n\t}\n\t\n\tpublic static Element getSubmissionElement(Node context) {\n\t\t\n\t\treturn submissionElementXPath.getNode(context);\n\t}\n\t\n\tpublic static Element getFormSubmissionInstanceElement(Document context) {\n\t\t\n\t\treturn formSubmissionInstanceElementXPath.getNode(context);\n\t}\n\t\n\tpublic static Element getFormSubmissionInstanceDataElement(Node context) {\n\t\t\n\t\treturn formSubmissionInstanceDataElementXPath.getNode(context);\n\t}\n\t\n\tpublic static Element getInstanceElement(Element context) {\n\t\t\n\t\treturn instanceElementXPath.getNode(context);\n\t}\n\t\n\tpublic static XPathUtil getInstanceElementByIdXPath() {\n\t\t\n\t\treturn instanceElementByIdXPath;\n\t}\n\t\n\tprivate static Element getFormTitleOutputElement(Node context) {\n\t\t\n\t\treturn formTitleOutputElementXPath.getNode(context);\n\t}\n\t\n\tprivate static Element getFormErrorMessageElement(Node context) {\n\t \n\t\treturn formErrorMessageXPath.getNode(context);\n\t}\n\t\n\tpublic static String getFormId(Node xformsDoc) {\n\t\treturn XFormsUtil.getFormId(xformsDoc);\n\t}\n\t\n\tpublic static void setFormId(Document xformsDoc, String formId) {\n\t\tXFormsUtil.setFormId(xformsDoc, formId);\n\t}\n\t\n\tpublic static Element getLocalizedStringElement(Node context) {\n\t\t\n\t\treturn localizedStringElementXPath.getNode(context);\n\t}\n\t\n\tpublic static Element getElementById(Node context, String id) {\n\t\t\n\t\tsynchronized (elementByIdXPath) {\n\t\t\n\t\t\telementByIdXPath.clearVariables();\n\t\t\telementByIdXPath.setVariable(id_att, id);\n\t\t\treturn elementByIdXPath.getNode(context);\n\t\t}\n\t}\n\t\n\tpublic static Element getFormParamsElement(Node context) {\n\t\t\n\t\treturn formParamsXPath.getNode(context);\n\t}\n\t\n\tpublic static Element createFormParamsElement(Element context, boolean appendToContext) {\n\n\t\tElement el = context.getOwnerDocument().createElement(\"params\");\n\t\tel.setAttribute(nodeTypeAtt, \"formParams\");\n\t\t\n\t\tif(appendToContext) {\n\t\t\tel = (Element)context.appendChild(el);\n\t\t}\n\t\t\n\t\treturn el;\n\t}\n\t\n\tpublic static NodeList getElementsContainingAttribute(Node context, String elementName, String attributeName) {\n\t\t\n\t\tif(isEmpty(elementName))\n\t\t\telementName = CoreConstants.STAR;\n\t\t\n\t\tif(isEmpty(attributeName))\n\t\t\tattributeName = CoreConstants.STAR;\n\t\t\n\t\tsynchronized (elementsContainingAttributeXPath) {\n\t\t\n\t\t\telementsContainingAttributeXPath.clearVariables();\n\t\t\telementsContainingAttributeXPath.setVariable(elementNameVariable, elementName);\n\t\t\telementsContainingAttributeXPath.setVariable(attributeNameVariable, attributeName);\n\t\t\t\n\t\t\treturn elementsContainingAttributeXPath.getNodeset(context);\n\t\t}\n\t}\n\t\n\tprivate static Element getDataModelSetValueElement(Node context) {\n\t\t\n\t\treturn localizaionSetValueElement.getNode(context);\n\t}\n\t\n\tpublic static Map<String, List<ComponentType>> getComponentsTypesByDatatype(Document form_components_doc) {\n\t\t\n\t\tElement instance_element = getElementByIdFromDocument(form_components_doc, head_tag, \"components-datatypes-mappings\");\n\t\tNodeList list = instance_element.getElementsByTagName(\"component\");\n\t\t\n\t\tMap<String, List<ComponentType>> types = new HashMap<String, List<ComponentType>>();\n\t\t\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\t\n\t\t\tElement component = (Element) list.item(i);\n\t\t\tString componentId = component.getAttribute(component_id_att);\n\t\t\tString accessSupport = component.getAttribute(accessSupport_att);\n\t\t\tComponentType type = new ComponentType(componentId, accessSupport);\n\t\t\t\n\t\t\tNodeList datatypes = component.getElementsByTagName(datatype_tag);\n\t\t\t\n\t\t\tfor (int j = 0; j < datatypes.getLength(); j++) {\n\t\t\t\t\n\t\t\t\tElement datatype = (Element)datatypes.item(j);\n\t\t\t\tString value = datatype.getTextContent();\n\t\t\t\t\n\t\t\t\tif(types.containsKey(value)) {\n\t\t\t\t\ttypes.get(value).add(type);\n\t\t\t\t} else {\n\t\t\t\t\tList<ComponentType> newList = new ArrayList<ComponentType>();\n\t\t\t\t\tnewList.add(type);\n\t\t\t\t\ttypes.put(value, newList);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn types;\n\t}\n}" ]
import org.w3c.dom.Element; import com.idega.documentmanager.business.component.ComponentMultiUploadDescription; import com.idega.documentmanager.business.component.properties.PropertiesMultiUploadDescription; import com.idega.documentmanager.component.properties.impl.ComponentPropertiesMultiUploadDescription; import com.idega.documentmanager.component.properties.impl.ConstUpdateType; import com.idega.documentmanager.manager.XFormsManagerMultiUploadDescription; import com.idega.documentmanager.util.FormManagerUtil; import com.idega.util.CoreConstants;
package com.idega.documentmanager.component.impl; /** * @author <a href="mailto:arunas@idega.com">Arūnas Vasmanas</a> * @version $Revision: 1.5 $ * * Last modified: $Date: 2008/10/26 16:47:10 $ by $Author: anton $ */ public class FormComponentMultiUploadDescriptionImpl extends FormComponentImpl implements ComponentMultiUploadDescription{ @Override public XFormsManagerMultiUploadDescription getXFormsManager() { return getContext().getXformsManagerFactory().getXformsManagerMultiUploadDescription(); } @Override public void setReadonly(boolean readonly) { super.setReadonly(readonly); Element bindElement = this.getXformsComponentDataBean().getBind().getBindElement(); Element groupElem = this.getXformsComponentDataBean().getElement(); if(readonly) { bindElement.setAttribute(FormManagerUtil.relevant_att, FormManagerUtil.xpath_false); groupElem.setAttribute(FormManagerUtil.bind_att, bindElement.getAttribute("id")); // TODO: needs to transform to link list for downloading files }else { if (!CoreConstants.EMPTY.equals(bindElement.getAttribute(FormManagerUtil.relevant_att))) bindElement.removeAttribute(FormManagerUtil.relevant_att); groupElem.removeAttribute(FormManagerUtil.bind_att); } } @Override
public PropertiesMultiUploadDescription getProperties(){
1
ChillingVan/AndroidInstantVideo
app/src/main/java/com/chillingvan/instantvideo/sample/test/publisher/TestCameraPublisherActivity.java
[ "public class CameraPreviewTextureView extends GLMultiTexProducerView {\n\n private H264Encoder.OnDrawListener onDrawListener;\n private IAndroidCanvasHelper drawTextHelper = IAndroidCanvasHelper.Factory.createAndroidCanvasHelper(IAndroidCanvasHelper.MODE.MODE_ASYNC);\n private Paint textPaint;\n\n public CameraPreviewTextureView(Context context) {\n super(context);\n }\n\n public CameraPreviewTextureView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public CameraPreviewTextureView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n @Override\n protected int getInitialTexCount() {\n return 2;\n }\n\n @Override\n public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {\n super.onSurfaceTextureAvailable(surface, width, height);\n if (mSharedEglContext == null) {\n setSharedEglContext(EglContextWrapper.EGL_NO_CONTEXT_WRAPPER);\n }\n }\n\n @Override\n public void onSurfaceChanged(int width, int height) {\n super.onSurfaceChanged(width, height);\n drawTextHelper.init(width, height);\n textPaint = new Paint();\n textPaint.setColor(Color.WHITE);\n textPaint.setTextSize(dp2px(15));\n }\n\n @Override\n protected void onGLDraw(ICanvasGL canvas, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) {\n onDrawListener.onGLDraw(canvas, producedTextures, consumedTextures);\n drawTextHelper.draw(new IAndroidCanvasHelper.CanvasPainter() {\n @Override\n public void draw(Canvas androidCanvas) {\n androidCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);\n androidCanvas.drawText(\"白色, White\", 100, 100, textPaint);\n }\n });\n Bitmap outputBitmap = drawTextHelper.getOutputBitmap();\n canvas.invalidateTextureContent(outputBitmap);\n canvas.drawBitmap(outputBitmap, 0, 0);\n }\n\n private float dp2px(int dp) {\n return dp * getContext().getResources().getDisplayMetrics().density;\n }\n\n public void setOnDrawListener(H264Encoder.OnDrawListener l) {\n onDrawListener = l;\n }\n}", "public class InstantVideoCamera implements CameraInterface {\n\n private Camera camera;\n private boolean isOpened;\n private int currentCamera;\n private int previewWidth;\n private int previewHeight;\n\n @Override\n public void setPreview(SurfaceTexture surfaceTexture) {\n try {\n camera.setPreviewTexture(surfaceTexture);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public InstantVideoCamera(int currentCamera, int previewWidth, int previewHeight) {\n this.currentCamera = currentCamera;\n this.previewWidth = previewWidth;\n this.previewHeight = previewHeight;\n }\n\n @Override\n public void openCamera() {\n Camera.CameraInfo info = new Camera.CameraInfo();\n\n // Try to find a front-facing camera (e.g. for videoconferencing).\n int numCameras = Camera.getNumberOfCameras();\n for (int i = 0; i < numCameras; i++) {\n Camera.getCameraInfo(i, info);\n if (info.facing == currentCamera) {\n camera = Camera.open(i);\n break;\n }\n }\n if (camera == null) {\n camera = Camera.open();\n }\n\n Camera.Parameters parms = camera.getParameters();\n\n CameraUtils.choosePreviewSize(parms, previewWidth, previewHeight);\n isOpened = true;\n }\n\n @Override\n public void switchCamera() {\n switchCamera(previewWidth, previewHeight);\n }\n\n @Override\n public void switchCamera(int previewWidth, int previewHeight) {\n this.previewWidth = previewWidth;\n this.previewHeight = previewHeight;\n release();\n currentCamera = currentCamera == Camera.CameraInfo.CAMERA_FACING_BACK ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;\n openCamera();\n }\n\n @Override\n public boolean isOpened() {\n return isOpened;\n }\n\n @Override\n public void startPreview() {\n camera.startPreview();\n }\n\n @Override\n public void stopPreview() {\n camera.stopPreview();\n }\n\n @Override\n public Camera getCamera() {\n return camera;\n }\n\n @Override\n public void release() {\n if (isOpened) {\n camera.stopPreview();\n camera.release();\n camera = null;\n isOpened = false;\n }\n }\n\n\n}", "public class H264Encoder {\n\n private final Surface mInputSurface;\n private final MediaCodecInputStream mediaCodecInputStream;\n MediaCodec mEncoder;\n\n private static final String MIME_TYPE = \"video/avc\"; // H.264 Advanced Video Coding\n private static final int FRAME_RATE = 30; // 30fps\n private static final int IFRAME_INTERVAL = 5; // 5 seconds between I-frames\n protected final EncoderCanvas offScreenCanvas;\n private OnDrawListener onDrawListener;\n private boolean isStart;\n private int initialTextureCount = 1;\n\n\n public H264Encoder(StreamPublisher.StreamPublisherParam params) throws IOException {\n this(params, EglContextWrapper.EGL_NO_CONTEXT_WRAPPER);\n }\n\n\n /**\n *\n * @param eglCtx can be EGL10.EGL_NO_CONTEXT or outside context\n */\n public H264Encoder(final StreamPublisher.StreamPublisherParam params, final EglContextWrapper eglCtx) throws IOException {\n\n// MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, params.width, params.height);\n MediaFormat format = params.createVideoMediaFormat();\n\n\n // Set some properties. Failing to specify some of these can cause the MediaCodec\n // configure() call to throw an unhelpful exception.\n format.setInteger(MediaFormat.KEY_COLOR_FORMAT,\n MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);\n format.setInteger(MediaFormat.KEY_BIT_RATE, params.videoBitRate);\n format.setInteger(MediaFormat.KEY_FRAME_RATE, params.frameRate);\n format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, params.iframeInterval);\n mEncoder = MediaCodec.createEncoderByType(params.videoMIMEType);\n mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);\n mInputSurface = mEncoder.createInputSurface();\n mEncoder.start();\n mediaCodecInputStream = new MediaCodecInputStream(mEncoder, new MediaCodecInputStream.MediaFormatCallback() {\n @Override\n public void onChangeMediaFormat(MediaFormat mediaFormat) {\n params.setVideoOutputMediaFormat(mediaFormat);\n }\n });\n\n this.initialTextureCount = params.getInitialTextureCount();\n offScreenCanvas = new EncoderCanvas(params.width, params.height, eglCtx);\n }\n\n /**\n * If called, should be called before start() called.\n */\n public void addSharedTexture(GLTexture texture) {\n offScreenCanvas.addConsumeGLTexture(texture);\n }\n\n\n public Surface getInputSurface() {\n return mInputSurface;\n }\n\n public MediaCodecInputStream getMediaCodecInputStream() {\n return mediaCodecInputStream;\n }\n\n /**\n *\n * @param initialTextureCount Default is 1\n */\n public void setInitialTextureCount(int initialTextureCount) {\n if (initialTextureCount < 1) {\n throw new IllegalArgumentException(\"initialTextureCount must >= 1\");\n }\n this.initialTextureCount = initialTextureCount;\n }\n\n public void start() {\n offScreenCanvas.start();\n isStart = true;\n }\n\n public void close() {\n if (!isStart) return;\n\n Loggers.d(\"H264Encoder\", \"close\");\n offScreenCanvas.end();\n mediaCodecInputStream.close();\n synchronized (mEncoder) {\n mEncoder.stop();\n mEncoder.release();\n }\n isStart = false;\n }\n\n public boolean isStart() {\n return isStart;\n }\n\n public void requestRender() {\n offScreenCanvas.requestRender();\n }\n\n\n public void requestRenderAndWait() {\n offScreenCanvas.requestRenderAndWait();\n }\n\n public void setOnDrawListener(OnDrawListener l) {\n this.onDrawListener = l;\n }\n\n public interface OnDrawListener {\n /**\n * Called when a frame is ready to be drawn.\n * @param canvasGL The gl canvas\n * @param producedTextures The textures produced by internal. These can be used for camera or video decoder to render.\n * @param consumedTextures See {@link #addSharedTexture(GLTexture)}. The textures you set from outside. Then you can draw the textures render by other Views of OffscreenCanvas.\n */\n void onGLDraw(ICanvasGL canvasGL, List<GLTexture> producedTextures, List<GLTexture> consumedTextures);\n }\n\n private class EncoderCanvas extends MultiTexOffScreenCanvas {\n public EncoderCanvas(int width, int height, EglContextWrapper eglCtx) {\n super(width, height, eglCtx, H264Encoder.this.mInputSurface);\n }\n\n @Override\n protected void onGLDraw(ICanvasGL canvas, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) {\n if (onDrawListener != null) {\n onDrawListener.onGLDraw(canvas, producedTextures, consumedTextures);\n }\n }\n\n @Override\n protected int getInitialTexCount() {\n return initialTextureCount;\n }\n }\n}", "public class RTMPStreamMuxer extends BaseMuxer {\n private RTMPMuxer rtmpMuxer;\n\n private FrameSender frameSender;\n\n\n public RTMPStreamMuxer() {\n super();\n }\n\n\n /**\n *\n * @return 1 if it is connected\n * 0 if it is not connected\n */\n @Override\n public synchronized int open(final StreamPublisher.StreamPublisherParam params) {\n super.open(params);\n\n if (TextUtils.isEmpty(params.outputUrl)) {\n throw new IllegalArgumentException(\"Param outputUrl is empty\");\n }\n\n rtmpMuxer = new RTMPMuxer();\n // -2 Url format error; -3 Connect error.\n int open = rtmpMuxer.open(params.outputUrl, params.width, params.height);\n Loggers.d(\"RTMPStreamMuxer\", String.format(Locale.CHINA, \"open: open: %d\", open));\n int connected = rtmpMuxer.isConnected();\n Loggers.d(\"RTMPStreamMuxer\", String.format(Locale.CHINA, \"open: isConnected: %d\", connected));\n\n Loggers.d(\"RTMPStreamMuxer\", String.format(\"open: %s\", params.outputUrl));\n if (!TextUtils.isEmpty(params.outputFilePath)) {\n rtmpMuxer.file_open(params.outputFilePath);\n rtmpMuxer.write_flv_header(true, true);\n }\n\n frameSender = new FrameSender(new FrameSender.FrameSenderCallback() {\n @Override\n public void onStart() {}\n\n @Override\n public void onSendVideo(FramePool.Frame sendFrame) {\n\n rtmpMuxer.writeVideo(sendFrame.data, 0, sendFrame.length, sendFrame.bufferInfo.getTotalTime());\n }\n\n @Override\n public void onSendAudio(FramePool.Frame sendFrame) {\n\n rtmpMuxer.writeAudio(sendFrame.data, 0, sendFrame.length, sendFrame.bufferInfo.getTotalTime());\n }\n\n @Override\n public void close() {\n if (rtmpMuxer != null) {\n if (!TextUtils.isEmpty(params.outputFilePath)) {\n rtmpMuxer.file_close();\n }\n rtmpMuxer.close();\n rtmpMuxer = null;\n }\n\n }\n });\n frameSender.sendStartMessage();\n return connected;\n }\n\n @Override\n public void writeVideo(byte[] buffer, int offset, int length, MediaCodec.BufferInfo bufferInfo) {\n super.writeVideo(buffer, offset, length, bufferInfo);\n Loggers.d(\"RTMPStreamMuxer\", \"writeVideo: \" + \" time:\" + videoTimeIndexCounter.getTimeIndex() + \" offset:\" + offset + \" length:\" + length);\n frameSender.sendAddFrameMessage(buffer, offset, length, new BufferInfoEx(bufferInfo, videoTimeIndexCounter.getTimeIndex()), FramePool.Frame.TYPE_VIDEO);\n }\n\n\n\n @Override\n public void writeAudio(byte[] buffer, int offset, int length, MediaCodec.BufferInfo bufferInfo) {\n super.writeAudio(buffer, offset, length, bufferInfo);\n Loggers.d(\"RTMPStreamMuxer\", \"writeAudio: \");\n frameSender.sendAddFrameMessage(buffer, offset, length, new BufferInfoEx(bufferInfo, audioTimeIndexCounter.getTimeIndex()), FramePool.Frame.TYPE_AUDIO);\n }\n\n @Override\n public synchronized int close() {\n if (frameSender != null) {\n frameSender.sendCloseMessage();\n }\n\n return 0;\n }\n\n\n}", "public class CameraStreamPublisher {\n\n private StreamPublisher streamPublisher;\n private IMuxer muxer;\n private GLMultiTexProducerView cameraPreviewTextureView;\n private CameraInterface instantVideoCamera;\n private OnSurfacesCreatedListener onSurfacesCreatedListener;\n\n public CameraStreamPublisher(IMuxer muxer, GLMultiTexProducerView cameraPreviewTextureView, CameraInterface instantVideoCamera) {\n this.muxer = muxer;\n this.cameraPreviewTextureView = cameraPreviewTextureView;\n this.instantVideoCamera = instantVideoCamera;\n }\n\n private void initCameraTexture() {\n cameraPreviewTextureView.setOnCreateGLContextListener(new GLThread.OnCreateGLContextListener() {\n @Override\n public void onCreate(EglContextWrapper eglContext) {\n streamPublisher = new StreamPublisher(eglContext, muxer);\n }\n });\n cameraPreviewTextureView.setSurfaceTextureCreatedListener(new GLMultiTexProducerView.SurfaceTextureCreatedListener() {\n @Override\n public void onCreated(List<GLTexture> producedTextureList) {\n if (onSurfacesCreatedListener != null) {\n onSurfacesCreatedListener.onCreated(producedTextureList, streamPublisher);\n }\n GLTexture texture = producedTextureList.get(0);\n SurfaceTexture surfaceTexture = texture.getSurfaceTexture();\n streamPublisher.addSharedTexture(new GLTexture(texture.getRawTexture(), surfaceTexture));\n surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {\n @Override\n public void onFrameAvailable(SurfaceTexture surfaceTexture) {\n cameraPreviewTextureView.requestRenderAndWait();\n streamPublisher.drawAFrame();\n }\n });\n\n instantVideoCamera.setPreview(surfaceTexture);\n instantVideoCamera.startPreview();\n }\n });\n }\n\n public void prepareEncoder(StreamPublisher.StreamPublisherParam param, H264Encoder.OnDrawListener onDrawListener) {\n streamPublisher.prepareEncoder(param, onDrawListener);\n }\n\n public void resumeCamera() {\n if (instantVideoCamera.isOpened()) return;\n\n instantVideoCamera.openCamera();\n initCameraTexture();\n cameraPreviewTextureView.onResume();\n }\n\n public boolean isStart() {\n return streamPublisher != null && streamPublisher.isStart();\n }\n\n public void pauseCamera() {\n if (!instantVideoCamera.isOpened()) return;\n\n instantVideoCamera.release();\n cameraPreviewTextureView.onPause();\n }\n\n public void startPublish() throws IOException {\n streamPublisher.start();\n }\n\n\n public void closeAll() {\n streamPublisher.close();\n }\n\n public void setOnSurfacesCreatedListener(OnSurfacesCreatedListener onSurfacesCreatedListener) {\n this.onSurfacesCreatedListener = onSurfacesCreatedListener;\n }\n\n public interface OnSurfacesCreatedListener {\n void onCreated(List<GLTexture> producedTextureList, StreamPublisher streamPublisher);\n }\n}", "public class StreamPublisher {\n\n public static final int MSG_OPEN = 1;\n public static final int MSG_WRITE_VIDEO = 2;\n private EglContextWrapper eglCtx;\n private IMuxer muxer;\n private AACEncoder aacEncoder;\n private H264Encoder h264Encoder;\n private boolean isStart;\n\n private HandlerThread writeVideoHandlerThread;\n\n private Handler writeVideoHandler;\n private StreamPublisherParam param;\n private List<GLTexture> sharedTextureList = new ArrayList<>();\n\n public StreamPublisher(EglContextWrapper eglCtx, IMuxer muxer) {\n this.eglCtx = eglCtx;\n this.muxer = muxer;\n }\n\n\n public void prepareEncoder(final StreamPublisherParam param, H264Encoder.OnDrawListener onDrawListener) {\n this.param = param;\n\n try {\n h264Encoder = new H264Encoder(param, eglCtx);\n for (GLTexture texture :sharedTextureList ) {\n h264Encoder.addSharedTexture(texture);\n }\n h264Encoder.setOnDrawListener(onDrawListener);\n aacEncoder = new AACEncoder(param);\n aacEncoder.setOnDataComingCallback(new AACEncoder.OnDataComingCallback() {\n private byte[] writeBuffer = new byte[param.audioBitRate / 8];\n\n @Override\n public void onComing() {\n MediaCodecInputStream mediaCodecInputStream = aacEncoder.getMediaCodecInputStream();\n MediaCodecInputStream.readAll(mediaCodecInputStream, writeBuffer, new MediaCodecInputStream.OnReadAllCallback() {\n @Override\n public void onReadOnce(byte[] buffer, int readSize, MediaCodec.BufferInfo bufferInfo) {\n if (readSize <= 0) {\n return;\n }\n muxer.writeAudio(buffer, 0, readSize, bufferInfo);\n }\n });\n }\n });\n\n } catch (IOException | IllegalStateException e) {\n e.printStackTrace();\n }\n\n writeVideoHandlerThread = new HandlerThread(\"WriteVideoHandlerThread\");\n writeVideoHandlerThread.start();\n writeVideoHandler = new Handler(writeVideoHandlerThread.getLooper()) {\n private byte[] writeBuffer = new byte[param.videoBitRate / 8 / 2];\n\n @Override\n public void handleMessage(Message msg) {\n super.handleMessage(msg);\n if (msg.what == MSG_WRITE_VIDEO) {\n MediaCodecInputStream mediaCodecInputStream = h264Encoder.getMediaCodecInputStream();\n MediaCodecInputStream.readAll(mediaCodecInputStream, writeBuffer, new MediaCodecInputStream.OnReadAllCallback() {\n @Override\n public void onReadOnce(byte[] buffer, int readSize, MediaCodec.BufferInfo bufferInfo) {\n if (readSize <= 0) {\n return;\n }\n Loggers.d(\"StreamPublisher\", String.format(\"onReadOnce: %d\", readSize));\n muxer.writeVideo(buffer, 0, readSize, bufferInfo);\n }\n });\n }\n }\n };\n }\n\n public void addSharedTexture(GLTexture outsideTexture) {\n sharedTextureList.add(outsideTexture);\n }\n\n\n public void start() throws IOException {\n if (!isStart) {\n if (muxer.open(param) <= 0) {\n Loggers.e(\"StreamPublisher\", \"muxer open fail\");\n throw new IOException(\"muxer open fail\");\n }\n h264Encoder.start();\n aacEncoder.start();\n isStart = true;\n }\n\n }\n\n public void close() {\n isStart = false;\n if (h264Encoder != null) {\n h264Encoder.close();\n }\n\n if (aacEncoder != null) {\n aacEncoder.close();\n }\n if (writeVideoHandlerThread != null) {\n writeVideoHandlerThread.quitSafely();\n }\n if (muxer != null) {\n muxer.close();\n }\n }\n\n public boolean isStart() {\n return isStart;\n }\n\n\n public boolean drawAFrame() {\n if (isStart) {\n h264Encoder.requestRender();\n writeVideoHandler.sendEmptyMessage(MSG_WRITE_VIDEO);\n return true;\n }\n return false;\n }\n\n public static class StreamPublisherParam {\n public int width = 640;\n public int height = 480;\n public int videoBitRate = 2949120;\n public int frameRate = 30;\n public int iframeInterval = 5;\n public int samplingRate = 44100;\n public int audioBitRate = 192000;\n public int audioSource;\n public int channelCfg = AudioFormat.CHANNEL_IN_STEREO;\n\n public String videoMIMEType = \"video/avc\";\n public String audioMIME = \"audio/mp4a-latm\";\n public int audioBufferSize;\n\n public String outputFilePath;\n public String outputUrl;\n private MediaFormat videoOutputMediaFormat;\n private MediaFormat audioOutputMediaFormat;\n\n private int initialTextureCount = 1;\n\n public StreamPublisherParam() {\n this(640, 480, 2949120, 30, 5, 44100, 192000, MediaRecorder.AudioSource.MIC, AudioFormat.CHANNEL_IN_STEREO);\n }\n\n private StreamPublisherParam(int width, int height, int videoBitRate, int frameRate,\n int iframeInterval, int samplingRate, int audioBitRate, int audioSource, int channelCfg) {\n this.width = width;\n this.height = height;\n this.videoBitRate = videoBitRate;\n this.frameRate = frameRate;\n this.iframeInterval = iframeInterval;\n this.samplingRate = samplingRate;\n this.audioBitRate = audioBitRate;\n this.audioBufferSize = AudioRecord.getMinBufferSize(samplingRate, channelCfg, AudioFormat.ENCODING_PCM_16BIT) * 2;\n this.audioSource = audioSource;\n this.channelCfg = channelCfg;\n }\n\n /**\n *\n * @param initialTextureCount Default is 1\n */\n public void setInitialTextureCount(int initialTextureCount) {\n if (initialTextureCount < 1) {\n throw new IllegalArgumentException(\"initialTextureCount must >= 1\");\n }\n this.initialTextureCount = initialTextureCount;\n }\n\n public int getInitialTextureCount() {\n return initialTextureCount;\n }\n\n public MediaFormat createVideoMediaFormat() {\n MediaFormat format = MediaFormat.createVideoFormat(videoMIMEType, width, height);\n\n // Set some properties. Failing to specify some of these can cause the MediaCodec\n // configure() call to throw an unhelpful exception.\n format.setInteger(MediaFormat.KEY_COLOR_FORMAT,\n MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);\n format.setInteger(MediaFormat.KEY_BIT_RATE, videoBitRate);\n format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);\n format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, iframeInterval);\n return format;\n }\n\n public MediaFormat createAudioMediaFormat() {\n MediaFormat format = MediaFormat.createAudioFormat(audioMIME, samplingRate, 2);\n format.setInteger(MediaFormat.KEY_BIT_RATE, audioBitRate);\n format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);\n format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, audioBufferSize);\n\n return format;\n }\n\n public void setVideoOutputMediaFormat(MediaFormat videoOutputMediaFormat) {\n this.videoOutputMediaFormat = videoOutputMediaFormat;\n }\n\n public void setAudioOutputMediaFormat(MediaFormat audioOutputMediaFormat) {\n this.audioOutputMediaFormat = audioOutputMediaFormat;\n }\n\n public MediaFormat getVideoOutputMediaFormat() {\n return videoOutputMediaFormat;\n }\n\n public MediaFormat getAudioOutputMediaFormat() {\n return audioOutputMediaFormat;\n }\n\n public static class Builder {\n private int width = 640;\n private int height = 480;\n private int videoBitRate = 2949120;\n private int frameRate = 30;\n private int iframeInterval = 5;\n private int samplingRate = 44100;\n private int audioBitRate = 192000;\n private int audioSource = MediaRecorder.AudioSource.MIC;\n private int channelCfg = AudioFormat.CHANNEL_IN_STEREO;\n\n public Builder setWidth(int width) {\n this.width = width;\n return this;\n }\n\n public Builder setHeight(int height) {\n this.height = height;\n return this;\n }\n\n public Builder setVideoBitRate(int videoBitRate) {\n this.videoBitRate = videoBitRate;\n return this;\n }\n\n public Builder setFrameRate(int frameRate) {\n this.frameRate = frameRate;\n return this;\n }\n\n public Builder setIframeInterval(int iframeInterval) {\n this.iframeInterval = iframeInterval;\n return this;\n }\n\n public Builder setSamplingRate(int samplingRate) {\n this.samplingRate = samplingRate;\n return this;\n }\n\n public Builder setAudioBitRate(int audioBitRate) {\n this.audioBitRate = audioBitRate;\n return this;\n }\n\n public Builder setAudioSource(int audioSource) {\n this.audioSource = audioSource;\n return this;\n }\n\n public Builder setChannelCfg(int channelCfg) {\n this.channelCfg = channelCfg;\n return this;\n }\n\n public StreamPublisherParam createStreamPublisherParam() {\n return new StreamPublisherParam(width, height, videoBitRate, frameRate, iframeInterval, samplingRate, audioBitRate, audioSource, channelCfg);\n }\n }\n }\n\n}" ]
import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.chillingvan.canvasgl.ICanvasGL; import com.chillingvan.canvasgl.glcanvas.BasicTexture; import com.chillingvan.canvasgl.glview.texture.GLTexture; import com.chillingvan.canvasgl.textureFilter.BasicTextureFilter; import com.chillingvan.canvasgl.textureFilter.HueFilter; import com.chillingvan.canvasgl.textureFilter.TextureFilter; import com.chillingvan.instantvideo.sample.R; import com.chillingvan.instantvideo.sample.test.camera.CameraPreviewTextureView; import com.chillingvan.lib.camera.InstantVideoCamera; import com.chillingvan.lib.encoder.video.H264Encoder; import com.chillingvan.lib.muxer.RTMPStreamMuxer; import com.chillingvan.lib.publisher.CameraStreamPublisher; import com.chillingvan.lib.publisher.StreamPublisher; import java.io.IOException; import java.util.List;
/* * * * * * * Copyright (C) 2017 ChillingVan * * * * * * 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.chillingvan.instantvideo.sample.test.publisher; public class TestCameraPublisherActivity extends AppCompatActivity { private CameraStreamPublisher streamPublisher; private CameraPreviewTextureView cameraPreviewTextureView;
private InstantVideoCamera instantVideoCamera;
1
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java
[ "public final class CircleDouble implements Circle {\n\n private final double x, y, radius;\n private final Rectangle mbr;\n\n private CircleDouble(double x, double y, double radius) {\n this.x = x;\n this.y = y;\n this.radius = radius;\n this.mbr = RectangleDouble.create(x - radius, y - radius, x + radius, y + radius);\n }\n\n public static CircleDouble create(double x, double y, double radius) {\n return new CircleDouble(x, y, radius);\n }\n\n @Override\n public double x() {\n return x;\n }\n\n @Override\n public double y() {\n return y;\n }\n\n @Override\n public double radius() {\n return radius;\n }\n\n @Override\n public Rectangle mbr() {\n return mbr;\n }\n\n @Override\n public double distance(Rectangle r) {\n return Math.max(0, GeometryUtil.distance(x, y, r) - radius);\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return distance(r) == 0;\n }\n\n @Override\n public boolean intersects(Circle c) {\n double total = radius + c.radius();\n return GeometryUtil.distanceSquared(x, y, c.x(), c.y()) <= total * total;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(x, y, radius);\n }\n\n @Override\n public boolean equals(Object obj) {\n Optional<CircleDouble> other = ObjectsHelper.asClass(obj, CircleDouble.class);\n if (other.isPresent()) {\n return Objects.equals(x, other.get().x) && Objects.equals(y, other.get().y)\n && Objects.equals(radius, other.get().radius);\n } else\n return false;\n }\n\n @Override\n public boolean intersects(Point point) {\n return Math.sqrt(sqr(x - point.x()) + sqr(y - point.y())) <= radius;\n }\n\n private double sqr(double x) {\n return x * x;\n }\n\n @Override\n public boolean intersects(Line line) {\n return line.intersects(this);\n }\n\n @Override\n public boolean isDoublePrecision() {\n return true;\n }\n}", "public final class CircleFloat implements Circle {\n\n private final float x, y, radius;\n private final Rectangle mbr;\n\n private CircleFloat(float x, float y, float radius) {\n this.x = x;\n this.y = y;\n this.radius = radius;\n this.mbr = RectangleFloat.create(x - radius, y - radius, x + radius, y + radius);\n }\n\n public static CircleFloat create(float x, float y, float radius) {\n return new CircleFloat(x, y, radius);\n }\n\n @Override\n public double x() {\n return x;\n }\n\n @Override\n public double y() {\n return y;\n }\n\n @Override\n public double radius() {\n return radius;\n }\n\n @Override\n public Rectangle mbr() {\n return mbr;\n }\n\n @Override\n public double distance(Rectangle r) {\n return Math.max(0, GeometryUtil.distance(x, y, r) - radius);\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return distance(r) == 0;\n }\n\n @Override\n public boolean intersects(Circle c) {\n double total = radius + c.radius();\n return GeometryUtil.distanceSquared(x, y, c.x(), c.y()) <= total * total;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(x, y, radius);\n }\n\n @Override\n public boolean equals(Object obj) {\n Optional<CircleFloat> other = ObjectsHelper.asClass(obj, CircleFloat.class);\n if (other.isPresent()) {\n return Objects.equals(x, other.get().x) && Objects.equals(y, other.get().y)\n && Objects.equals(radius, other.get().radius);\n } else\n return false;\n }\n\n @Override\n public boolean intersects(Point point) {\n return Math.sqrt(sqr(x - point.x()) + sqr(y - point.y())) <= radius;\n }\n\n private double sqr(double x) {\n return x * x;\n }\n\n @Override\n public boolean intersects(Line line) {\n return line.intersects(this);\n }\n\n @Override\n public boolean isDoublePrecision() {\n return false;\n }\n}", "public final class LineDouble implements Line {\n\n private final double x1;\n private final double y1;\n private final double x2;\n private final double y2;\n\n private LineDouble(double x1, double y1, double x2, double y2) {\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n\n public static LineDouble create(double x1, double y1, double x2, double y2) {\n return new LineDouble(x1, y1, x2, y2);\n }\n\n @Override\n public double distance(Rectangle r) {\n if (r.contains(x1, y1) || r.contains(x2, y2)) {\n return 0;\n } else {\n double d1 = distance(r.x1(), r.y1(), r.x1(), r.y2());\n if (d1 == 0)\n return 0;\n double d2 = distance(r.x1(), r.y2(), r.x2(), r.y2());\n if (d2 == 0)\n return 0;\n double d3 = distance(r.x2(), r.y2(), r.x2(), r.y1());\n double d4 = distance(r.x2(), r.y1(), r.x1(), r.y1());\n return Math.min(d1, Math.min(d2, Math.min(d3, d4)));\n }\n }\n\n private double distance(double x1, double y1, double x2, double y2) {\n Line2D line = new Line2D(x1, y1, x2, y2);\n double d1 = line.ptSegDist(this.x1, this.y1);\n double d2 = line.ptSegDist(this.x2, this.y2);\n Line2D line2 = new Line2D(this.x1, this.y1, this.x2, this.y2);\n double d3 = line2.ptSegDist(x1, y1);\n if (d3 == 0)\n return 0;\n double d4 = line2.ptSegDist(x2, y2);\n if (d4 == 0)\n return 0;\n else\n return Math.min(d1, Math.min(d2, Math.min(d3, d4)));\n\n }\n\n @Override\n public Rectangle mbr() {\n return Geometries.rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2),\n Math.max(y1, y2));\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return RectangleUtil.rectangleIntersectsLine(r.x1(), r.y1(), r.x2() - r.x1(),\n r.y2() - r.y1(), x1, y1, x2, y2);\n }\n\n @Override\n public double x1() {\n return x1;\n }\n\n @Override\n public double y1() {\n return y1;\n }\n\n @Override\n public double x2() {\n return x2;\n }\n\n @Override\n public double y2() {\n return y2;\n }\n\n @Override\n public boolean intersects(Line b) {\n Line2D line1 = new Line2D(x1, y1, x2, y2);\n Line2D line2 = new Line2D(b.x1(), b.y1(), b.x2(), b.y2());\n return line2.intersectsLine(line1);\n }\n\n @Override\n public boolean intersects(Point point) {\n return intersects(point.mbr());\n }\n\n @Override\n public boolean intersects(Circle circle) {\n return GeometryUtil.lineIntersects(x1, y1, x2, y2, circle);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(x1, y1, x2, y2);\n }\n\n @Override\n public boolean equals(Object obj) {\n Optional<LineDouble> other = ObjectsHelper.asClass(obj, LineDouble.class);\n if (other.isPresent()) {\n return Objects.equals(x1, other.get().x1) && Objects.equals(x2, other.get().x2)\n && Objects.equals(y1, other.get().y1) && Objects.equals(y2, other.get().y2);\n } else\n return false;\n }\n\n @Override\n public boolean isDoublePrecision() {\n return true;\n }\n\n}", "public final class LineFloat implements Line {\n\n private final double x1;\n private final double y1;\n private final double x2;\n private final double y2;\n\n private LineFloat(double x1, double y1, double x2, double y2) {\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n\n public static LineFloat create(double x1, double y1, double x2, double y2) {\n return new LineFloat(x1, y1, x2, y2);\n }\n\n @Override\n public double distance(Rectangle r) {\n if (r.contains(x1, y1) || r.contains(x2, y2)) {\n return 0;\n } else {\n double d1 = distance(r.x1(), r.y1(), r.x1(), r.y2());\n if (d1 == 0)\n return 0;\n double d2 = distance(r.x1(), r.y2(), r.x2(), r.y2());\n if (d2 == 0)\n return 0;\n double d3 = distance(r.x2(), r.y2(), r.x2(), r.y1());\n double d4 = distance(r.x2(), r.y1(), r.x1(), r.y1());\n return Math.min(d1, Math.min(d2, Math.min(d3, d4)));\n }\n }\n\n private double distance(double x1, double y1, double x2, double y2) {\n Line2D line = new Line2D(x1, y1, x2, y2);\n double d1 = line.ptSegDist(this.x1, this.y1);\n double d2 = line.ptSegDist(this.x2, this.y2);\n Line2D line2 = new Line2D(this.x1, this.y1, this.x2, this.y2);\n double d3 = line2.ptSegDist(x1, y1);\n if (d3 == 0)\n return 0;\n double d4 = line2.ptSegDist(x2, y2);\n if (d4 == 0)\n return 0;\n else\n return Math.min(d1, Math.min(d2, Math.min(d3, d4)));\n\n }\n\n @Override\n public Rectangle mbr() {\n return Geometries.rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2),\n Math.max(y1, y2));\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return RectangleUtil.rectangleIntersectsLine(r.x1(), r.y1(), r.x2() - r.x1(),\n r.y2() - r.y1(), x1, y1, x2, y2);\n }\n\n @Override\n public double x1() {\n return x1;\n }\n\n @Override\n public double y1() {\n return y1;\n }\n\n @Override\n public double x2() {\n return x2;\n }\n\n @Override\n public double y2() {\n return y2;\n }\n\n @Override\n public boolean intersects(Line b) {\n Line2D line1 = new Line2D(x1, y1, x2, y2);\n Line2D line2 = new Line2D(b.x1(), b.y1(), b.x2(), b.y2());\n return line2.intersectsLine(line1);\n }\n\n @Override\n public boolean intersects(Point point) {\n return intersects(point.mbr());\n }\n\n @Override\n public boolean intersects(Circle circle) {\n return GeometryUtil.lineIntersects(x1, y1, x2, y2, circle);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(x1, y1, x2, y2);\n }\n\n @Override\n public boolean equals(Object obj) {\n Optional<LineFloat> other = ObjectsHelper.asClass(obj, LineFloat.class);\n if (other.isPresent()) {\n return Objects.equals(x1, other.get().x1) && Objects.equals(x2, other.get().x2)\n && Objects.equals(y1, other.get().y1) && Objects.equals(y2, other.get().y2);\n } else\n return false;\n }\n\n @Override\n public boolean isDoublePrecision() {\n return false;\n }\n\n}", "public final class PointDouble implements Point {\n\n private final double x;\n private final double y;\n\n private PointDouble(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n public static PointDouble create(double x, double y) {\n return new PointDouble(x, y);\n }\n\n @Override\n public Rectangle mbr() {\n return this;\n }\n\n @Override\n public double distance(Rectangle r) {\n return GeometryUtil.distance(x, y, r);\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return r.x1() <= x && x <= r.x2() && r.y1() <= y && y <= r.y2();\n }\n\n @Override\n public double x() {\n return x;\n }\n\n @Override\n public double y() {\n return y;\n }\n\n @Override\n public String toString() {\n return \"Point [x=\" + x() + \", y=\" + y() + \"]\";\n }\n\n @Override\n public Geometry geometry() {\n return this;\n }\n\n @Override\n public double x1() {\n return x;\n }\n\n @Override\n public double y1() {\n return y;\n }\n\n @Override\n public double x2() {\n return x;\n }\n\n @Override\n public double y2() {\n return y;\n }\n\n @Override\n public double area() {\n return 0;\n }\n\n @Override\n public Rectangle add(Rectangle r) {\n return Geometries.rectangle(Math.min(x, r.x1()), Math.min(y, r.y1()), Math.max(x, r.x2()),\n Math.max(y, r.y2()));\n }\n\n @Override\n public boolean contains(double x, double y) {\n return this.x == x && this.y == y;\n }\n\n @Override\n public double intersectionArea(Rectangle r) {\n return 0;\n }\n\n @Override\n public double perimeter() {\n return 0;\n }\n\n @Override\n public boolean isDoublePrecision() {\n return true;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n long temp;\n temp = Double.doubleToLongBits(x);\n result = prime * result + (int) (temp ^ (temp >>> 32));\n temp = Double.doubleToLongBits(y);\n result = prime * result + (int) (temp ^ (temp >>> 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 PointDouble other = (PointDouble) obj;\n if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))\n return false;\n if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))\n return false;\n return true;\n }\n\n}", "public final class PointFloat implements Point {\n\n private final float x;\n private final float y;\n\n private PointFloat(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public static PointFloat create(float x, float y) {\n return new PointFloat(x, y);\n }\n\n @Override\n public Rectangle mbr() {\n return this;\n }\n\n @Override\n public double distance(Rectangle r) {\n return GeometryUtil.distance(x, y, r);\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return r.x1() <= x && x <= r.x2() && r.y1() <= y && y <= r.y2();\n }\n\n @Override\n public double x() {\n return x;\n }\n\n @Override\n public double y() {\n return y;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + Float.floatToIntBits(x);\n result = prime * result + Float.floatToIntBits(y);\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 PointFloat other = (PointFloat) obj;\n if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))\n return false;\n if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Point [x=\" + x() + \", y=\" + y() + \"]\";\n }\n\n @Override\n public Geometry geometry() {\n return this;\n }\n\n @Override\n public double x1() {\n return x;\n }\n\n @Override\n public double y1() {\n return y;\n }\n\n @Override\n public double x2() {\n return x;\n }\n\n @Override\n public double y2() {\n return y;\n }\n\n @Override\n public double area() {\n return 0;\n }\n\n @Override\n public Rectangle add(Rectangle r) {\n if (r.isDoublePrecision()) {\n return RectangleDouble.create(Math.min(x, r.x1()), Math.min(y, r.y1()),\n Math.max(x, r.x2()), Math.max(y, r.y2()));\n } else if (r instanceof RectangleFloat) {\n RectangleFloat rf = (RectangleFloat) r;\n return RectangleFloat.create(Math.min(x, rf.x1), Math.min(y, rf.y1), Math.max(x, rf.x2),\n Math.max(y, rf.y2));\n } else if (r instanceof PointFloat) {\n PointFloat p = (PointFloat) r;\n return RectangleFloat.create(Math.min(x, p.x), Math.min(y, p.y), Math.max(x, p.x),\n Math.max(y, p.y));\n } else {\n PointDouble p = (PointDouble) r;\n return RectangleDouble.create(Math.min(x, p.x()), Math.min(y, p.y()),\n Math.max(x, p.x()), Math.max(y, p.y()));\n }\n }\n\n @Override\n public boolean contains(double x, double y) {\n return this.x == x && this.y == y;\n }\n\n @Override\n public double intersectionArea(Rectangle r) {\n return 0;\n }\n\n @Override\n public double perimeter() {\n return 0;\n }\n\n @Override\n public boolean isDoublePrecision() {\n return false;\n }\n\n public float xFloat() {\n return x;\n }\n\n public float yFloat() {\n return y;\n }\n\n}", "public final class RectangleDouble implements Rectangle {\n private final double x1, y1, x2, y2;\n\n private RectangleDouble(double x1, double y1, double x2, double y2) {\n Preconditions.checkArgument(x2 >= x1);\n Preconditions.checkArgument(y2 >= y1);\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n\n public static RectangleDouble create(double x1, double y1, double x2, double y2) {\n return new RectangleDouble((double) x1, (double) y1, (double) x2, (double) y2);\n }\n\n @Override\n public double x1() {\n return x1;\n }\n\n @Override\n public double y1() {\n return y1;\n }\n\n @Override\n public double x2() {\n return x2;\n }\n\n @Override\n public double y2() {\n return y2;\n }\n\n @Override\n public Rectangle add(Rectangle r) {\n return new RectangleDouble(min(x1, r.x1()), min(y1, r.y1()), max(x2, r.x2()),\n max(y2, r.y2()));\n }\n\n @Override\n public boolean contains(double x, double y) {\n return x >= x1 && x <= x2 && y >= y1 && y <= y2;\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n if (r instanceof RectangleDouble) {\n RectangleDouble rd = (RectangleDouble) r;\n return intersects(rd);\n } else {\n return GeometryUtil.intersects(x1, y1, x2, y2, r.x1(), r.y1(), r.x2(), r.y2());\n }\n }\n\n private boolean intersects(RectangleDouble rd) {\n return GeometryUtil.intersects(x1, y1, x2, y2, rd.x1, rd.y1, rd.x2, rd.y2);\n }\n\n @Override\n public double distance(Rectangle r) {\n return GeometryUtil.distance(x1, y1, x2, y2, r.x1(), r.y1(), r.x2(), r.y2());\n }\n\n @Override\n public Rectangle mbr() {\n return this;\n }\n\n @Override\n public String toString() {\n return \"Rectangle [x1=\" + x1 + \", y1=\" + y1 + \", x2=\" + x2 + \", y2=\" + y2 + \"]\";\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(x1, y1, x2, y2);\n }\n\n @Override\n public boolean equals(Object obj) {\n Optional<RectangleDouble> other = ObjectsHelper.asClass(obj, RectangleDouble.class);\n if (other.isPresent()) {\n return Objects.equals(x1, other.get().x1) && Objects.equals(x2, other.get().x2)\n && Objects.equals(y1, other.get().y1) && Objects.equals(y2, other.get().y2);\n } else\n return false;\n }\n\n @Override\n public double intersectionArea(Rectangle r) {\n if (!intersects(r))\n return 0;\n else {\n return create(max(x1, r.x1()), max(y1, r.y1()), min(x2, r.x2()), min(y2, r.y2()))\n .area();\n }\n }\n\n @Override\n public Geometry geometry() {\n return this;\n }\n\n private static double max(double a, double b) {\n if (a < b)\n return b;\n else\n return a;\n }\n\n private static double min(double a, double b) {\n if (a < b)\n return a;\n else\n return b;\n }\n\n @Override\n public double perimeter() {\n return 2 * (x2 - x1) + 2 * (y2 - y1);\n }\n\n @Override\n public double area() {\n return (x2 - x1) * (y2 - y1);\n }\n\n @Override\n public boolean isDoublePrecision() {\n return true;\n }\n\n}", "public final class RectangleFloat implements Rectangle {\n public final float x1, y1, x2, y2;\n\n private RectangleFloat(float x1, float y1, float x2, float y2) {\n Preconditions.checkArgument(x2 >= x1);\n Preconditions.checkArgument(y2 >= y1);\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n\n public static Rectangle create(float x1, float y1, float x2, float y2) {\n return new RectangleFloat(x1, y1, x2, y2);\n }\n\n @Override\n public double x1() {\n return x1;\n }\n\n @Override\n public double y1() {\n return y1;\n }\n\n @Override\n public double x2() {\n return x2;\n }\n\n @Override\n public double y2() {\n return y2;\n }\n\n @Override\n public double area() {\n return (x2 - x1) * (y2 - y1);\n }\n\n @Override\n public Rectangle add(Rectangle r) {\n if (r.isDoublePrecision()) {\n return RectangleDouble.create(min(x1, r.x1()), min(y1, r.y1()), max(x2, r.x2()),\n max(y2, r.y2()));\n } else if (r instanceof RectangleFloat) {\n RectangleFloat rf = (RectangleFloat) r;\n return RectangleFloat.create(min(x1, rf.x1), min(y1, rf.y1), max(x2, rf.x2),\n max(y2, rf.y2));\n } else {\n PointFloat rf = (PointFloat) r;\n return RectangleFloat.create(min(x1, rf.xFloat()), min(y1, rf.yFloat()),\n max(x2, rf.xFloat()), max(y2, rf.yFloat()));\n }\n }\n\n @Override\n public boolean contains(double x, double y) {\n return x >= x1 && x <= x2 && y >= y1 && y <= y2;\n }\n\n @Override\n public boolean intersects(Rectangle r) {\n return GeometryUtil.intersects(x1, y1, x2, y2, r.x1(), r.y1(), r.x2(), r.y2());\n }\n\n @Override\n public double distance(Rectangle r) {\n return GeometryUtil.distance(x1, y1, x2, y2, r.x1(), r.y1(), r.x2(), r.y2());\n }\n\n @Override\n public Rectangle mbr() {\n return this;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(x1, y1, x2, y2);\n }\n\n @Override\n public boolean equals(Object obj) {\n Optional<RectangleFloat> other = ObjectsHelper.asClass(obj, RectangleFloat.class);\n if (other.isPresent()) {\n return Objects.equals(x1, other.get().x1) && Objects.equals(x2, other.get().x2)\n && Objects.equals(y1, other.get().y1) && Objects.equals(y2, other.get().y2);\n } else\n return false;\n }\n\n @Override\n public double intersectionArea(Rectangle r) {\n if (!intersects(r))\n return 0;\n else\n return RectangleDouble\n .create(max(x1, r.x1()), max(y1, r.y1()), min(x2, r.x2()), min(y2, r.y2()))\n .area();\n }\n\n @Override\n public double perimeter() {\n return 2 * (x2 - x1) + 2 * (y2 - y1);\n }\n\n @Override\n public Geometry geometry() {\n return this;\n }\n\n @Override\n public boolean isDoublePrecision() {\n return false;\n }\n\n @Override\n public String toString() {\n return \"Rectangle [x1=\" + x1 + \", y1=\" + y1 + \", x2=\" + x2 + \", y2=\" + y2 + \"]\";\n }\n\n}" ]
import com.github.davidmoten.guavamini.annotations.VisibleForTesting; import com.github.davidmoten.rtree.geometry.internal.CircleDouble; import com.github.davidmoten.rtree.geometry.internal.CircleFloat; import com.github.davidmoten.rtree.geometry.internal.LineDouble; import com.github.davidmoten.rtree.geometry.internal.LineFloat; import com.github.davidmoten.rtree.geometry.internal.PointDouble; import com.github.davidmoten.rtree.geometry.internal.PointFloat; import com.github.davidmoten.rtree.geometry.internal.RectangleDouble; import com.github.davidmoten.rtree.geometry.internal.RectangleFloat;
package com.github.davidmoten.rtree.geometry; public final class Geometries { private Geometries() { // prevent instantiation } public static Point point(double x, double y) {
return PointDouble.create(x, y);
4
e-Spirit/basicworkflows
src/main/java/com/espirit/moddev/basicworkflows/release/WorkflowObject.java
[ "public class FsException extends RuntimeException {\n\n private static final long serialVersionUID = -1010220755632543938L;\n\n /**\n * Throws an exception.\n */\n public FsException() {\n super();\n }\n}", "public class FsLocale {\n\n /**\n * The current locale.\n */\n private Locale locale;\n\n /**\n * The current workflowScriptContext.\n */\n private WorkflowScriptContext workflowScriptContext;\n\n /**\n * The current context (for WorkflowStatusProvider).\n */\n private BaseContext baseContext;\n\n /**\n * Logger class.\n */\n public static final Class<?> LOGGER = FsLocale.class;\n\n /**\n * Constructor for FsLocale.\n *\n * @param baseContext The baseContext of webedit (for WorkflowStatusProvider).\n */\n public FsLocale(BaseContext baseContext) {\n WebeditUiAgent uiAgent = baseContext.requireSpecialist(WebeditUiAgent.TYPE);\n set(uiAgent.getDisplayLanguage().getLocale());\n this.baseContext = baseContext;\n }\n\n\n /**\n * Constructor for FsLocale.\n *\n * @param workflowScriptContext The workflowScriptContext from the workflow.\n */\n public FsLocale(WorkflowScriptContext workflowScriptContext) {\n this.workflowScriptContext = workflowScriptContext;\n if (workflowScriptContext.is(BaseContext.Env.WEBEDIT)) {\n WebeditUiAgent uiAgent = workflowScriptContext.requireSpecialist(WebeditUiAgent.TYPE);\n set(uiAgent.getDisplayLanguage().getLocale());\n } else {\n try {\n UIAgent uiAgent = workflowScriptContext.requireSpecialist(UIAgent.TYPE);\n set(uiAgent.getDisplayLanguage().getLocale());\n } catch (IllegalStateException e) {\n // catch exception for integration test case\n set(Locale.getDefault());\n Logging.logWarning(\"Falling back to default locale: \" + Locale.getDefault(), e, LOGGER);\n }\n }\n }\n\n /**\n * Setter for the field locale.\n *\n * @param locale The locale to set.\n */\n private void set(Locale locale) {\n this.locale = locale;\n }\n\n /**\n * Method to get the current locale.\n *\n * @return the current locale.\n */\n public Locale get() {\n return locale;\n }\n\n /**\n * Method to get the current language.\n *\n * @return the current language.\n */\n public Language getLanguage() {\n if (workflowScriptContext == null) {\n LanguageAgent languageAgent = baseContext.requestSpecialist(LanguageAgent.TYPE);\n Language language = languageAgent.getMasterLanguage();\n for (Language lang : languageAgent.getLanguages()) {\n if (lang.getLocale().equals(locale)) {\n language = lang;\n break;\n }\n }\n return language;\n } else {\n return workflowScriptContext.getProject().getLanguage(locale.getLanguage().toUpperCase());\n }\n }\n\n\n}", "public class ReferenceResult {\n\n /**\n * This variable determines if only media is referenced.\n */\n private boolean onlyMedia;\n /**\n * This variable determines if all referenced non media elements are released.\n */\n private boolean notMediaReleased;\n /**\n * This variable determines if all referenced elements are released.\n */\n private boolean allObjectsReleased;\n /**\n * This variable determines if there are broken references.\n */\n private boolean noBrokenReferences;\n /**\n * This variable determines if there are no objects in a workflow.\n */\n private boolean noObjectsInWorkflow;\n\n /**\n * Constructor for ReferenceResult.\n */\n public ReferenceResult() {\n onlyMedia = true;\n notMediaReleased = true;\n allObjectsReleased = true;\n noBrokenReferences = true;\n noObjectsInWorkflow = true;\n }\n\n /**\n * Is broken references.\n *\n * @return the boolean\n */\n public boolean isNoBrokenReferences() {\n return noBrokenReferences;\n }\n\n /**\n * Sets broken references.\n *\n * @param noBrokenReferences the broken references\n */\n public void setNoBrokenReferences(boolean noBrokenReferences) {\n this.noBrokenReferences = noBrokenReferences;\n }\n\n /**\n * Method to check if only media is referenced.\n *\n * @return true if only media is referenced.\n */\n private boolean isOnlyMedia() {\n return onlyMedia;\n }\n\n /**\n * Setter for the field onlyMedia.\n *\n * @param onlyMedia Set to false if not only media is referenced.\n */\n public void setOnlyMedia(boolean onlyMedia) {\n this.onlyMedia = onlyMedia;\n }\n\n /**\n * Method to check if all non media elements are released.\n *\n * @return true if not media and released.\n */\n private boolean isNotMediaReleased() {\n return notMediaReleased;\n }\n\n /**\n * Setter for the field notMediaReleased.\n *\n * @param notMediaReleased Set to false if not a medium and not/never released.\n */\n public void setNotMediaReleased(boolean notMediaReleased) {\n this.notMediaReleased = notMediaReleased;\n }\n\n /**\n * Method to check if all objects are released.\n *\n * @return true if all objects are released.\n */\n private boolean isAllObjectsReleased() {\n return allObjectsReleased;\n }\n\n /**\n * Setter for the field allObjectsReleased.\n *\n * @param allObjectsReleased Set to false if not all objects are released.\n */\n public void setAllObjectsReleased(boolean allObjectsReleased) {\n this.allObjectsReleased = allObjectsReleased;\n }\n\n /**\n * Checks if there are any release issues.\n *\n * @param releaseWithMedia the release with media\n * @return true if it has release issues\n */\n public boolean hasReleaseIssues(boolean releaseWithMedia) {\n boolean allReleased = false;\n\n // check result if can be released\n if (isOnlyMedia() && releaseWithMedia) {\n Logging.logWarning(\"Is only media and checked\", getClass());\n allReleased = true;\n } else if (isNotMediaReleased() && releaseWithMedia) {\n Logging.logWarning(\"All non media released and checked\", getClass());\n allReleased = true;\n } else if (isAllObjectsReleased() && !releaseWithMedia) {\n Logging.logWarning(\"Everything released and not checked\", getClass());\n allReleased = true;\n }\n\n return !(allReleased && isNoBrokenReferences() && hasNoObjectsInWorkflow());\n }\n\n /**\n * Setter for the field allObjectsReleased.\n *\n * @param noObjectsInWorkflow Set to false some objects are in a workflow.\n */\n public void setNoObjectsInWorkflow(boolean noObjectsInWorkflow) {\n this.noObjectsInWorkflow = noObjectsInWorkflow;\n }\n\n /**\n * Check if there are no objects in a workflow.\n *\n * @return the boolean\n */\n private boolean hasNoObjectsInWorkflow() {\n return noObjectsInWorkflow;\n }\n}", "public interface WorkflowConstants {\n\n /**\n * The package name of the resource bundle.\n */\n String MESSAGES = \"com.espirit.moddev.basicworkflows.Messages\";\n\n /**\n * String representation of true.\n */\n String TRUE = \"true\";\n\n /**\n * String representation of false.\n */\n String FALSE = \"false\";\n\n /**\n * Key for context in executable's parameters.\n */\n String CONTEXT = \"context\";\n\n /**\n * Resource bundle key for error message title.\n */\n String ERROR_MSG = \"errorMsg\";\n\n /**\n * Resource bundle key for delete failed message.\n */\n String DELETE_FAILED = \"deleteFailed\";\n\n /**\n * Resource bundle key for release failed message.\n */\n String RELEASE_FAILED = \"releaseFailed\";\n\n /**\n * Key to suppress dialog for testing.\n */\n String WF_SUPPRESS_DIALOG = \"wfSuppressDialog\";\n\n /**\n * Resource bundle key for warning message.\n */\n String WARNING = \"warning\";\n\n /**\n * Key that identifies the releasePageRefElements.\n */\n String RELEASE_PAGEREF_ELEMENTS = \"releasePageRefElements\";\n\n /**\n * Key that identifies the relatedPageRefElements.\n */\n String RELATED_PAGEREF_ELEMENTS = \"relatedPageRefElements\";\n\n String WF_NOT_RELEASED_ELEMENTS = \"wfNotReleasedElements\";\n\n String WF_BROKEN_REFERENCES = \"wfBrokenReferences\";\n\n String IMAGE_HAS_REFERENCES = \"wfImageHasReferences\";\n\n String IMAGE_FOLDER_HAS_REFERENCES = \"wfImageFolderHasReferences\";\n\n String WF_RECURSIVE_CHILDREN = \"wfRecursiveChildren\";\n\n String MEDIA_FORM_REFNAME = \"wf_releasewmedia\";\n\n String RECURSIVE_FORM_REFNAME = \"wf_releaseRecursively\";\n\n String WF_OBJECTS_IN_WORKFLOW = \"wfObjectsInWorkflow\";\n}", "public class WorkflowSessionHelper {\n\n\tprivate WorkflowSessionHelper() {}\n\n\n\tpublic static Map<String, IDProvider.UidType> readMapFromSession(final WorkflowScriptContext workflowScriptContext, final String key) {\n\t\tfinal Map<String, IDProvider.UidType> map = readObjectFromSession(workflowScriptContext, key);\n\t\treturn map == null ? Collections.<String, IDProvider.UidType> emptyMap() : map;\n\t}\n\n\n\tpublic static boolean readBooleanFromSession(final WorkflowScriptContext workflowScriptContext, final String key) {\n\t\tfinal Boolean value = readObjectFromSession(workflowScriptContext, key);\n\t\treturn value != null && value;\n\t}\n\n\n\t/**\n\t * Read object from session.\n\t *\n\t * @param <T> the type parameter\n\t * @param workflowScriptContext the workflow script context\n\t * @param key the key\n\t * @return the t\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T> T readObjectFromSession(final WorkflowScriptContext workflowScriptContext, final String key) {\n\t\treturn (T) workflowScriptContext.getSession().get(key); // NOSONAR\n\t}\n}" ]
import com.espirit.moddev.basicworkflows.util.FsException; import com.espirit.moddev.basicworkflows.util.FsLocale; import com.espirit.moddev.basicworkflows.util.ReferenceResult; import com.espirit.moddev.basicworkflows.util.WorkflowConstants; import com.espirit.moddev.basicworkflows.util.WorkflowSessionHelper; import de.espirit.common.TypedFilter; import de.espirit.common.base.Logging; import de.espirit.common.util.Listable; import de.espirit.firstspirit.access.BaseContext; import de.espirit.firstspirit.access.ReferenceEntry; import de.espirit.firstspirit.access.store.IDProvider; import de.espirit.firstspirit.access.store.Store; import de.espirit.firstspirit.access.store.StoreElement; import de.espirit.firstspirit.access.store.contentstore.Content2; import de.espirit.firstspirit.access.store.contentstore.ContentFolder; import de.espirit.firstspirit.access.store.contentstore.ContentStoreRoot; import de.espirit.firstspirit.access.store.contentstore.ContentWorkflowable; import de.espirit.firstspirit.access.store.globalstore.GCAFolder; import de.espirit.firstspirit.access.store.globalstore.GCAPage; import de.espirit.firstspirit.access.store.globalstore.ProjectProperties; import de.espirit.firstspirit.access.store.mediastore.Media; import de.espirit.firstspirit.access.store.mediastore.MediaFolder; import de.espirit.firstspirit.access.store.pagestore.Content2Section; import de.espirit.firstspirit.access.store.pagestore.Page; import de.espirit.firstspirit.access.store.pagestore.PageFolder; import de.espirit.firstspirit.access.store.pagestore.Section; import de.espirit.firstspirit.access.store.sitestore.DocumentGroup; import de.espirit.firstspirit.access.store.sitestore.PageRef; import de.espirit.firstspirit.access.store.sitestore.PageRefFolder; import de.espirit.firstspirit.access.store.sitestore.SiteStoreFolder; import de.espirit.firstspirit.access.store.templatestore.Query; import de.espirit.firstspirit.access.store.templatestore.TemplateStoreElement; import de.espirit.firstspirit.access.store.templatestore.WorkflowScriptContext; import de.espirit.firstspirit.agency.StoreAgent; import de.espirit.or.schema.Entity; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set;
/* * BasicWorkflows Module * %% * Copyright (C) 2012 - 2018 e-Spirit AG * %% * 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.espirit.moddev.basicworkflows.release; /** * This class provides methods to get the references of the workflow object and store them in the session. * * @author stephan * @since 1.0 */ class WorkflowObject { /** * The storeElement to use. */ private StoreElement storeElement; private StoreElement startElement; /** * The workflowScriptContext from the workflow. */ private WorkflowScriptContext workflowScriptContext; /** * The content2 object from the workflow. */ private Content2 content2; /** * The Entity to use. */ private Entity entity; /** * The ResourceBundle that contains language specific labels. */ private ResourceBundle bundle; /** * The logging class to use. */ public static final Class<?> LOGGER = WorkflowObject.class; private boolean releaseRecursively = false; private final Set<IDProvider> recursiveChildrenList = new HashSet<>(); /** * Constructor for WorkflowObject. * * @param workflowScriptContext The workflowScriptContext from the workflow. */ WorkflowObject(final WorkflowScriptContext workflowScriptContext) { this.workflowScriptContext = workflowScriptContext; ResourceBundle.clearCache(); bundle = ResourceBundle.getBundle(WorkflowConstants.MESSAGES, new FsLocale(workflowScriptContext).get()); if (workflowScriptContext.getWorkflowable() instanceof ContentWorkflowable) { content2 = ((ContentWorkflowable) workflowScriptContext.getWorkflowable()).getContent(); entity = ((ContentWorkflowable) workflowScriptContext.getWorkflowable()).getEntity(); } else { storeElement = (StoreElement) workflowScriptContext.getWorkflowable(); startElement = (StoreElement) workflowScriptContext.getWorkflowable(); } // get elements from recursive release final Map<Long, Store.Type> childrenIdMap = WorkflowSessionHelper.readObjectFromSession(workflowScriptContext, WorkflowConstants.WF_RECURSIVE_CHILDREN); if (childrenIdMap != null && !childrenIdMap.isEmpty()) { final StoreAgent storeAgent = workflowScriptContext.requireSpecialist(StoreAgent.TYPE); for (final Map.Entry<Long, Store.Type> childrenId : childrenIdMap.entrySet()) { recursiveChildrenList.add(storeAgent.getStore(childrenId.getValue()).getStoreElement(childrenId.getKey())); } } } /** * This method gets the referenced objects from the workflow object (StoreElement) that prevent the release. * * @param releaseWithMedia Determines if media references should also be checked * @return a list of elements that reference the workflow object. */ Set<Object> getRefObjectsFromStoreElement(final boolean releaseWithMedia, final boolean recursive) { return getRefObjectsFromStoreElement(releaseWithMedia, recursive, storeElement); } /** * This method gets the referenced objects from the workflow object (StoreElement) that prevent the release. * * @param releaseWithMedia Determines if media references should also be checked * @return a list of elements that reference the workflow object. */ private Set<Object> getRefObjectsFromStoreElement(final boolean releaseWithMedia, final boolean recursive, StoreElement storeElement) { Set<Object> referencedObjects = new HashSet<>(); if (isPageRef(storeElement)) { // add outgoing references referencedObjects.addAll(getReferences(releaseWithMedia, storeElement)); // add outgoing references of referenced page if it is not released final Page page = ((PageRef) storeElement).getPage(); addOutgoingReferences(page, referencedObjects, releaseWithMedia); final Set<Object> refObjectsFromSection = getRefObjectsFromSection(page, releaseWithMedia); referencedObjects.addAll(refObjectsFromSection); } else if (recursive && storeElement instanceof SiteStoreFolder) { for (IDProvider idProvider : storeElement.getChildren(IDProvider.class)) { referencedObjects.addAll(getRefObjectsFromStoreElement(releaseWithMedia, true, idProvider)); } } else if (isValidStoreElement()) { // add outgoing references referencedObjects.addAll(getReferences(releaseWithMedia, storeElement)); if (isPage(storeElement)) { final Set<Object> refObjectsFromSection = getRefObjectsFromSection(storeElement, releaseWithMedia); referencedObjects.addAll(refObjectsFromSection); } } else if (storeElement instanceof Content2) { //Element is a content2 object -> aborting"
workflowScriptContext.gotoErrorState(bundle.getString("releaseC2notPossible"), new FsException());
0
wenerme/bbvm
jbbvm/bbvm-core/src/test/java/me/wener/bbvm/BasmTester.java
[ "public interface ImageManager extends ResourceManager<ImageManager, ImageResource> {\n /**\n * @param file Resource name\n * @param index Resource index start from 0\n */\n ImageResource load(String file, int index);\n\n /**\n * @return Mutable directories to search the resource\n */\n List<String> getResourceDirectory();\n\n @Override\n default String getType() {\n return \"image\";\n }\n}", "public interface InputManager {\n\n boolean isKeyPressed(int key);\n\n /**\n * @return Wait any key or mouse click.\n */\n int waitKey();\n\n /**\n * Test is there any key press or mouse click.\n */\n int inKey();\n\n String inKeyString();\n\n /**\n * @return read a string, use Enter of confirm.\n */\n String readText();\n\n default int makeClickKey(int x, int y) {\n return x | 0x80000000 | (y << 16);\n }\n\n default int getX(int key) {\n return key & 0xFFFF;\n }\n\n default int getY(int key) {\n return key >>> 16 ^ 0x8000;\n }\n}", "public interface PageManager extends ResourceManager<PageManager, PageResource> {\n\n PageResource getScreen();\n\n int getWidth();\n\n int getHeight();\n\n PageManager setSize(int w, int h);\n\n @Override\n default String getType() {\n return \"page\";\n }\n}", "public class Swings implements DeviceConstants {\n static {\n IntEnums.cache(FontType.class);\n }\n\n public static Module module() {\n return new SwingModule();\n }\n\n static <T> T checkMissing(ResourceManager mgr, int handler, T v) {\n if (v == null) {\n throw new ResourceMissingException(String.format(\"%s #%s not exists\", mgr.getType(), handler), handler);\n }\n return v;\n }\n}", "public class Dumper {\n // region 数据 dump\n\n public static String hexDumpReadable(ByteBuf buf) {\n if (buf.readableBytes() == 0) {\n return \"00000000 \\n\";\n }\n\n return hexDump(Arrays.copyOfRange(buf.array(), buf.readerIndex(), buf.readableBytes()), buf.readerIndex());\n }\n\n public static String hexDumpOut(byte[] buf) {\n String dump = hexDump(buf);\n System.out.println(dump);\n return dump;\n }\n\n public static String hexDump(byte[] bytes) {\n return hexDump(bytes, 0);\n }\n\n public static String hexDump(byte[] bytes, int index) {\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n try {\n HexDump.dump(bytes, 0, os, index);\n } catch (IOException e) {\n Throwables.propagate(e);\n }\n return new String(os.toByteArray());\n }\n\n // endregion\n\n}" ]
import com.google.common.base.Throwables; import com.google.inject.Guice; import com.google.inject.Injector; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import me.wener.bbvm.asm.BBAsmParser; import me.wener.bbvm.asm.ParseException; import me.wener.bbvm.dev.ImageManager; import me.wener.bbvm.dev.InputManager; import me.wener.bbvm.dev.PageManager; import me.wener.bbvm.dev.swing.Swings; import me.wener.bbvm.util.Dumper; import me.wener.bbvm.vm.*; import me.wener.bbvm.vm.invoke.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.*; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Scanner; import static org.junit.Assert.assertNull;
package me.wener.bbvm; /** * @author wener * @since 15/12/13 */ public class BasmTester { private final static Logger log = LoggerFactory.getLogger(BasmTester.class); private static final Config DEFAULT_CONFIG = ConfigFactory.parseString("charset=UTF-8,test-io=true"); private final ByteArrayOutputStream out; private final InputInvoke in; private final Charset charset; // Parse basm // Compare with bin // Extract io from basm // Run // Compare io File basmFile; @Inject SystemInvokeManager systemInvokeManager; private Config c; private PrintStream printStream = System.out; @Inject private VM vm; private String basmContent; private BBAsmParser parser; private TestSpec io = new TestSpec(); private Injector injector; private boolean doTest = true; public BasmTester() { this(DEFAULT_CONFIG); } public BasmTester(Config config) { this.c = config; if (c != DEFAULT_CONFIG) { c = c.withFallback(DEFAULT_CONFIG); } this.charset = Charset.forName(c.getString("charset")); VMConfig.Builder builder = new VMConfig.Builder() .withModule(Swings.module()) .charset(charset); injector = Guice.createInjector(new VirtualMachineModule(builder.build())); injector.injectMembers(this); injector.getInstance(ImageManager.class).getResourceDirectory().add("../bbvm-test/image"); out = new ByteArrayOutputStream(); in = new InputInvoke(); // TODO Need a way to make up the input and output PageManager manager = injector.getInstance(PageManager.class); if (c.getBoolean("test-io")) { systemInvokeManager.register(new OutputInvoke((s) -> { try { out.write(s.getBytes()); } catch (IOException e) { Throwables.propagate(e); } manager.getScreen().draw(s); }), in); } else { systemInvokeManager.register(new OutputInvoke((s) -> { manager.getScreen().draw(s); }), new InputInvoke().setSupplier(() -> injector.getInstance(InputManager.class).readText())); } systemInvokeManager.register(GraphInvoke.class, BasicInvoke.class, FileInvoke.class, KeyInvoke.class); } public BasmTester setPrintStream(PrintStream printStream) { this.printStream = printStream; return this; } public BasmTester init(File basm) { log.info("Init basm tester {}", basm); basmFile = basm; try { basmContent = new String(Files.readAllBytes(basm.toPath()), charset); } catch (IOException e) { throw Throwables.propagate(e); } parser = new BBAsmParser(new StringReader(basmContent)); parser.setCharset(charset); io.clear().accept(basmContent); return this; } public void run() { out.reset(); Scanner scanner = new Scanner(io.output().toString()); in.setSupplier(scanner::nextLine); try { parser.Parse(); parser.getAssemblies().stream().forEach(s -> printStream.printf("%02d %s\n", s.getLine(), s.toAssembly())); } catch (ParseException e) { Throwables.propagate(e); } int length = parser.estimateAddress(); printStream.printf("Estimate length is %s\n", length); printStream.printf("Expected output \n%s\nWith input\n%s\n", io.output(), io.input()); parser.checkLabel(); ByteBuf buf = Unpooled.buffer(length).order(ByteOrder.LITTLE_ENDIAN); parser.write(buf); printStream.println(basmContent);
printStream.println(Dumper.hexDumpReadable(buf));
4
wtud/tsap
tsap/src/org/tribler/tsap/downloads/DownloadActivity.java
[ "public class Torrent implements Serializable {\n\n\tprivate static final long serialVersionUID = 1619276011406943212L;\n\n\tprivate String name;\n\tprivate String infoHash;\n\tprivate long size;\n\tprivate int seeders;\n\tprivate int leechers;\n\tprivate File thumbnailFile = null;\n\tprivate String category;\n\n\t/**\n\t * Constructor: initializes the instance variables\n\t * \n\t * @param name\n\t * The name of the torrent\n\t * @param infoHash\n\t * The infohash of the torrent\n\t * @param size\n\t * The size of the torrent\n\t * @param seeders\n\t * The number of seeders of the torrent\n\t * @param leechers\n\t * The number of leechers of the torrent\n\t * @param category\n\t * The category of the torrent\n\t */\n\tpublic Torrent(String name, String infoHash, long size, int seeders,\n\t\t\tint leechers, String category) {\n\t\tthis.name = name;\n\t\tthis.infoHash = infoHash;\n\t\tthis.size = size;\n\t\tthis.seeders = seeders;\n\t\tthis.leechers = leechers;\n\t\tthis.category = category;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name\n\t * the name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * @return the infoHash\n\t */\n\tpublic String getInfoHash() {\n\t\treturn infoHash;\n\t}\n\n\t/**\n\t * @param infoHash\n\t * the infoHash to set\n\t */\n\tpublic void setInfoHash(String infoHash) {\n\t\tthis.infoHash = infoHash;\n\t}\n\n\t/**\n\t * @return the size\n\t */\n\tpublic long getSize() {\n\t\treturn size;\n\t}\n\n\t/**\n\t * @param size\n\t * the size to set\n\t */\n\tpublic void setSize(long size) {\n\t\tthis.size = size;\n\t}\n\n\t/**\n\t * @return the seeders\n\t */\n\tpublic int getSeeders() {\n\t\treturn seeders;\n\t}\n\n\t/**\n\t * @param seeders\n\t * the seeders to set\n\t */\n\tpublic void setSeeders(int seeders) {\n\t\tthis.seeders = seeders;\n\t}\n\n\t/**\n\t * @return the leechers\n\t */\n\tpublic int getLeechers() {\n\t\treturn leechers;\n\t}\n\n\t/**\n\t * @param leechers\n\t * the leechers to set\n\t */\n\tpublic void setLeechers(int leechers) {\n\t\tthis.leechers = leechers;\n\t}\n\n\t/**\n\t * @return the thumbnailFile\n\t */\n\tpublic File getThumbnailFile() {\n\t\treturn thumbnailFile;\n\t}\n\n\t/**\n\t * @param thumbnailFile\n\t * the thumbnailFile to set\n\t */\n\tpublic void setThumbnailFile(File thumbnailFile) {\n\t\tthis.thumbnailFile = thumbnailFile;\n\t}\n\n\t/**\n\t * @return the category\n\t */\n\tpublic String getCategory() {\n\t\treturn category;\n\t}\n\n\t/**\n\t * @param category\n\t * the category to set\n\t */\n\tpublic void setCategory(String category) {\n\t\tthis.category = category;\n\t}\n\n\t/**\n\t * @return the health of the torrent\n\t */\n\tpublic TORRENT_HEALTH getHealth() {\n\t\tif (seeders == -1 || leechers == -1) {\n\t\t\treturn TORRENT_HEALTH.UNKNOWN;\n\t\t}\n\n\t\tif (seeders == 0) {\n\t\t\treturn TORRENT_HEALTH.RED;\n\t\t}\n\n\t\treturn ((leechers / seeders) > 0.5) ? TORRENT_HEALTH.YELLOW\n\t\t\t\t: TORRENT_HEALTH.GREEN;\n\t}\n\n\t/**\n\t * @return the string representation of a torrent (=name)\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\t\n\t/**\n\t* The default equals function, only checks on infohash\n\t* @param obj The object to be compared with\n\t* @return True if equal infohashes, otherwise false.\n\t*/\n\tpublic boolean equals(Object obj)\n\t{\n\t\t// Pre-check if we are the same\n\t\tif (this == obj)\n\t\treturn true;\n\t\t\n\t\t// Only check infohash if it's actually a ThumbItem\n\t\tif (!(obj instanceof Torrent))\n\t\treturn false;\n\t\t\n\t\t// Compare infohashes\n\t\treturn ((Torrent) obj).getInfoHash().equals(this.getInfoHash());\n\t}\n\n}", "public class PlayButtonListener implements OnClickListener, IPollListener {\n\n\tprivate final int POLLER_INTERVAL = 1000; // in ms\n\n\tprivate Torrent torrent;\n\tprivate String infoHash;\n\tprivate boolean needsToBeDownloaded;\n\tprivate MainThreadPoller mPoller;\n\tprivate VODDialogFragment vodDialog;\n\tprivate AlertDialog aDialog;\n\tprivate boolean inVODMode = false;\n\tprivate Activity mActivity;\n\tprivate Download mDownload;\n\n\t/**\n\t * @param torrent\n\t * The torrent of a which an info screen was opened\n\t * @param activity\n\t * The activity in which the button resides\n\t * @param needsToBeDownloaded\n\t * Indicates whether the torrent still needs to be downloaded\n\t */\n\tpublic PlayButtonListener(Torrent torrent, Activity activity,\n\t\t\tboolean needsToBeDownloaded) {\n\t\tthis.torrent = torrent;\n\t\tthis.infoHash = torrent.getInfoHash();\n\t\tthis.needsToBeDownloaded = needsToBeDownloaded;\n\t\tthis.mActivity = activity;\n\t\tthis.mPoller = new MainThreadPoller(this, POLLER_INTERVAL, mActivity);\n\t}\n\n\t/**\n\t * When the 'Play video' button is clicked, this method will start\n\t * downloading the torrent (if necessary), disable the button and show the\n\t * VOD dialog\n\t */\n\t@Override\n\tpublic void onClick(View buttonClicked) {\n\t\t// start downloading the torrent\n\t\tButton button = (Button) buttonClicked;\n\t\tif (needsToBeDownloaded) {\n\t\t\tstartDownload();\n\t\t}\n\n\t\t// disable the play button\n\t\tbutton.setEnabled(false);\n\n\t\t// start waiting for VOD\n\t\tvodDialog = new VODDialogFragment(mPoller, button);\n\t\tvodDialog.show(mActivity.getFragmentManager(), \"wait_vod\");\n\t\tmPoller.start();\n\t}\n\n\t/**\n\t * Starts downloading the torrent\n\t */\n\tprivate void startDownload() {\n\t\tXMLRPCDownloadManager.getInstance().downloadTorrent(infoHash,\n\t\t\t\ttorrent.getName());\n\t}\n\n\t/**\n\t * Called when the Poller returns: starts streaming the video when its ready\n\t * or updates the message of the vod dialog to the current download status\n\t */\n\t@Override\n\tpublic void onPoll() {\n\t\tXMLRPCDownloadManager.getInstance().getProgressInfo(infoHash);\n\t\tmDownload = XMLRPCDownloadManager.getInstance().getCurrentDownload();\n\t\taDialog = (AlertDialog) vodDialog.getDialog();\n\t\tif (mDownload != null) {\n\t\t\tif (!mDownload.getTorrent().getInfoHash().equals(infoHash))\n\t\t\t\treturn;\n\n\t\t\tif (mDownload.isVODPlayable())\n\t\t\t\tstartStreaming();\n\t\t\telse\n\t\t\t\tupdate();\n\t\t}\n\t}\n\n\t/**\n\t * Starts streaming the video with VLC and cleans up the dialog and poller\n\t */\n\tprivate void startStreaming() {\n\t\tUri videoLink = XMLRPCDownloadManager.getInstance().getVideoUri();\n\t\tif (videoLink != null) {\n\t\t\tIntent intent = new Intent(Intent.ACTION_VIEW,\n\t\t\t\t\tXMLRPCDownloadManager.getInstance().getVideoUri(),\n\t\t\t\t\tmActivity.getApplicationContext(),\n\t\t\t\t\tVideoPlayerActivity.class);\n\t\t\tmActivity.startActivity(intent);\n\t\t\taDialog.cancel();\n\t\t} else\n\t\t\taDialog.setMessage(\"No video file could be found in the torrent\");\n\n\t\tmPoller.stop();\n\t}\n\n\t/**\n\t * Starts downloading in vod mode if necessary and updates the dialog\n\t */\n\tprivate void update() {\n\t\tint statusCode = mDownload.getDownloadStatus().getStatus();\n\t\tif (statusCode == 3 && !inVODMode) {\n\t\t\tXMLRPCDownloadManager.getInstance().startVOD(infoHash);\n\t\t\tinVODMode = true;\n\t\t}\n\t\tupdateDialog();\n\t}\n\n\t/**\n\t * Updates the message of the dialog to the current download status\n\t */\n\tprivate void updateDialog() {\n\t\tif (aDialog != null) {\n\t\t\tint statusCode = mDownload.getDownloadStatus().getStatus();\n\t\t\tif (statusCode == 3)\n\t\t\t\tupdateVODMessage();\n\t\t\telse\n\t\t\t\tupdateMessageToStatus(statusCode);\n\t\t}\n\t}\n\n\t/**\n\t * Updates the dialog message to show the VOD ETA\n\t */\n\tprivate void updateVODMessage() {\n\t\taDialog.setMessage(\"Video starts playing in about \"\n\t\t\t\t+ Utility.convertSecondsToString(mDownload.getVOD_ETA())\n\t\t\t\t+ \" (\"\n\t\t\t\t+ Utility.convertBytesPerSecToString(mDownload\n\t\t\t\t\t\t.getDownloadStatus().getDownloadSpeed()) + \").\");\n\t}\n\n\t/**\n\t * Updated the dialog message to the current status\n\t * \n\t * @param statusCode\n\t * The status code of the download\n\t */\n\tprivate void updateMessageToStatus(int statusCode) {\n\t\taDialog.setMessage(\"Download status: \"\n\t\t\t\t+ Utility.convertDownloadStateIntToMessage(statusCode)\n\t\t\t\t+ ((statusCode == 2) ? \" (\"\n\t\t\t\t\t\t+ Math.round(mDownload.getDownloadStatus()\n\t\t\t\t\t\t\t\t.getProgress() * 100) + \"%)\" : \"\"));\n\t}\n}", "public class MainThreadPoller extends Poller {\n\tprivate Activity mActivity;\n\n\t/**\n\t * Initialized the poller\n\t * \n\t * @param listener\n\t * @param interval\n\t * @param activity\n\t */\n\tpublic MainThreadPoller(IPollListener listener, long interval,\n\t\t\tActivity activity) {\n\t\tsuper(listener, interval);\n\t\tmActivity = activity;\n\t}\n\n\t/**\n\t * Create a TimerTask that runs the onPoll method of the listener on the UI\n\t * thread\n\t */\n\t@Override\n\tprotected TimerTask MakeTimerTask() {\n\t\tfinal Runnable callOnPoll = new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tmListener.onPoll();\n\t\t\t}\n\t\t};\n\t\treturn new TimerTask() {\n\t\t\tpublic void run() {\n\t\t\t\tmActivity.runOnUiThread(callOnPoll);\n\t\t\t}\n\t\t};\n\t}\n}", "public interface IPollListener {\n\tpublic void onPoll();\n}", "public class ThumbnailUtils {\n\n\t/**\n\t * Loads the thumbnail of the file into mImageView\n\t * \n\t * @param file\n\t * The location of the thumbnail\n\t * @param mImageView\n\t * The view to load the image into\n\t * @param context\n\t * The context of the view\n\t */\n\tpublic static void loadThumbnail(File file, ImageView mImageView,\n\t\t\tContext context) {\n\t\tfloat dens = context.getResources().getDisplayMetrics().density;\n\t\tint thumbWidth = (int) (100 * dens);\n\t\tint thumbHeight = (int) (150 * dens);\n\t\tPicasso.with(context).load(file).placeholder(R.drawable.default_thumb)\n\t\t\t\t.resize(thumbWidth, thumbHeight).into(mImageView);\n\t}\n\n\t/**\n\t * Loads the default thumbnail into imageView\n\t * \n\t * @param imageView\n\t * The view to load the image into\n\t * @param context\n\t * The context of the view\n\t */\n\tpublic static void loadDefaultThumbnail(ImageView imageView, Context context) {\n\t\tloadThumbnail(null, imageView, context);\n\t}\n\n\t/**\n\t * Returns the thumbnail location of the torrent specified by infoHash (if\n\t * it exists)\n\t * \n\t * @param infoHash\n\t * The infohash of the torrent\n\t * @return the thumbnail location of the torrent specified by infoHash (if\n\t * it exists)\n\t */\n\tpublic static File getThumbnailLocation(final String infoHash) {\n\t\tFile baseDirectory = Settings.getThumbFolder();\n\t\tif (baseDirectory == null || !baseDirectory.isDirectory()) {\n\t\t\tLog.e(\"ThumbnailUtils\",\n\t\t\t\t\t\"The collected_torrent_files thumbnailfolder could not be found\");\n\t\t\treturn null;\n\t\t}\n\n\t\tFile thumbsDirectory = new File(baseDirectory, \"thumbs-\" + infoHash);\n\t\tif (!thumbsDirectory.exists()) {\n\t\t\tLog.d(\"ThumbnailUtils\", \"No thumbnailfolder found for \" + infoHash);\n\t\t\treturn null;\n\t\t}\n\n\t\tFile thumbsSubDirectory = null;\n\t\tfor (File file : thumbsDirectory.listFiles()) {\n\t\t\tif (file.isDirectory()) {\n\t\t\t\tthumbsSubDirectory = file;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (thumbsSubDirectory == null) {\n\t\t\tLog.d(\"ThumbnailUtils\", \"No thumbnail subfolder found for \"\n\t\t\t\t\t+ infoHash);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn findImage(thumbsSubDirectory);\n\t}\n\n\t/**\n\t * Returns the location of a thumbnail\n\t * \n\t * @param directory\n\t * The directory to look for a thumnail\n\t * @return the location of a thumbnail\n\t */\n\tprivate static File findImage(File directory) {\n\t\tFile[] foundImages = directory.listFiles(new FilenameFilter() {\n\t\t\t@Override\n\t\t\tpublic boolean accept(File file, String name) {\n\t\t\t\treturn name.endsWith(\".png\") || name.endsWith(\".gif\")\n\t\t\t\t\t\t|| name.endsWith(\".jpg\") || name.endsWith(\".jpeg\");\n\t\t\t}\n\t\t});\n\n\t\t// TODO: Find the best one\n\t\tif (foundImages.length > 0) {\n\t\t\treturn foundImages[0];\n\t\t} else {\n\t\t\tLog.d(\"ThumbnailUtils\", \"No thumbnailimages found: \"\n\t\t\t\t\t+ foundImages.length);\n\t\t\treturn null;\n\t\t}\n\t}\n}", "public class Utility {\n\n\t/**\n\t * Converts a number of seconds to a sensible string that can be shown to\n\t * the user.\n\t * \n\t * @param seconds\n\t * Number of seconds\n\t * @return A user friendly string\n\t */\n\tpublic static String convertSecondsToString(double seconds) {\n\t\tif (seconds < 10) {\n\t\t\treturn \"a few seconds\";\n\t\t} else if (seconds < 60) {\n\t\t\treturn \"about \" + (Math.round(seconds / 10) * 10) + \" seconds\";\n\t\t} else if (seconds < 3600) {\n\t\t\tlong value = Math.round(seconds / 60);\n\t\t\treturn \"about \" + value + \" minute\" + ((value > 1) ? \"s\" : \"\");\n\t\t} else if (seconds < 24 * 3600) {\n\t\t\tlong value = (Math.round(seconds / 3600));\n\t\t\treturn \"about \" + value + \" hour\" + ((value > 1) ? \"s\" : \"\");\n\t\t} else {\n\t\t\treturn \"more than a day\";\n\t\t}\n\t}\n\n\t/**\n\t * Converts an amount of bytes into a nicely formatted String. It adds the\n\t * correct prefix like KB or GB and limits the precision to one number\n\t * behind the point.\n\t * \n\t * @param size\n\t * The amount of bytes.\n\t * @return A string in the format NNN.NXB\n\t */\n\tpublic static String convertBytesToString(double size) {\n\t\tString prefixes[] = { \" B\", \" kB\", \" MB\", \" GB\", \" TB\", \" PB\" };\n\t\tint prefix = 0;\n\t\tString minus;\n\t\tif (size < 0) {\n\t\t\tsize = -size;\n\t\t\tminus = \"-\";\n\t\t} else {\n\t\t\tminus = \"\";\n\t\t}\n\t\twhile (size > 1000 && prefix < prefixes.length - 1) {\n\t\t\tsize /= 1000;\n\t\t\tprefix++;\n\t\t}\n\t\tString intString = minus + String.valueOf((int) size);\n\t\tif (prefix == 0 || size == (int) size) {\n\t\t\treturn intString + prefixes[prefix];\n\t\t} else {\n\t\t\treturn intString + \".\"\n\t\t\t\t\t+ String.valueOf(size - (int) size).charAt(2)\n\t\t\t\t\t+ prefixes[prefix];\n\t\t}\n\t}\n\n\t/**\n\t * Does the same as convertBytesToString, but adds /s to indicate it's bytes\n\t * per second\n\t * \n\t * @param speed\n\t * the amount of bytes per second\n\t * @return A string in the format NNN.NXB/s\n\t */\n\tpublic static String convertBytesPerSecToString(double speed) {\n\t\treturn convertBytesToString(speed) + \"/s\";\n\t}\n\n\t/**\n\t * Converts the Tribler state code of a download into a readable message.\n\t * \n\t * @param state\n\t * Tribler state code\n\t * @return The message corresponding to the code\n\t */\n\tpublic static String convertDownloadStateIntToMessage(int state) {\n\t\tswitch (state) {\n\t\tcase 1:\n\t\t\treturn \"Allocating disk space\";\n\t\tcase 2:\n\t\t\treturn \"Waiting for hash check\";\n\t\tcase 3:\n\t\t\treturn \"Downloading\";\n\t\tcase 4:\n\t\t\treturn \"Seeding\";\n\t\tcase 5:\n\t\t\treturn \"Stopped\";\n\t\tcase 6:\n\t\t\treturn \"Stopped because of an error\";\n\t\tcase 7:\n\t\t\treturn \"Acquiring metadata\";\n\t\tdefault:\n\t\t\treturn \"Invalid state\";\n\t\t}\n\t}\n\n\t/**\n\t * Returns the value belonging to key if it exists in the map, otherwise it\n\t * retursn defaultValue\n\t * \n\t * @param map\n\t * The map to search for the value\n\t * @param key\n\t * The key to look for\n\t * @param defaultValue\n\t * The value that is returned when the map doesn't contain the\n\t * key\n\t * @return\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T> T getFromMap(Map<String, Object> map, String key,\n\t\t\tT defaultValue) {\n\t\tT returnValue = (T) map.get(key);\n\t\tif (returnValue == null) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn returnValue;\n\t\t}\n\t}\n}" ]
import org.tribler.tsap.R; import org.tribler.tsap.Torrent; import org.tribler.tsap.streaming.PlayButtonListener; import org.tribler.tsap.util.MainThreadPoller; import org.tribler.tsap.util.Poller.IPollListener; import org.tribler.tsap.util.ThumbnailUtils; import org.tribler.tsap.util.Utility; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView;
package org.tribler.tsap.downloads; /** * Activity that shows detailed information of a download * * @author Dirk Schut & Niels Spruit * */ public class DownloadActivity extends Activity implements IPollListener { private ActionBar mActionBar; private Download mDownload; private Torrent mTorrent; private View mView;
private MainThreadPoller mPoller;
2
guiguito/AIRShare
shAIRe/src/main/java/com/ggt/airshare/httpserver/ShAIReHttpServer.java
[ "public class UrlShortener {\n\n private static UrlShortener mInstance;\n\n private static AQuery mAQuery;\n\n private static final String ERROR_MESSAGE = \"Url shortening failed\";\n\n private UrlShortener(Context context) {\n if (mAQuery == null) {\n mAQuery = new AQuery(context);\n }\n }\n\n public static UrlShortener getInstance(Context context) {\n if (mInstance == null) {\n mInstance = new UrlShortener(context);\n }\n return mInstance;\n }\n\n\t/* Google service */\n\n private static final String URL_GOOGLE_SHORTENER_SERVICE = \"https://www.googleapis.com/urlshortener/v1/url\";\n private static final String URL_GOOGLE_SHORTENER_SERVICE_API_KEY = \"?key=AIzaSyBLgWRPpTgIZcXt6Ya-wbOM_D_kn3NJl4k\";\n private static final String LONG_URL_KEY = \"longUrl\";\n private static final String ID_KEY = \"id\";\n\n public void shortenUrlonGoogle(final String sourceUrl,\n final UrlShortenerListener googleUrlShortenerListener) {\n JSONObject input = new JSONObject();\n try {\n input.putOpt(LONG_URL_KEY, sourceUrl);\n } catch (JSONException e1) {\n // cant'happen\n }\n // TODO activate key on google api console\n mAQuery.post(URL_GOOGLE_SHORTENER_SERVICE /*\n * +\n\t\t\t\t\t\t\t\t\t\t\t\t * URL_GOOGLE_SHORTENER_SERVICE_API_KEY\n\t\t\t\t\t\t\t\t\t\t\t\t */, input, JSONObject.class,\n new AjaxCallback<JSONObject>() {\n @Override\n public void callback(String url, JSONObject jsonobject,\n AjaxStatus status) {\n super.callback(url, jsonobject, status);\n try {\n if (status.getCode() == HttpsURLConnection.HTTP_OK\n && jsonobject != null\n && jsonobject.getString(LONG_URL_KEY) != null) {\n googleUrlShortenerListener.onUrlShortened(\n sourceUrl, jsonobject.getString(ID_KEY));\n } else {\n googleUrlShortenerListener\n .onUrlShorteningFailed(sourceUrl,\n new UrlShortenerException(\n ERROR_MESSAGE));\n }\n } catch (JSONException e) {\n googleUrlShortenerListener.onUrlShorteningFailed(\n sourceUrl,\n new UrlShortenerException(ERROR_MESSAGE\n + \" : \" + e.getMessage()));\n }\n }\n });\n }\n\n\t/* is.gd service */\n\n private static final String URL_IS_GD_SHORTENER_SERVICE = \"http://is.gd/create.php?format=json&url=%s\";\n private static final String SHORT_URL_KEY = \"shorturl\";\n\n public void shortenUrlonIsGd(final String sourceUrl,\n final UrlShortenerListener googleUrlShortenerListener) {\n mAQuery.ajax(\n String.format(URL_IS_GD_SHORTENER_SERVICE,\n URLEncoder.encode(sourceUrl)), JSONObject.class,\n new AjaxCallback<JSONObject>() {\n @Override\n public void callback(String url, JSONObject jsonobject,\n AjaxStatus status) {\n super.callback(url, jsonobject, status);\n try {\n if (status.getCode() == HttpsURLConnection.HTTP_OK\n && jsonobject != null\n && jsonobject.getString(SHORT_URL_KEY) != null) {\n googleUrlShortenerListener.onUrlShortened(\n sourceUrl,\n jsonobject.getString(SHORT_URL_KEY));\n } else {\n googleUrlShortenerListener\n .onUrlShorteningFailed(sourceUrl,\n new UrlShortenerException(\n ERROR_MESSAGE));\n }\n } catch (JSONException e) {\n googleUrlShortenerListener.onUrlShorteningFailed(\n sourceUrl,\n new UrlShortenerException(ERROR_MESSAGE\n + \" : \" + e.getMessage()));\n }\n }\n });\n }\n\n /* shorten url on tiny url */\n private static final String URL_TINY_URL_SHORTENER_SERVICE = \"http://tiny-url.info/api/v1/create\";\n private static final String URL_SHORTEN_KEY = \"shorturl\";\n\n public void shortenUrlonTinyUrl(final String sourceUrl,\n final UrlShortenerListener googleUrlShortenerListener) {\n Map<String, String> params = new HashMap<String, String>();\n params.put(\"format\", \"json\");\n params.put(\"apikey\", \"8206D9G737DD879F69C\");\n params.put(\"provider\", \"clicky_me\");\n params.put(\"url\", sourceUrl);\n mAQuery.ajax(URL_TINY_URL_SHORTENER_SERVICE, params, JSONObject.class,\n new AjaxCallback<JSONObject>() {\n @Override\n public void callback(String url, JSONObject jsonobject,\n AjaxStatus status) {\n try {\n if (status.getCode() == HttpsURLConnection.HTTP_OK\n && jsonobject != null\n && jsonobject.getString(URL_SHORTEN_KEY) != null) {\n googleUrlShortenerListener.onUrlShortened(\n sourceUrl,\n jsonobject.getString(URL_SHORTEN_KEY));\n } else {\n googleUrlShortenerListener\n .onUrlShorteningFailed(sourceUrl,\n new UrlShortenerException(\n ERROR_MESSAGE));\n }\n } catch (JSONException e) {\n googleUrlShortenerListener.onUrlShorteningFailed(\n sourceUrl,\n new UrlShortenerException(ERROR_MESSAGE\n + \" : \" + e.getMessage()));\n }\n }\n });\n }\n}", "public class UrlShortenerException extends Exception {\n\n private static final long serialVersionUID = 6087218793856704661L;\n\n public UrlShortenerException(String message) {\n super(message);\n }\n\n}", "public interface UrlShortenerListener {\n\n public void onUrlShortened(String sourceUrl, String urlShortened);\n\n public void onUrlShorteningFailed(String sourceUrl, UrlShortenerException exception);\n}", "public class ContactsUtils {\n\n\tpublic static AddressBookParsedResult getContactDetailsFromUri(\n\t\t\tContext context, Uri contactUri) {\n\t\ttry {\n\t\t\tbyte[] vcard;\n\t\t\tString vcardString;\n\t\t\tInputStream stream;\n\t\t\tstream = context.getContentResolver().openInputStream(contactUri);\n\t\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\t\tbyte[] buffer = new byte[2048];\n\t\t\tint bytesRead;\n\t\t\twhile ((bytesRead = stream.read(buffer)) > 0) {\n\t\t\t\tbaos.write(buffer, 0, bytesRead);\n\t\t\t}\n\t\t\tvcard = baos.toByteArray();\n\t\t\tvcardString = new String(vcard, 0, vcard.length, \"UTF-8\");\n\t\t\tResult result = new Result(vcardString, vcard, null,\n\t\t\t\t\tBarcodeFormat.QR_CODE);\n\t\t\tParsedResult parsedResult = ResultParser.parseResult(result);\n\t\t\treturn (AddressBookParsedResult) parsedResult;\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}", "public class NetworkUtils {\n\n\tpublic static class WifiDetails {\n\t\tpublic String ipAddress;\n\t\tpublic String ssid;\n\t}\n\n\tprivate static final String LOG_TAG = \"NetworkUtils\";\n\n\tpublic static WifiDetails getWifiDetails(Context context) {\n\t\tWifiDetails wifiDetails = null;\n\t\tif (isWifiApActivated(context)) {\n\t\t\twifiDetails = new NetworkUtils.WifiDetails();\n\t\t\t// phone as HotSpot case\n\t\t\tWifiConfiguration wifiConfiguration = getWifiApConfiguration(context);\n\t\t\tif (wifiConfiguration != null) {\n\t\t\t\twifiDetails.ssid = wifiConfiguration.SSID;\n\t\t\t\twifiDetails.ipAddress = getWifiApIpAddress();\n\t\t\t}\n\t\t} else {\n\t\t\t// phone maybe connected on wifi normally\n\t\t\tConnectivityManager connManager = (ConnectivityManager) context\n\t\t\t\t\t.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\t\tNetworkInfo networkInfo = connManager\n\t\t\t\t\t.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\n\n\t\t\tif (networkInfo.isConnected()) {\n\t\t\t\twifiDetails = new NetworkUtils.WifiDetails();\n\t\t\t\tfinal WifiManager wifiManager = (WifiManager) context\n\t\t\t\t\t\t.getSystemService(Context.WIFI_SERVICE);\n\t\t\t\tfinal WifiInfo connectionInfo = wifiManager.getConnectionInfo();\n\t\t\t\tif (connectionInfo != null\n\t\t\t\t\t\t&& !StringUtils.isBlank(connectionInfo.getSSID())) {\n\t\t\t\t\twifiDetails.ssid = connectionInfo.getSSID();\n\t\t\t\t}\n\t\t\t\tif (connectionInfo != null) {\n\t\t\t\t\twifiDetails.ipAddress = convertInToIpAddress(connectionInfo\n\t\t\t\t\t\t\t.getIpAddress());\n\t\t\t\t}\n\t\t\t\treturn wifiDetails;\n\t\t\t}\n\t\t}\n\n\t\treturn wifiDetails;\n\t}\n\n\tprivate static String getWifiApIpAddress() {\n\t\ttry {\n\t\t\tfor (Enumeration<NetworkInterface> en = NetworkInterface\n\t\t\t\t\t.getNetworkInterfaces(); en.hasMoreElements();) {\n\t\t\t\tNetworkInterface intf = en.nextElement();\n\t\t\t\tif (intf.getName().contains(\"wlan\")) {\n\t\t\t\t\tfor (Enumeration<InetAddress> enumIpAddr = intf\n\t\t\t\t\t\t\t.getInetAddresses(); enumIpAddr.hasMoreElements();) {\n\t\t\t\t\t\tInetAddress inetAddress = enumIpAddr.nextElement();\n\t\t\t\t\t\tif (!inetAddress.isLoopbackAddress()\n\t\t\t\t\t\t\t\t&& (inetAddress.getAddress().length == 4)) {\n\t\t\t\t\t\t\tLog.d(LOG_TAG, inetAddress.getHostAddress());\n\t\t\t\t\t\t\treturn inetAddress.getHostAddress();\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} catch (SocketException ex) {\n\t\t\tLog.e(LOG_TAG, ex.toString());\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate static WifiConfiguration getWifiApConfiguration(Context context) {\n\t\tWifiConfiguration wifiConfiguration = null;\n\t\ttry {\n\t\t\tWifiManager manager = (WifiManager) context\n\t\t\t\t\t.getSystemService(Context.WIFI_SERVICE);\n\t\t\tMethod method = manager.getClass().getDeclaredMethod(\n\t\t\t\t\t\"getWifiApConfiguration\");\n\t\t\tmethod.setAccessible(true); // in the case of visibility change in\n\t\t\t// future APIs\n\t\t\twifiConfiguration = (WifiConfiguration) method.invoke(manager);\n\t\t} catch (NoSuchMethodException e) {\n\t\t} catch (IllegalArgumentException e) {\n\t\t} catch (IllegalAccessException e) {\n\t\t} catch (InvocationTargetException e) {\n\t\t}\n\t\treturn wifiConfiguration;\n\n\t}\n\n\tprivate static boolean isWifiApActivated(Context context) {\n\t\tboolean value = false;\n\t\ttry {\n\t\t\tWifiManager manager = (WifiManager) context\n\t\t\t\t\t.getSystemService(Context.WIFI_SERVICE);\n\t\t\tMethod method = manager.getClass().getDeclaredMethod(\n\t\t\t\t\t\"isWifiApEnabled\");\n\t\t\tmethod.setAccessible(true); // in the case of visibility change in\n\t\t\t// future APIs\n\t\t\tvalue = (Boolean) method.invoke(manager);\n\t\t} catch (NoSuchMethodException e) {\n\t\t} catch (IllegalArgumentException e) {\n\t\t} catch (IllegalAccessException e) {\n\t\t} catch (InvocationTargetException e) {\n\t\t}\n\t\treturn value;\n\t}\n\n\tprivate static String convertInToIpAddress(int ipAddress) {\n\t\tbyte[] bytes = BigInteger.valueOf(ipAddress).toByteArray();\n\t\tbyte[] bytes2 = new byte[4];\n\t\tbytes2[0] = bytes[3];\n\t\tbytes2[1] = bytes[2];\n\t\tbytes2[2] = bytes[1];\n\t\tbytes2[3] = bytes[0];\n\t\ttry {\n\t\t\tInetAddress address = InetAddress.getByAddress(bytes2);\n\t\t\treturn address.getHostAddress();\n\t\t} catch (UnknownHostException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}", "public class ShAIReConstants {\n\n\tprivate ShAIReConstants() {\n\n\t}\n\n\tpublic static final int SERVER_PORT = 5000;\n}", "public final class QRCodeEncoder {\n\n private static final String TAG = QRCodeEncoder.class.getSimpleName();\n\n private static final int WHITE = 0xFFFFFFFF;\n private static final int BLACK = 0xFF000000;\n\n private final Context activity;\n private String contents;\n private String displayContents;\n private String title;\n private BarcodeFormat format;\n private final int dimension;\n private final boolean useVCard;\n\n public QRCodeEncoder(Context activity, Intent intent, int dimension, boolean useVCard) throws WriterException {\n this.activity = activity;\n this.dimension = dimension;\n this.useVCard = useVCard;\n String action = intent.getAction();\n if (action.equals(Intents.Encode.ACTION)) {\n encodeContentsFromZXingIntent(intent);\n } else if (action.equals(Intent.ACTION_SEND)) {\n encodeContentsFromShareIntent(intent);\n }\n }\n\n String getContents() {\n return contents;\n }\n\n String getDisplayContents() {\n return displayContents;\n }\n\n String getTitle() {\n return title;\n }\n\n boolean isUseVCard() {\n return useVCard;\n }\n\n // It would be nice if the string encoding lived in the core ZXing library,\n // but we use platform specific code like PhoneNumberUtils, so it can't.\n private boolean encodeContentsFromZXingIntent(Intent intent) {\n // Default to QR_CODE if no format given.\n String formatString = intent.getStringExtra(Intents.Encode.FORMAT);\n format = null;\n if (formatString != null) {\n try {\n format = BarcodeFormat.valueOf(formatString);\n } catch (IllegalArgumentException iae) {\n // Ignore it then\n }\n }\n if (format == null || format == BarcodeFormat.QR_CODE) {\n String type = intent.getStringExtra(Intents.Encode.TYPE);\n if (type == null || type.isEmpty()) {\n return false;\n }\n this.format = BarcodeFormat.QR_CODE;\n encodeQRCodeContents(intent, type);\n } else {\n String data = intent.getStringExtra(Intents.Encode.DATA);\n if (data != null && !data.isEmpty()) {\n contents = data;\n displayContents = data;\n title = activity.getString(R.string.contents_text);\n }\n }\n return contents != null && !contents.isEmpty();\n }\n\n // Handles send intents from multitude of Android applications\n private void encodeContentsFromShareIntent(Intent intent) throws WriterException {\n // Check if this is a plain text encoding, or contact\n if (intent.hasExtra(Intent.EXTRA_STREAM)) {\n encodeFromStreamExtra(intent);\n } else {\n encodeFromTextExtras(intent);\n }\n }\n\n private void encodeFromTextExtras(Intent intent) throws WriterException {\n // Notice: Google Maps shares both URL and details in one text, bummer!\n String theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_TEXT));\n if (theContents == null) {\n theContents = ContactEncoder.trim(intent.getStringExtra(\"android.intent.extra.HTML_TEXT\"));\n // Intent.EXTRA_HTML_TEXT\n if (theContents == null) {\n theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_SUBJECT));\n if (theContents == null) {\n String[] emails = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);\n if (emails != null) {\n theContents = ContactEncoder.trim(emails[0]);\n } else {\n theContents = \"?\";\n }\n }\n }\n }\n\n // Trim text to avoid URL breaking.\n if (theContents == null || theContents.isEmpty()) {\n throw new WriterException(\"Empty EXTRA_TEXT\");\n }\n contents = theContents;\n // We only do QR code.\n format = BarcodeFormat.QR_CODE;\n if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {\n displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT);\n } else if (intent.hasExtra(Intent.EXTRA_TITLE)) {\n displayContents = intent.getStringExtra(Intent.EXTRA_TITLE);\n } else {\n displayContents = contents;\n }\n title = activity.getString(R.string.contents_text);\n }\n\n // Handles send intents from the Contacts app, retrieving a contact as a\n // VCARD.\n private void encodeFromStreamExtra(Intent intent) throws WriterException {\n format = BarcodeFormat.QR_CODE;\n Bundle bundle = intent.getExtras();\n if (bundle == null) {\n throw new WriterException(\"No extras\");\n }\n Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM);\n if (uri == null) {\n throw new WriterException(\"No EXTRA_STREAM\");\n }\n byte[] vcard;\n String vcardString;\n try {\n InputStream stream = activity.getContentResolver().openInputStream(uri);\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n byte[] buffer = new byte[2048];\n int bytesRead;\n while ((bytesRead = stream.read(buffer)) > 0) {\n baos.write(buffer, 0, bytesRead);\n }\n vcard = baos.toByteArray();\n vcardString = new String(vcard, 0, vcard.length, \"UTF-8\");\n } catch (IOException ioe) {\n throw new WriterException(ioe);\n }\n Log.d(TAG, \"Encoding share intent content:\");\n Log.d(TAG, vcardString);\n Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);\n ParsedResult parsedResult = ResultParser.parseResult(result);\n if (!(parsedResult instanceof AddressBookParsedResult)) {\n throw new WriterException(\"Result was not an address\");\n }\n encodeQRCodeContents((AddressBookParsedResult) parsedResult);\n if (contents == null || contents.isEmpty()) {\n throw new WriterException(\"No content to encode\");\n }\n }\n\n private void encodeQRCodeContents(Intent intent, String type) {\n if (type.equals(Contents.Type.TEXT)) {\n String data = intent.getStringExtra(Intents.Encode.DATA);\n if (data != null && !data.isEmpty()) {\n contents = data;\n displayContents = data;\n title = activity.getString(R.string.contents_text);\n }\n } else if (type.equals(Contents.Type.EMAIL)) {\n String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));\n if (data != null) {\n contents = \"mailto:\" + data;\n displayContents = data;\n title = activity.getString(R.string.contents_email);\n }\n } else if (type.equals(Contents.Type.PHONE)) {\n String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));\n if (data != null) {\n contents = \"tel:\" + data;\n displayContents = PhoneNumberUtils.formatNumber(data);\n title = activity.getString(R.string.contents_phone);\n }\n } else if (type.equals(Contents.Type.SMS)) {\n String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));\n if (data != null) {\n contents = \"sms:\" + data;\n displayContents = PhoneNumberUtils.formatNumber(data);\n title = activity.getString(R.string.contents_sms);\n }\n } else if (type.equals(Contents.Type.CONTACT)) {\n\n Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);\n if (bundle != null) {\n\n String name = bundle.getString(ContactsContract.Intents.Insert.NAME);\n String organization = bundle.getString(ContactsContract.Intents.Insert.COMPANY);\n String address = bundle.getString(ContactsContract.Intents.Insert.POSTAL);\n Collection<String> phones = new ArrayList<String>(Contents.PHONE_KEYS.length);\n for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {\n phones.add(bundle.getString(Contents.PHONE_KEYS[x]));\n }\n Collection<String> emails = new ArrayList<String>(Contents.EMAIL_KEYS.length);\n for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {\n emails.add(bundle.getString(Contents.EMAIL_KEYS[x]));\n }\n String url = bundle.getString(Contents.URL_KEY);\n Iterable<String> urls = url == null ? null : Collections.singletonList(url);\n String note = bundle.getString(Contents.NOTE_KEY);\n\n ContactEncoder mecardEncoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder();\n String[] encoded = mecardEncoder.encode(Collections.singleton(name),\n organization,\n Collections.singleton(address),\n phones,\n emails,\n urls,\n note);\n // Make sure we've encoded at least one field.\n if (!encoded[1].isEmpty()) {\n contents = encoded[0];\n displayContents = encoded[1];\n title = activity.getString(R.string.contents_contact);\n }\n\n }\n\n } else if (type.equals(Contents.Type.LOCATION)) {\n Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);\n if (bundle != null) {\n // These must use Bundle.getFloat(), not getDouble(), it's part\n // of the API.\n float latitude = bundle.getFloat(\"LAT\", Float.MAX_VALUE);\n float longitude = bundle.getFloat(\"LONG\", Float.MAX_VALUE);\n if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {\n contents = \"geo:\" + latitude + ',' + longitude;\n displayContents = latitude + \",\" + longitude;\n title = activity.getString(R.string.contents_location);\n }\n }\n }\n }\n\n private void encodeQRCodeContents(AddressBookParsedResult contact) {\n ContactEncoder encoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder();\n String[] encoded = encoder.encode(toIterable(contact.getNames()),\n contact.getOrg(),\n toIterable(contact.getAddresses()),\n toIterable(contact.getPhoneNumbers()),\n toIterable(contact.getEmails()),\n toIterable(contact.getURLs()),\n null);\n // Make sure we've encoded at least one field.\n if (!encoded[1].isEmpty()) {\n contents = encoded[0];\n displayContents = encoded[1];\n title = activity.getString(R.string.contents_contact);\n }\n }\n\n private static Iterable<String> toIterable(String[] values) {\n return values == null ? null : Arrays.asList(values);\n }\n\n public Bitmap encodeAsBitmap() throws WriterException {\n String contentsToEncode = contents;\n if (contentsToEncode == null) {\n return null;\n }\n Map<EncodeHintType, Object> hints = null;\n String encoding = guessAppropriateEncoding(contentsToEncode);\n if (encoding != null) {\n hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);\n hints.put(EncodeHintType.CHARACTER_SET, encoding);\n }\n BitMatrix result;\n try {\n result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);\n } catch (IllegalArgumentException iae) {\n // Unsupported format\n return null;\n }\n int width = result.getWidth();\n int height = result.getHeight();\n int[] pixels = new int[width * height];\n for (int y = 0; y < height; y++) {\n int offset = y * width;\n for (int x = 0; x < width; x++) {\n pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;\n }\n }\n\n Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n bitmap.setPixels(pixels, 0, width, 0, 0, width, height);\n return bitmap;\n }\n\n private static String guessAppropriateEncoding(CharSequence contents) {\n // Very crude at the moment\n for (int i = 0; i < contents.length(); i++) {\n if (contents.charAt(i) > 0xFF) {\n return \"UTF-8\";\n }\n }\n return null;\n }\n\n}", "public class FileUtils {\n private FileUtils() {\n } //private constructor to enforce Singleton pattern\n\n /**\n * TAG for log messages.\n */\n static final String TAG = \"FileUtils\";\n private static final boolean DEBUG = false; // Set to true to enable logging\n\n public static final String MIME_TYPE_AUDIO = \"audio/*\";\n public static final String MIME_TYPE_TEXT = \"text/*\";\n public static final String MIME_TYPE_IMAGE = \"image/*\";\n public static final String MIME_TYPE_VIDEO = \"video/*\";\n public static final String MIME_TYPE_APP = \"application/*\";\n\n public static final String HIDDEN_PREFIX = \".\";\n\n /**\n * Gets the extension of a file name, like \".png\" or \".jpg\".\n *\n * @param uri\n * @return Extension including the dot(\".\"); \"\" if there is no extension;\n * null if uri was null.\n */\n public static String getExtension(String uri) {\n if (uri == null) {\n return null;\n }\n\n int dot = uri.lastIndexOf(\".\");\n if (dot >= 0) {\n return uri.substring(dot);\n } else {\n // No extension.\n return \"\";\n }\n }\n\n /**\n * @return Whether the URI is a local one.\n */\n public static boolean isLocal(String url) {\n if (url != null && !url.startsWith(\"http://\") && !url.startsWith(\"https://\")) {\n return true;\n }\n return false;\n }\n\n /**\n * @return True if Uri is a MediaStore Uri.\n * @author paulburke\n */\n public static boolean isMediaUri(Uri uri) {\n return \"media\".equalsIgnoreCase(uri.getAuthority());\n }\n\n /**\n * Convert File into Uri.\n *\n * @param file\n * @return uri\n */\n public static Uri getUri(File file) {\n if (file != null) {\n return Uri.fromFile(file);\n }\n return null;\n }\n\n /**\n * Returns the path only (without file name).\n *\n * @param file\n * @return\n */\n public static File getPathWithoutFilename(File file) {\n if (file != null) {\n if (file.isDirectory()) {\n // no file to be split off. Return everything\n return file;\n } else {\n String filename = file.getName();\n String filepath = file.getAbsolutePath();\n\n // Construct path without file name.\n String pathwithoutname = filepath.substring(0,\n filepath.length() - filename.length());\n if (pathwithoutname.endsWith(\"/\")) {\n pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);\n }\n return new File(pathwithoutname);\n }\n }\n return null;\n }\n\n /**\n * @return The MIME type for the given file.\n */\n public static String getMimeType(File file) {\n\n String extension = getExtension(file.getName());\n\n if (extension.length() > 0) {\n String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));\n if (mimeType != null && !TextUtils.isEmpty(mimeType)) {\n return mimeType;\n }\n } else if (file.getPath().startsWith(\"http\")) {\n return \"text/url\";\n }\n\n return \"application/octet-stream\";\n }\n\n /**\n * @return The MIME type for the give Uri.\n */\n public static String getMimeType(Context context, Uri uri) {\n String path = getPath(context, uri);\n if (path != null && (path.startsWith(\"/\") || path.startsWith(\"http\"))) {\n File file = new File(path);\n return getMimeType(file);\n } else {\n return null;\n }\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is {@link LocalStorageProvider}.\n * @author paulburke\n */\n\n public static boolean isLocalStorageDocument(Uri uri) {\n return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is ExternalStorageProvider.\n * @author paulburke\n */\n public static boolean isExternalStorageDocument(Uri uri) {\n return \"com.android.externalstorage.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is DownloadsProvider.\n * @author paulburke\n */\n public static boolean isDownloadsDocument(Uri uri) {\n return \"com.android.providers.downloads.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is MediaProvider.\n * @author paulburke\n */\n public static boolean isMediaDocument(Uri uri) {\n return \"com.android.providers.media.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is Google Photos.\n */\n public static boolean isGooglePhotosUri(Uri uri) {\n return \"com.google.android.apps.photos.content\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is Google Drive.\n */\n public static boolean isGoogleDriveUri(Uri uri) {\n return \"com.google.android.apps.docs.storage\".equals(uri.getAuthority());\n }\n\n /**\n * Get the value of the data column for this Uri. This is useful for\n * MediaStore Uris, and other file-based ContentProviders.\n *\n * @param context The context.\n * @param uri The Uri to query.\n * @param selection (Optional) Filter used in the query.\n * @param selectionArgs (Optional) Selection arguments used in the query.\n * @return The value of the _data column, which is typically a file path.\n * @author paulburke\n */\n public static String getDataColumn(Context context, Uri uri, String selection,\n String[] selectionArgs) {\n\n Cursor cursor = null;\n final String column = \"_data\";\n final String[] projection = {\n column\n };\n\n try {\n cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,\n null);\n if (cursor != null && cursor.moveToFirst()) {\n if (DEBUG)\n DatabaseUtils.dumpCursor(cursor);\n\n final int column_index = cursor.getColumnIndexOrThrow(column);\n return cursor.getString(column_index);\n }\n } finally {\n if (cursor != null)\n cursor.close();\n }\n return null;\n }\n\n /**\n * Get a file path from a Uri. This will get the the path for Storage Access\n * Framework Documents, as well as the _data field for the MediaStore and\n * other file-based ContentProviders.<br>\n * <br>\n * Callers should check whether the path is local before assuming it\n * represents a local file.\n *\n * @param context The context.\n * @param uri The Uri to query.\n * @author paulburke\n * @see #isLocal(String)\n * @see #getFile(Context, Uri)\n */\n public static String getPath(final Context context, final Uri uri) {\n\n if (DEBUG)\n Log.d(TAG + \" File -\",\n \"Authority: \" + uri.getAuthority() +\n \", Fragment: \" + uri.getFragment() +\n \", Port: \" + uri.getPort() +\n \", Query: \" + uri.getQuery() +\n \", Scheme: \" + uri.getScheme() +\n \", Host: \" + uri.getHost() +\n \", Segments: \" + uri.getPathSegments().toString()\n );\n\n final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;\n\n // DocumentProvider\n if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {\n // LocalStorageProvider\n if (isLocalStorageDocument(uri)) {\n // The path is the id\n return DocumentsContract.getDocumentId(uri);\n }\n // ExternalStorageProvider\n else if (isExternalStorageDocument(uri)) {\n final String docId = DocumentsContract.getDocumentId(uri);\n final String[] split = docId.split(\":\");\n final String type = split[0];\n if (\"primary\".equalsIgnoreCase(type)) {\n return Environment.getExternalStorageDirectory() + \"/\" + split[1];\n }\n // TODO handle non-primary volumes\n }\n // DownloadsProvider\n else if (isDownloadsDocument(uri)) {\n\n final String id = DocumentsContract.getDocumentId(uri);\n final Uri contentUri = ContentUris.withAppendedId(\n Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id));\n\n return getDataColumn(context, contentUri, null, null);\n }\n // MediaProvider\n else if (isMediaDocument(uri)) {\n final String docId = DocumentsContract.getDocumentId(uri);\n final String[] split = docId.split(\":\");\n final String type = split[0];\n\n Uri contentUri = null;\n if (\"image\".equals(type)) {\n contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;\n } else if (\"video\".equals(type)) {\n contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;\n } else if (\"audio\".equals(type)) {\n contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;\n }\n\n final String selection = \"_id=?\";\n final String[] selectionArgs = new String[]{\n split[1]\n };\n\n return getDataColumn(context, contentUri, selection, selectionArgs);\n } else {\n //TODO handle google drive and one drive better !\n return null;\n }\n }\n // MediaStore (and general)\n else if (\"content\".equalsIgnoreCase(uri.getScheme())) {\n\n // Return the remote address\n if (isGooglePhotosUri(uri))\n return uri.getLastPathSegment();\n\n return getDataColumn(context, uri, null, null);\n }\n // File\n else if (\"file\".equalsIgnoreCase(uri.getScheme())) {\n return uri.getPath();\n }\n\n return null;\n }\n\n /**\n * Convert Uri into File, if possible.\n *\n * @return file A local file that the Uri was pointing to, or null if the\n * Uri is unsupported or pointed to a remote resource.\n * @author paulburke\n * @see #getPath(Context, Uri)\n */\n public static File getFile(Context context, Uri uri) {\n if (uri != null) {\n String path = getPath(context, uri);\n if (path != null && isLocal(path)) {\n return new File(path);\n }\n }\n return null;\n }\n\n /**\n * Get the file size in a human-readable string.\n *\n * @param size\n * @return\n * @author paulburke\n */\n public static String getReadableFileSize(int size) {\n final int BYTES_IN_KILOBYTES = 1024;\n final DecimalFormat dec = new DecimalFormat(\"###.#\");\n final String KILOBYTES = \" KB\";\n final String MEGABYTES = \" MB\";\n final String GIGABYTES = \" GB\";\n float fileSize = 0;\n String suffix = KILOBYTES;\n\n if (size > BYTES_IN_KILOBYTES) {\n fileSize = size / BYTES_IN_KILOBYTES;\n if (fileSize > BYTES_IN_KILOBYTES) {\n fileSize = fileSize / BYTES_IN_KILOBYTES;\n if (fileSize > BYTES_IN_KILOBYTES) {\n fileSize = fileSize / BYTES_IN_KILOBYTES;\n suffix = GIGABYTES;\n } else {\n suffix = MEGABYTES;\n }\n }\n }\n return String.valueOf(dec.format(fileSize) + suffix);\n }\n\n /**\n * Attempt to retrieve the thumbnail of given File from the MediaStore. This\n * should not be called on the UI thread.\n *\n * @param context\n * @param file\n * @return\n * @author paulburke\n */\n public static Bitmap getThumbnail(Context context, File file) {\n return getThumbnail(context, getUri(file), getMimeType(file));\n }\n\n /**\n * Attempt to retrieve the thumbnail of given Uri from the MediaStore. This\n * should not be called on the UI thread.\n *\n * @param context\n * @param uri\n * @return\n * @author paulburke\n */\n public static Bitmap getThumbnail(Context context, Uri uri) {\n return getThumbnail(context, uri, getMimeType(context, uri));\n }\n\n /**\n * Attempt to retrieve the thumbnail of given Uri from the MediaStore. This\n * should not be called on the UI thread.\n *\n * @param context\n * @param uri\n * @param mimeType\n * @return\n * @author paulburke\n */\n public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {\n if (DEBUG)\n Log.d(TAG, \"Attempting to get thumbnail\");\n\n if (!isMediaUri(uri)) {\n Log.e(TAG, \"You can only retrieve thumbnails for images and videos.\");\n return null;\n }\n\n Bitmap bm = null;\n if (uri != null) {\n final ContentResolver resolver = context.getContentResolver();\n Cursor cursor = null;\n try {\n cursor = resolver.query(uri, null, null, null, null);\n if (cursor.moveToFirst()) {\n final int id = cursor.getInt(0);\n if (DEBUG)\n Log.d(TAG, \"Got thumb ID: \" + id);\n\n if (mimeType.contains(\"video\")) {\n bm = MediaStore.Video.Thumbnails.getThumbnail(\n resolver,\n id,\n MediaStore.Video.Thumbnails.MINI_KIND,\n null);\n } else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {\n bm = MediaStore.Images.Thumbnails.getThumbnail(\n resolver,\n id,\n MediaStore.Images.Thumbnails.MINI_KIND,\n null);\n }\n }\n } catch (Exception e) {\n if (DEBUG)\n Log.e(TAG, \"getThumbnail\", e);\n } finally {\n if (cursor != null)\n cursor.close();\n }\n }\n return bm;\n }\n\n /**\n * File and folder comparator. TODO Expose sorting option method\n *\n * @author paulburke\n */\n public static Comparator<File> sComparator = new Comparator<File>() {\n @Override\n public int compare(File f1, File f2) {\n // Sort alphabetically by lower case, which is much cleaner\n return f1.getName().toLowerCase().compareTo(\n f2.getName().toLowerCase());\n }\n };\n\n /**\n * File (not directories) filter.\n *\n * @author paulburke\n */\n public static FileFilter sFileFilter = new FileFilter() {\n @Override\n public boolean accept(File file) {\n final String fileName = file.getName();\n // Return files only (not directories) and skip hidden files\n return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);\n }\n };\n\n /**\n * Folder (directories) filter.\n *\n * @author paulburke\n */\n public static FileFilter sDirFilter = new FileFilter() {\n @Override\n public boolean accept(File file) {\n final String fileName = file.getName();\n // Return directories only and skip hidden directories\n return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);\n }\n };\n\n /**\n * Get the Intent for selecting content to be used in an Intent Chooser.\n *\n * @return The intent for opening a file with Intent.createChooser()\n * @author paulburke\n */\n public static Intent createGetContentIntent() {\n // Implicitly allow the user to select a particular kind of data\n final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);\n // The MIME data type filter\n intent.setType(\"*/*\");\n // Only return URIs that can be opened with ContentResolver\n intent.addCategory(Intent.CATEGORY_OPENABLE);\n return intent;\n }\n}" ]
import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.text.TextUtils; import com.ggt.airshare.R; import com.ggt.airshare.urlshortener.UrlShortener; import com.ggt.airshare.urlshortener.UrlShortenerException; import com.ggt.airshare.urlshortener.UrlShortenerListener; import com.ggt.airshare.utils.ContactsUtils; import com.ggt.airshare.utils.HTMLUtils; import com.ggt.airshare.utils.NetworkUtils; import com.ggt.airshare.utils.ShAIReConstants; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.Intents; import com.google.zxing.client.android.encode.QRCodeEncoder; import com.google.zxing.client.result.AddressBookParsedResult; import com.ipaulpro.afilechooser.utils.FileUtils; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.Random;
package com.ggt.airshare.httpserver; /** * Sharing nano server . * * @author gduche */ public class ShAIReHttpServer extends NanoHTTPD implements UrlShortenerListener { private String mFilePath; private String mMimeType; private String mTextToShare; private Context mContext; private String mRealUrl; private String mRandomString; private QRCodeEncoder mQrCodeEncoder; private ShAIReHttpServerListener mShAIReHttpServerListener; private static final String GET_STRING = "GET"; private static final String URL_BEGIN = "http://"; public ShAIReHttpServer(Context context, ShAIReHttpServerListener shAIReHttpServerListener, Intent intent) throws IOException {
super(ShAIReConstants.SERVER_PORT, null);
5
Toberumono/WRF-Runner
src/toberumono/wrf/timing/NamelistTiming.java
[ "public class WRFRunnerComponentFactory<T> {\n\tprivate static final Map<Class<?>, WRFRunnerComponentFactory<?>> factories = new HashMap<>();\n\tprivate final Map<String, BiFunction<ScopedMap, Scope, T>> components;\n\tprivate String defaultComponentType;\n\tprivate BiFunction<ScopedMap, Scope, T> disabledComponentConstructor;\n\tprivate final Class<T> rootType;\n\t\n\tprivate WRFRunnerComponentFactory(Class<T> rootType, String defaultComponentType, BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tcomponents = new HashMap<>();\n\t\tthis.rootType = rootType;\n\t\tthis.defaultComponentType = defaultComponentType;\n\t\tthis.disabledComponentConstructor = disabledComponentConstructor;\n\t}\n\t\n\t/**\n\t * Retrieves the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param <T>\n\t * the type of the component to be generated\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} that is to be retrieved was created\n\t * @return an instance of {@link WRFRunnerComponentFactory} that produces components that are subclasses of {@code clazz}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t */\n\tpublic static <T> WRFRunnerComponentFactory<T> getFactory(Class<T> clazz) {\n\t\tsynchronized (factories) {\n\t\t\tif (!factories.containsKey(clazz))\n\t\t\t\tthrow new NoSuchFactoryException(\"The factory for \" + clazz.getName() + \" does not exist.\");\n\t\t\t@SuppressWarnings(\"unchecked\") WRFRunnerComponentFactory<T> factory = (WRFRunnerComponentFactory<T>) factories.get(clazz);\n\t\t\treturn factory;\n\t\t}\n\t}\n\t\n\t/**\n\t * Retrieves the {@link WRFRunnerComponentFactory} for the given {@link Class} if the {@link WRFRunnerComponentFactory} exists and updates its\n\t * {@code defaultComponentType} and {@code disabledComponentConstructor} if they are not {@code null}. Otherwise, it creates a\n\t * {@link WRFRunnerComponentFactory} for the given {@link Class} with the given {@code defaultComponentType} and\n\t * {@code disabledComponentConstructor}.\n\t * \n\t * @param <T>\n\t * the type of the component to be generated\n\t * @param clazz\n\t * the root {@link Class} of the component type for which the {@link WRFRunnerComponentFactory} is being created or retrieved\n\t * @param defaultComponentType\n\t * the name of the default component type as a {@link String}\n\t * @param disabledComponentConstructor\n\t * a {@link BiFunction} that returns an instance of the component that performs no action or equates to a disabled state\n\t * @return an instance of {@link WRFRunnerComponentFactory} that produces components that are subclasses of {@code clazz}\n\t */\n\tpublic static <T> WRFRunnerComponentFactory<T> createFactory(Class<T> clazz, String defaultComponentType, BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tsynchronized (factories) {\n\t\t\tif (factories.containsKey(clazz)) {\n\t\t\t\t@SuppressWarnings(\"unchecked\") WRFRunnerComponentFactory<T> factory = (WRFRunnerComponentFactory<T>) factories.get(clazz);\n\t\t\t\tif (defaultComponentType != null)\n\t\t\t\t\tfactory.setDefaultComponentType(defaultComponentType);\n\t\t\t\tif (disabledComponentConstructor != null)\n\t\t\t\t\tfactory.setDisabledComponentConstructor(disabledComponentConstructor);\n\t\t\t\treturn factory;\n\t\t\t}\n\t\t\tWRFRunnerComponentFactory<T> factory = new WRFRunnerComponentFactory<>(clazz, defaultComponentType, disabledComponentConstructor);\n\t\t\tfactories.put(clazz, factory);\n\t\t\treturn factory;\n\t\t}\n\t}\n\t\n\t/**\n\t * Adds the constructor for a named component type to the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param <T>\n\t * the type of the component to be constructed\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param type\n\t * the name of the component type\n\t * @param constructor\n\t * a {@link BiFunction} that takes the parameters that describe the component (as a {@link ScopedMap}) and the component's parent (as a\n\t * {@link Scope}) and constructs the component accordingly. For most components with implementing class {@code T}, this function should\n\t * be equivalent to {@code T::new}.\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t */\n\tpublic static <T> void addComponentConstructor(Class<T> clazz, String type, BiFunction<ScopedMap, Scope, T> constructor) {\n\t\tgetFactory(clazz).addComponentConstructor(type, constructor);\n\t}\n\t\n\t/**\n\t * Adds the constructor for a named component type to the {@link WRFRunnerComponentFactory}.\n\t * \n\t * @param type\n\t * the name of the component type\n\t * @param constructor\n\t * a {@link BiFunction} that takes the parameters that describe the component as a {@link ScopedMap} and the component's parent as a\n\t * {@link Scope} and constructs the component accordingly. For a component with implementing class {@code T}, this function should be\n\t * equivalent to {@code T::new}.\n\t */\n\tpublic void addComponentConstructor(String type, BiFunction<ScopedMap, Scope, T> constructor) {\n\t\tsynchronized (components) {\n\t\t\tcomponents.put(type, constructor);\n\t\t}\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} for the given {@link Class} to generate a new instance of the component defined by the given\n\t * {@code parameters} and {@code parent}.\n\t * \n\t * @param <T>\n\t * the type of the component to be returned\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code parameters} and {@code parent}\n\t * @see #generateComponent(ScopedMap, Scope)\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t */\n\tpublic static <T> T generateComponent(Class<T> clazz, ScopedMap parameters, Scope parent) {\n\t\treturn getFactory(clazz).generateComponent(parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} to generate a new instance of the component defined by the given {@code parameters} and\n\t * {@code parent}.\n\t * \n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code parameters} and {@code parent}\n\t * @see #generateComponent(Class, ScopedMap, Scope)\n\t */\n\tpublic T generateComponent(ScopedMap parameters, Scope parent) {\n\t\treturn generateComponent(parameters != null && parameters.containsKey(\"type\") ? parameters.get(\"type\").toString() : defaultComponentType, parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} for the given {@link Class} to generate a new instance of the component defined by the given\n\t * {@code type}, {@code parameters}, and {@code parent}.\n\t * \n\t * @param <T>\n\t * the type of the component to be returned\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param type\n\t * the name of the type of component described by the given parameters (this overrides the type field in the given parameters if it\n\t * exists\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code type}, {@code parameters}, and {@code parent}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #generateComponent(String, ScopedMap, Scope)\n\t */\n\tpublic static <T> T generateComponent(Class<T> clazz, String type, ScopedMap parameters, Scope parent) {\n\t\treturn getFactory(clazz).generateComponent(type, parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} to generate a new instance of the component defined by the given {@code type}, {@code parameters},\n\t * and {@code parent}.\n\t * \n\t * @param type\n\t * the name of the type of component described by the given parameters (this overrides the type field in the given parameters if it\n\t * exists\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the component defined by the given {@code type}, {@code parameters}, and {@code parent}\n\t * @see #generateComponent(Class, String, ScopedMap, Scope)\n\t */\n\tpublic T generateComponent(String type, ScopedMap parameters, Scope parent) {\n\t\tsynchronized (components) {\n\t\t\tif (type != null && type.equals(\"disabled\"))\n\t\t\t\treturn getDisabledComponentInstance(parameters, parent);\n\t\t\tif (parameters == null)\n\t\t\t\treturn implicitInheritance(parent);\n\t\t\tif (parameters.get(\"enabled\") instanceof Boolean && !((Boolean) parameters.get(\"enabled\")))\n\t\t\t\treturn getDisabledComponentInstance(parameters, parent);\n\t\t\tObject inherit = parameters.get(\"inherit\");\n\t\t\tif (inherit != null) {\n\t\t\t\tif (inherit instanceof String) //Then this is an explicit inheritance\n\t\t\t\t\tinherit = ScopedFormulaProcessor.process((String) inherit, parameters, null);\n\t\t\t\tif (inherit instanceof Boolean && (Boolean) inherit)\n\t\t\t\t\treturn implicitInheritance(parent);\n\t\t\t\tif (inherit instanceof ScopedMap) //Then this is scope-based inheritance\n\t\t\t\t\treturn generateComponent((ScopedMap) inherit, parent);\n\t\t\t\tif (rootType.isInstance(inherit))\n\t\t\t\t\treturn rootType.cast(inherit);\n\t\t\t}\n\t\t\treturn components.get(type != null ? type : defaultComponentType).apply(parameters, parent);\n\t\t}\n\t}\n\t\n\tprivate T implicitInheritance(Scope parent) {\n\t\tif (rootType.isInstance(parent))\n\t\t\treturn rootType.cast(parent);\n\t\tthrow new TypeHierarchyException(\"Cannot perform implicit full-object inheritance when the parent is of a different type.\");\n\t}\n\t\n\t/**\n\t * A convenience method for use with more complex inheritance structures, primarily in the form of custom scoping.\n\t * \n\t * @param parameters\n\t * parameters that define a component as a {@link ScopedMap}\n\t * @return {@code true} iff the component will be entirely inherited from its parent\n\t */\n\tpublic static boolean willInherit(ScopedMap parameters) {\n\t\treturn parameters == null || (parameters.containsKey(\"inherit\") && (!(parameters.get(\"inherit\") instanceof Boolean) || ((Boolean) parameters.get(\"inherit\"))));\n\t}\n\t\n\t/**\n\t * Sets the default component type for the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param type\n\t * the name of the new default component type as a {@link String}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #setDefaultComponentType(String)\n\t */\n\tpublic static void setDefaultComponentType(Class<?> clazz, String type) {\n\t\tgetFactory(clazz).setDefaultComponentType(type);\n\t}\n\t\n\t/**\n\t * Sets the default component type for the {@link WRFRunnerComponentFactory}.\n\t * \n\t * @param type\n\t * the name of the new default component type as a {@link String}\n\t * @see #setDefaultComponentType(Class, String)\n\t */\n\tpublic void setDefaultComponentType(String type) {\n\t\tsynchronized (components) {\n\t\t\tdefaultComponentType = type;\n\t\t}\n\t}\n\t\n\t/**\n\t * Sets the constructor used to create disabled instances of the component in the {@link WRFRunnerComponentFactory} for the given {@link Class}.\n\t * \n\t * @param <T>\n\t * the type of the component to be constructed\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param disabledComponentConstructor\n\t * a {@link BiFunction} that returns an instance of the component that performs no action and/or equates to a disabled state\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #setDisabledComponentConstructor(BiFunction)\n\t */\n\tpublic static <T> void setDisabledComponentConstructor(Class<T> clazz, BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tgetFactory(clazz).setDisabledComponentConstructor(disabledComponentConstructor);\n\t}\n\t\n\t/**\n\t * Sets the constructor used to create disabled instances of the component in the {@link WRFRunnerComponentFactory}.\n\t * \n\t * @param disabledComponentConstructor\n\t * a {@link BiFunction} that returns an instance of the component that performs no action and/or equates to a disabled state\n\t * @see #setDisabledComponentConstructor(BiFunction)\n\t */\n\tpublic void setDisabledComponentConstructor(BiFunction<ScopedMap, Scope, T> disabledComponentConstructor) {\n\t\tsynchronized (components) {\n\t\t\tthis.disabledComponentConstructor = disabledComponentConstructor;\n\t\t}\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} for the given {@link Class} to generate a new disabled instance of the component described by the\n\t * given {@code parameters} and {@code parent}.\n\t * \n\t * @param <T>\n\t * the type of the component to be returned\n\t * @param clazz\n\t * the {@link Class} provided when the {@link WRFRunnerComponentFactory} was created\n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the disabled type described by the given {@code parameters} and {@code parent}\n\t * @throws NoSuchFactoryException\n\t * if a {@link WRFRunnerComponentFactory} for the given {@link Class} does not exist\n\t * @see #getDisabledComponentInstance(ScopedMap, Scope)\n\t */\n\tpublic static <T> T getDisabledComponentInstance(Class<T> clazz, ScopedMap parameters, Scope parent) {\n\t\treturn getFactory(clazz).getDisabledComponentInstance(parameters, parent);\n\t}\n\t\n\t/**\n\t * Uses the {@link WRFRunnerComponentFactory} to generate a new disabled instance of the component described by the given {@code parameters} and\n\t * {@code parent}.\n\t * \n\t * @param parameters\n\t * the parameters that describe the component as a {@link ScopedMap}\n\t * @param parent\n\t * the component's parent as a {@link Scope}\n\t * @return a new instance of the disabled type described by the given {@code parameters} and {@code parent}\n\t * @see #getDisabledComponentInstance(Class, ScopedMap, Scope)\n\t */\n\tpublic T getDisabledComponentInstance(ScopedMap parameters, Scope parent) {\n\t\tsynchronized (components) {\n\t\t\treturn disabledComponentConstructor.apply(parameters, parent);\n\t\t}\n\t}\n}", "public class AbstractScope<T extends Scope> implements Scope {\n\tprivate final T parent;\n\tprivate final Map<String, ExceptedSupplier<Object>> namedItems;\n\t\n\t/**\n\t * Constructs the {@link AbstractScope} and builds the scopes variable table from fields and methods annotated with {@link NamedScopeValue}.\n\t * \n\t * @param parent\n\t * the parent {@link Scope}\n\t */\n\tpublic AbstractScope(T parent) {\n\t\tthis.parent = parent;\n\t\tnamedItems = new HashMap<>();\n\t\tfor (Field f : getClass().getFields())\n\t\t\taddFieldIfNamed(f);\n\t\tfor (Field f : getClass().getDeclaredFields()) //Second pass is to allow names declared in the current type to override those declared in its supertypes\n\t\t\taddFieldIfNamed(f);\n\t\tfor (Method m : getClass().getMethods())\n\t\t\taddMethodIfNamed(m);\n\t\tfor (Method m : getClass().getDeclaredMethods()) //Second pass is to allow names declared in the current type to override those declared in its supertypes\n\t\t\taddMethodIfNamed(m);\n\t}\n\t\n\tprivate void addFieldIfNamed(Field f) {\n\t\tNamedScopeValue nsv = f.getAnnotation(NamedScopeValue.class);\n\t\tif (nsv != null) {\n\t\t\tf.setAccessible(true);\n\t\t\taddNamedValue(nsv, nsv.asString() ? () -> (f.get(this) != null ? f.get(this).toString() : null) : () -> f.get(this));\n\t\t}\n\t}\n\t\n\tprivate void addMethodIfNamed(Method m) {\n\t\tNamedScopeValue nsv = m.getAnnotation(NamedScopeValue.class);\n\t\tif (nsv != null) {\n\t\t\tm.setAccessible(true);\n\t\t\taddNamedValue(nsv, nsv.asString() ? () -> (m.invoke(this) != null ? m.invoke(this).toString() : null) : () -> m.invoke(this));\n\t\t}\n\t}\n\t\n\tprivate void addNamedValue(NamedScopeValue nsv, ExceptedSupplier<Object> supplier) {\n\t\tfor (String name : nsv.value())\n\t\t\tnamedItems.put(name, supplier);\n\t}\n\t\n\t@Override\n\tpublic T getParent() {\n\t\treturn parent;\n\t}\n\t\n\t@Override\n\tpublic boolean hasValueByName(String name) {\n\t\treturn namedItems.containsKey(name);\n\t}\n\t\n\t@Override\n\tpublic Object getValueByName(String name) throws InvalidVariableAccessException {\n\t\ttry {\n\t\t\tif (namedItems.containsKey(name))\n\t\t\t\treturn namedItems.get(name).get();\n\t\t\telse\n\t\t\t\tthrow new InvalidVariableAccessException(\"'\" + name + \"' does not exist in the current scope.\");\n\t\t}\n\t\tcatch (Throwable t) {\n\t\t\tthrow new InvalidVariableAccessException(\"Could not access '\" + name + \"'.\", t);\n\t\t}\n\t}\n}", "public interface Scope {\n\t/**\n\t * @return the parent {@link Scope}; if this is the root of the {@link Scope} tree, this method returns {@code null}\n\t */\n\tpublic Scope getParent();\n\t\n\t/**\n\t * This method <i>only</i> checks the current {@link Scope Scope's} values - it does not query the parent {@link Scope}.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return the named variable's value if it exists\n\t * @throws InvalidVariableAccessException\n\t * if the current {@link Scope} (not including its parent {@link Scope}) does not contain a variable with the given name\n\t */\n\tpublic Object getValueByName(String name) throws InvalidVariableAccessException;\n\t\n\t/**\n\t * This method <i>only</i> checks the current {@link Scope Scope's} values - it does not query the parent {@link Scope}.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return {@code true} iff the current {@link Scope} (not including its parent {@link Scope}) contains a variable with the given name\n\t */\n\tpublic boolean hasValueByName(String name);\n\t\n\t/**\n\t * This method follows the {@link Scope} tree up to the root until it finds a variable with the given name.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return the named variable's value if it exists\n\t * @throws InvalidVariableAccessException\n\t * if the neither current {@link Scope} nor any of its parent {@link Scope Scopes} contain a variable with the given name\n\t */\n\tpublic default Object getScopedValueByName(String name) throws InvalidVariableAccessException {\n\t\tfor (Scope scope = this; scope != null; scope = scope.getParent())\n\t\t\tif (scope.hasValueByName(name))\n\t\t\t\treturn scope.getValueByName(name);\n\t\tthrow new InvalidVariableAccessException(\"Could not access \" + name);\n\t}\n\t\n\t/**\n\t * This method follows the {@link Scope} tree up to the root until it finds a variable with the given name.\n\t * \n\t * @param name\n\t * the name of the variable to retrieve as a {@link String}\n\t * @return {@code true} iff the current {@link Scope} or any of its parent {@link Scope Scopes} contain a variable with the given name\n\t */\n\tpublic default boolean hasScopedValueByName(String name) {\n\t\tfor (Scope scope = this; scope != null; scope = scope.getParent())\n\t\t\tif (scope.hasValueByName(name))\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n}", "public interface Clear extends Scope, TimingComponent {\n\t/**\n\t * The name that {@link Logger Loggers} in instances of {@link Clear} should be created from.\n\t */\n\tpublic static final String LOGGER_NAME = SIMULATION_LOGGER_ROOT + \".Clear\";\n}", "public interface Duration extends Scope, TimingComponent {\n\t/**\n\t * The name that {@link Logger Loggers} in instances of {@link Duration} should be created from.\n\t */\n\tpublic static final String LOGGER_NAME = SIMULATION_LOGGER_ROOT + \".Duration\";\n}", "public class NamelistDuration extends AbstractDuration {\n\tprivate int[] duration;\n\tprivate final NamelistSection timeControl;\n\t\n\t/**\n\t * Constructs a new instance of {@link NamelistDuration} based on the information in {@code timeControl}.\n\t * \n\t * @param timeControl\n\t * the \"time_control\" section of a {@link Namelist} file as a {@link NamelistSection}\n\t * @param parent\n\t * the parent {@link Scope}\n\t */\n\tpublic NamelistDuration(NamelistSection timeControl, Scope parent) {\n\t\tsuper(null, parent);\n\t\tthis.timeControl = timeControl;\n\t}\n\t\n\t@Override\n\tprotected Calendar doApply(Calendar base) {\n\t\tfor (int i = 0; i < duration.length; i++)\n\t\t\tbase.add(TIMING_FIELD_IDS.get(i), duration[i]);\n\t\treturn base;\n\t}\n\t\n\t@Override\n\tprotected void compute() {\n\t\tduration = new int[TIMING_FIELD_NAMES.size()];\n\t\tfor (int i = 0; i < duration.length; i++)\n\t\t\tif (timeControl.containsKey(\"run_\" + TIMING_FIELD_NAMES.get(i)))\n\t\t\t\tduration[i] = ((Number) timeControl.get(\"run_\" + TIMING_FIELD_NAMES.get(i)).get(0).value()).intValue();\n\t}\n}", "public interface Offset extends Scope, TimingComponent {\n\t/**\n\t * The name that {@link Logger Loggers} in instances of {@link Offset} should be created from.\n\t */\n\tpublic static final String LOGGER_NAME = SIMULATION_LOGGER_ROOT + \".Offset\";\n\t\n\t/**\n\t * @return {@code true} iff offsets should wrap according to the {@link Calendar Calendar's} model\n\t */\n\t@NamedScopeValue(\"does-wrap\")\n\tpublic boolean doesWrap();\n\t\n\t/**\n\t * Performs the steps necessary to apply the modifications specified by the {@link Offset} to the given {@link Calendar}.\n\t * \n\t * @param base\n\t * the {@link Calendar} to modify with the {@link Offset}\n\t * @param inPlace\n\t * whether the modification should be performed in place (if {@code false} then the {@link Calendar} is cloned before being modified)\n\t * @return {@code base} (or a copy thereof if {@code inPlace} is {@code false}) with the {@link Offset} applied\n\t */\n\t@Override\n\tpublic Calendar apply(Calendar base, boolean inPlace);\n}", "public interface Round extends Scope, TimingComponent {\n\t/**\n\t * The name that {@link Logger Loggers} in instances of {@link Round} should be created from.\n\t */\n\tpublic static final String LOGGER_NAME = SIMULATION_LOGGER_ROOT + \".Round\";\n}", "public class SimulationConstants {\n\t/**\n\t * The names of the valid timing fields. Used in conjunction with {@link #TIMING_FIELD_IDS}.\n\t * \n\t * @see #TIMING_FIELD_IDS\n\t */\n\tpublic static final List<String> TIMING_FIELD_NAMES = Collections.unmodifiableList(Arrays.asList(\"milliseconds\", \"seconds\", \"minutes\", \"hours\", \"days\", \"months\", \"years\"));\n\t/**\n\t * The IDs of the valid timing fields as they are defined in {@link Calendar}. Used in conjunction with {@link #TIMING_FIELD_NAMES}.\n\t * \n\t * @see #TIMING_FIELD_NAMES\n\t */\n\tpublic static final List<Integer> TIMING_FIELD_IDS = Collections.unmodifiableList(Arrays.asList(MILLISECOND, SECOND, MINUTE, HOUR_OF_DAY, DAY_OF_MONTH, MONTH, YEAR));\n\t/**\n\t * The name of the field used to identify the relative path to a {@link Module Module's} {@link Namelist}\n\t */\n\tpublic static final String NAMELIST_FIELD_NAME = \"namelist\";\n\t/**\n\t * The name of the timing subsection in the configuration JSON\n\t */\n\tpublic static final String TIMING_FIELD_NAME = \"timing\";\n\t/**\n\t * The name root {@link Logger} for all simulation components\n\t */\n\tpublic static final String SIMULATION_LOGGER_ROOT = \"WRFRunner.Simulation\";\n}" ]
import java.util.Calendar; import java.util.List; import java.util.stream.Collectors; import toberumono.namelist.parser.Namelist; import toberumono.namelist.parser.NamelistSection; import toberumono.wrf.WRFRunnerComponentFactory; import toberumono.wrf.scope.AbstractScope; import toberumono.wrf.scope.Scope; import toberumono.wrf.timing.clear.Clear; import toberumono.wrf.timing.duration.Duration; import toberumono.wrf.timing.duration.NamelistDuration; import toberumono.wrf.timing.offset.Offset; import toberumono.wrf.timing.round.Round; import static toberumono.wrf.SimulationConstants.*;
package toberumono.wrf.timing; /** * Implementation of {@link Timing} that uses static data from a {@link Namelist} file instead of computing the timing data at runtime. * * @author Toberumono */ public class NamelistTiming extends AbstractScope<Scope> implements Timing { private static final List<String> TIMING_FIELD_SINGULAR_NAMES = TIMING_FIELD_NAMES.stream().map(s -> s.substring(0, s.length() - 1)).collect(Collectors.toList()); private final Calendar base; private final Calendar start, end;
private final Offset offset;
6
syvaidya/openstego
src/test/java/com/openstego/desktop/plugin/randlsb/RandomLSBOutputStreamTest.java
[ "public class OpenStegoException extends Exception {\n private static final long serialVersionUID = 668241029491685413L;\n\n /**\n * Error Code - Unhandled exception\n */\n static final int UNHANDLED_EXCEPTION = 0;\n\n /**\n * Map to store error code to message key mapping\n */\n private static final Map<String, String> errMsgKeyMap = new HashMap<>();\n\n /**\n * Error code for the exception\n */\n private final int errorCode;\n\n /**\n * Namespace for the exception\n */\n private final String namespace;\n\n /**\n * Constructor using default namespace for unhandled exceptions\n *\n * @param cause Original exception which caused this exception to be raised\n */\n public OpenStegoException(Throwable cause) {\n this(cause, OpenStego.NAMESPACE, UNHANDLED_EXCEPTION, (Object[]) null);\n }\n\n /**\n * Default constructor\n *\n * @param cause Original exception which caused this exception to be raised\n * @param namespace Namespace of the error\n * @param errorCode Error code for the exception\n */\n public OpenStegoException(Throwable cause, String namespace, int errorCode) {\n this(cause, namespace, errorCode, (Object[]) null);\n }\n\n /**\n * Constructor with a single parameter for the message\n *\n * @param cause Original exception which caused this exception to be raised\n * @param namespace Namespace of the error\n * @param errorCode Error code for the exception\n * @param param Parameter for exception message\n */\n public OpenStegoException(Throwable cause, String namespace, int errorCode, String param) {\n this(cause, namespace, errorCode, new Object[]{param});\n }\n\n /**\n * Constructor which takes object array for parameters for the message\n *\n * @param cause Original exception which caused this exception to be raised\n * @param namespace Namespace of the error\n * @param errorCode Error code for the exception\n * @param params Parameters for exception message\n */\n public OpenStegoException(Throwable cause, String namespace, int errorCode, Object... params) {\n super((OpenStego.NAMESPACE.equals(namespace) && errorCode == UNHANDLED_EXCEPTION) ? cause.toString()\n : LabelUtil.getInstance(namespace).getString(errMsgKeyMap.get(namespace + errorCode), params), cause);\n\n this.namespace = namespace;\n this.errorCode = errorCode;\n }\n\n /**\n * Get method for errorCode\n *\n * @return errorCode\n */\n public int getErrorCode() {\n return this.errorCode;\n }\n\n /**\n * Get method for namespace\n *\n * @return namespace\n */\n public String getNamespace() {\n return this.namespace;\n }\n\n /**\n * Method to add new error codes to the namespace\n *\n * @param namespace Namespace for the error\n * @param errorCode Error code of the error\n * @param labelKey Key of the label for the error\n */\n public static void addErrorCode(String namespace, int errorCode, String labelKey) {\n errMsgKeyMap.put(namespace + errorCode, labelKey);\n }\n}", "public class LSBConfig extends OpenStegoConfig {\n /**\n * Key string for configuration item - maxBitsUsedPerChannel.\n * <p>\n * Maximum bits to use per color channel. Allowing for higher number here might degrade the quality of the image in\n * case the data size is big.\n */\n public static final String MAX_BITS_USED_PER_CHANNEL = \"maxBitsUsedPerChannel\";\n\n /**\n * Maximum bits to use per color channel. Allowing for higher number here might degrade the quality\n * of the image in case the data size is big.\n */\n private int maxBitsUsedPerChannel = 3;\n\n /**\n * Converts command line options to Map form\n *\n * @param options Command-line options\n * @return Options in Map form\n * @throws OpenStegoException Processing issues\n */\n @Override\n protected Map<String, Object> convertCmdLineOptionsToMap(CmdLineOptions options) throws OpenStegoException {\n Map<String, Object> map = super.convertCmdLineOptionsToMap(options);\n\n if (options.getOption(\"-b\") != null) { // maxBitsUsedPerChannel\n map.put(MAX_BITS_USED_PER_CHANNEL,\n options.getIntegerValue(\"-b\", LSBPlugin.NAMESPACE, LSBErrors.MAX_BITS_NOT_NUMBER));\n }\n\n return map;\n }\n\n /**\n * Processes a configuration item.\n *\n * @param key Configuration item key\n * @param value Configuration item value\n */\n @Override\n protected void processConfigItem(String key, Object value) throws OpenStegoException {\n super.processConfigItem(key, value);\n if (key.equals(MAX_BITS_USED_PER_CHANNEL)) {\n assert value instanceof Integer;\n this.maxBitsUsedPerChannel = (int) value;\n if (this.maxBitsUsedPerChannel < 1 || this.maxBitsUsedPerChannel > 8) {\n throw new OpenStegoException(null, LSBPlugin.NAMESPACE, LSBErrors.MAX_BITS_NOT_IN_RANGE, value);\n }\n }\n }\n\n /**\n * Get method for configuration item - maxBitsUsedPerChannel\n *\n * @return maxBitsUsedPerChannel\n */\n public int getMaxBitsUsedPerChannel() {\n return this.maxBitsUsedPerChannel;\n }\n\n /**\n * Set method for configuration item - maxBitsUsedPerChannel\n *\n * @param maxBitsUsedPerChannel Value to be set\n */\n public void setMaxBitsUsedPerChannel(int maxBitsUsedPerChannel) {\n this.maxBitsUsedPerChannel = maxBitsUsedPerChannel;\n }\n}", "public class LSBDataHeader {\n /**\n * Magic string at the start of the header to identify OpenStego embedded data\n */\n public static final byte[] DATA_STAMP = \"OPENSTEGO\".getBytes(StandardCharsets.UTF_8);\n\n /**\n * Header version to distinguish between various versions of data embedding. This should be changed to next\n * version, in case the logic of embedding data is changed.\n */\n public static final byte[] HEADER_VERSION = new byte[]{(byte) 2};\n\n /**\n * Length of the fixed portion of the header\n */\n private static final int FIXED_HEADER_LENGTH = 8;\n\n /**\n * Length of the encryption algorithm string\n */\n private static final int CRYPT_ALGO_LENGTH = 8;\n\n /**\n * Length of the data embedded in the image (excluding the header data)\n */\n private final int dataLength;\n\n /**\n * Number of bits used per color channel for embedding the data\n */\n private int channelBitsUsed;\n\n /**\n * Name of the file being embedded in the image (as byte array)\n */\n private final byte[] fileName;\n\n /**\n * OpenStegoConfig instance to hold the configuration data\n */\n private final OpenStegoConfig config;\n\n /**\n * This constructor should normally be used when writing the data.\n *\n * @param dataLength Length of the data embedded in the image (excluding the header data)\n * @param channelBitsUsed Number of bits used per color channel for embedding the data\n * @param fileName Name of the file of data being embedded\n * @param config OpenStegoConfig instance to hold the configuration data\n */\n public LSBDataHeader(int dataLength, int channelBitsUsed, String fileName, OpenStegoConfig config) {\n this.dataLength = dataLength;\n this.channelBitsUsed = channelBitsUsed;\n this.config = config;\n\n if (fileName == null) {\n this.fileName = new byte[0];\n } else {\n this.fileName = fileName.getBytes(StandardCharsets.UTF_8);\n }\n }\n\n /**\n * This constructor should be used when reading embedded data from an InputStream.\n *\n * @param dataInStream Data input stream containing the embedded data\n * @param config OpenStegoConfig instance to hold the configuration data\n * @throws OpenStegoException Processing issues\n */\n public LSBDataHeader(InputStream dataInStream, OpenStegoConfig config) throws OpenStegoException {\n int stampLen;\n int versionLen;\n int fileNameLen;\n int channelBits;\n int n;\n byte[] header;\n byte[] cryptAlgo;\n byte[] stamp;\n byte[] version;\n\n stampLen = DATA_STAMP.length;\n versionLen = HEADER_VERSION.length;\n header = new byte[FIXED_HEADER_LENGTH];\n cryptAlgo = new byte[CRYPT_ALGO_LENGTH];\n stamp = new byte[stampLen];\n version = new byte[versionLen];\n\n try {\n n = dataInStream.read(stamp, 0, stampLen);\n if (n == -1 || !(new String(stamp)).equals(new String(DATA_STAMP))) {\n throw new OpenStegoException(null, LSBPlugin.NAMESPACE, LSBErrors.INVALID_STEGO_HEADER);\n }\n\n n = dataInStream.read(version, 0, versionLen);\n if (n == -1 || !(new String(version)).equals(new String(HEADER_VERSION))) {\n throw new OpenStegoException(null, LSBPlugin.NAMESPACE, LSBErrors.INVALID_HEADER_VERSION);\n }\n\n n = dataInStream.read(header, 0, FIXED_HEADER_LENGTH);\n if (n < FIXED_HEADER_LENGTH) {\n throw new OpenStegoException(null, LSBPlugin.NAMESPACE, LSBErrors.INVALID_STEGO_HEADER);\n }\n this.dataLength = (CommonUtil.byteToInt(header[0]) + (CommonUtil.byteToInt(header[1]) << 8) + (CommonUtil.byteToInt(header[2]) << 16)\n + (CommonUtil.byteToInt(header[3]) << 24));\n channelBits = header[4];\n fileNameLen = header[5];\n config.setUseCompression(header[6] == 1);\n config.setUseEncryption(header[7] == 1);\n\n n = dataInStream.read(cryptAlgo, 0, CRYPT_ALGO_LENGTH);\n if (n < CRYPT_ALGO_LENGTH) {\n throw new OpenStegoException(null, LSBPlugin.NAMESPACE, LSBErrors.INVALID_STEGO_HEADER);\n }\n config.setEncryptionAlgorithm(new String(cryptAlgo).trim());\n\n if (fileNameLen == 0) {\n this.fileName = new byte[0];\n } else {\n this.fileName = new byte[fileNameLen];\n n = dataInStream.read(this.fileName, 0, fileNameLen);\n if (n < fileNameLen) {\n throw new OpenStegoException(null, LSBPlugin.NAMESPACE, LSBErrors.INVALID_STEGO_HEADER);\n }\n }\n } catch (OpenStegoException osEx) {\n throw osEx;\n } catch (Exception ex) {\n throw new OpenStegoException(ex);\n }\n\n this.channelBitsUsed = channelBits;\n this.config = config;\n }\n\n /**\n * This method generates the header in the form of byte array based on the parameters provided in the constructor.\n *\n * @return Header data\n */\n public byte[] getHeaderData() {\n byte[] out;\n int stampLen;\n int versionLen;\n int currIndex = 0;\n\n stampLen = DATA_STAMP.length;\n versionLen = HEADER_VERSION.length;\n out = new byte[stampLen + versionLen + FIXED_HEADER_LENGTH + CRYPT_ALGO_LENGTH + this.fileName.length];\n\n System.arraycopy(DATA_STAMP, 0, out, currIndex, stampLen);\n currIndex += stampLen;\n\n System.arraycopy(HEADER_VERSION, 0, out, currIndex, versionLen);\n currIndex += versionLen;\n\n out[currIndex++] = (byte) ((this.dataLength & 0x000000FF));\n out[currIndex++] = (byte) ((this.dataLength & 0x0000FF00) >> 8);\n out[currIndex++] = (byte) ((this.dataLength & 0x00FF0000) >> 16);\n out[currIndex++] = (byte) ((this.dataLength & 0xFF000000) >> 24);\n out[currIndex++] = (byte) this.channelBitsUsed;\n out[currIndex++] = (byte) this.fileName.length;\n out[currIndex++] = (byte) (this.config.isUseCompression() ? 1 : 0);\n out[currIndex++] = (byte) (this.config.isUseEncryption() ? 1 : 0);\n\n if (this.config.getEncryptionAlgorithm() != null) {\n byte[] encAlgo = this.config.getEncryptionAlgorithm().getBytes(StandardCharsets.UTF_8);\n System.arraycopy(encAlgo, 0, out, currIndex, encAlgo.length);\n }\n currIndex += CRYPT_ALGO_LENGTH;\n\n if (this.fileName.length > 0) {\n System.arraycopy(this.fileName, 0, out, currIndex, this.fileName.length);\n //currIndex += this.fileName.length;\n }\n\n return out;\n }\n\n /**\n * Get Method for channelBitsUsed\n *\n * @return channelBitsUsed\n */\n public int getChannelBitsUsed() {\n return this.channelBitsUsed;\n }\n\n /**\n * Set Method for channelBitsUsed\n *\n * @param channelBitsUsed Value to be set\n */\n public void setChannelBitsUsed(int channelBitsUsed) {\n this.channelBitsUsed = channelBitsUsed;\n }\n\n /**\n * Get Method for dataLength\n *\n * @return dataLength\n */\n public int getDataLength() {\n return this.dataLength;\n }\n\n /**\n * Get Method for fileName\n *\n * @return fileName\n */\n public String getFileName() {\n String name;\n\n name = new String(this.fileName, StandardCharsets.UTF_8);\n return name;\n }\n\n /**\n * Method to get size of the current header\n *\n * @return Header size\n */\n public int getHeaderSize() {\n return DATA_STAMP.length + HEADER_VERSION.length + FIXED_HEADER_LENGTH + CRYPT_ALGO_LENGTH + this.fileName.length;\n }\n\n /**\n * Method to get the maximum possible size of the header\n *\n * @return Maximum possible header size\n */\n public static int getMaxHeaderSize() {\n // Max file name length assumed to be 256\n return DATA_STAMP.length + HEADER_VERSION.length + FIXED_HEADER_LENGTH + CRYPT_ALGO_LENGTH + 256;\n }\n}", "public class LSBErrors {\n /**\n * Error Code - Error while reading image data\n */\n public static final int ERR_IMAGE_DATA_READ = 1;\n\n /**\n * Error Code - Null value provided for image\n */\n public static final int NULL_IMAGE_ARGUMENT = 2;\n\n /**\n * Error Code - Image size insufficient for data\n */\n public static final int IMAGE_SIZE_INSUFFICIENT = 3;\n\n /**\n * Error Code - maxBitsUsedPerChannel is not a number\n */\n public static final int MAX_BITS_NOT_NUMBER = 4;\n\n /**\n * Error Code - maxBitsUsedPerChannel is not in valid range\n */\n public static final int MAX_BITS_NOT_IN_RANGE = 5;\n\n /**\n * Error Code - Invalid stego header data\n */\n public static final int INVALID_STEGO_HEADER = 6;\n\n /**\n * Error Code - Invalid image header version\n */\n public static final int INVALID_HEADER_VERSION = 7;\n\n /**\n * Initialize the error code - message key map\n */\n public static void init() {\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, ERR_IMAGE_DATA_READ, \"err.image.read\");\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, NULL_IMAGE_ARGUMENT, \"err.image.arg.nullValue\");\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, IMAGE_SIZE_INSUFFICIENT, \"err.image.insufficientSize\");\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, MAX_BITS_NOT_NUMBER, \"err.config.maxBitsUsedPerChannel.notNumber\");\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, MAX_BITS_NOT_IN_RANGE, \"err.config.maxBitsUsedPerChannel.notInRange\");\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, INVALID_STEGO_HEADER, \"err.invalidHeaderStamp\");\n OpenStegoException.addErrorCode(LSBPlugin.NAMESPACE, INVALID_HEADER_VERSION, \"err.invalidHeaderVersion\");\n }\n}", "public class LSBPlugin extends DHImagePluginTemplate<LSBConfig> {\n /**\n * LabelUtil instance to retrieve labels\n */\n private static final LabelUtil labelUtil = LabelUtil.getInstance(LSBPlugin.NAMESPACE);\n\n /**\n * Constant for Namespace to use for this plugin\n */\n public final static String NAMESPACE = \"LSB\";\n\n /**\n * Default constructor\n */\n public LSBPlugin() {\n LabelUtil.addNamespace(NAMESPACE, \"i18n.LSBPluginLabels\");\n LSBErrors.init(); // Initialize error codes\n }\n\n /**\n * Gives the name of the plugin\n *\n * @return Name of the plugin\n */\n @Override\n public String getName() {\n return \"LSB\";\n }\n\n /**\n * Gives a short description of the plugin\n *\n * @return Short description of the plugin\n */\n @Override\n public String getDescription() {\n return labelUtil.getString(\"plugin.description\");\n }\n\n /**\n * Method to embed the message into the cover data\n *\n * @param msg Message to be embedded\n * @param msgFileName Name of the message file. If this value is provided, then the filename should be\n * embedded in the cover data\n * @param cover Cover data into which message needs to be embedded\n * @param coverFileName Name of the cover file\n * @param stegoFileName Name of the output stego file\n * @return Stego data containing the message\n * @throws OpenStegoException Processing issues\n */\n @Override\n public byte[] embedData(byte[] msg, String msgFileName, byte[] cover, String coverFileName, String stegoFileName) throws OpenStegoException {\n int numOfPixels;\n ImageHolder image;\n\n try {\n // Generate random image, if input image is not provided\n if (cover == null) {\n numOfPixels = (int) (LSBDataHeader.getMaxHeaderSize() * 8 / 3.0);\n numOfPixels += (int) (msg.length * 8 / (3.0 * this.config.getMaxBitsUsedPerChannel()));\n image = ImageUtil.generateRandomImage(numOfPixels);\n } else {\n image = ImageUtil.byteArrayToImage(cover, coverFileName);\n }\n try (LSBOutputStream lsbOS = new LSBOutputStream(image, msg.length, msgFileName, this.config)) {\n lsbOS.write(msg);\n lsbOS.flush();\n image = lsbOS.getImage();\n }\n\n return ImageUtil.imageToByteArray(image, stegoFileName, this);\n } catch (IOException ioEx) {\n throw new OpenStegoException(ioEx);\n }\n }\n\n /**\n * Method to extract the message file name from the stego data\n *\n * @param stegoData Stego data containing the message\n * @param stegoFileName Name of the stego file\n * @return Message file name\n * @throws OpenStegoException Processing issues\n */\n @Override\n public String extractMsgFileName(byte[] stegoData, String stegoFileName) throws OpenStegoException {\n ImageHolder imgHolder = ImageUtil.byteArrayToImage(stegoData, stegoFileName);\n try (LSBInputStream lsbIS = new LSBInputStream(imgHolder, this.config)) {\n return lsbIS.getDataHeader().getFileName();\n } catch (IOException ioEx) {\n throw new OpenStegoException(ioEx);\n }\n }\n\n /**\n * Method to extract the message from the stego data\n *\n * @param stegoData Stego data containing the message\n * @param stegoFileName Name of the stego file\n * @param origSigData Optional signature data file for watermark\n * @return Extracted message\n * @throws OpenStegoException Processing issues\n */\n @Override\n public byte[] extractData(byte[] stegoData, String stegoFileName, byte[] origSigData) throws OpenStegoException {\n int bytesRead;\n byte[] data;\n LSBDataHeader header;\n ImageHolder imgHolder = ImageUtil.byteArrayToImage(stegoData, stegoFileName);\n\n try (LSBInputStream lsbIS = new LSBInputStream(imgHolder, this.config)) {\n header = lsbIS.getDataHeader();\n data = new byte[header.getDataLength()];\n\n bytesRead = lsbIS.read(data, 0, data.length);\n if (bytesRead != data.length) {\n throw new OpenStegoException(null, NAMESPACE, LSBErrors.ERR_IMAGE_DATA_READ);\n }\n\n return data;\n } catch (IOException ex) {\n throw new OpenStegoException(ex);\n }\n }\n\n /**\n * Method to get the list of supported file extensions for writing\n *\n * @return List of supported file extensions for writing\n * @throws OpenStegoException Processing issues\n */\n @Override\n public List<String> getWritableFileExtensions() throws OpenStegoException {\n if (writeFormats != null) {\n return writeFormats;\n }\n\n super.getWritableFileExtensions();\n String format;\n String[] compTypes;\n Iterator<ImageWriter> iter;\n ImageWriteParam writeParam;\n\n for (int i = writeFormats.size() - 1; i >= 0; i--) {\n format = writeFormats.get(i);\n iter = ImageIO.getImageWritersBySuffix(format);\n while (iter.hasNext()) {\n writeParam = (iter.next()).getDefaultWriteParam();\n try {\n writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n compTypes = writeParam.getCompressionTypes();\n if (compTypes.length > 0) {\n writeParam.setCompressionType(compTypes[0]);\n }\n } catch (UnsupportedOperationException uoEx) {\n // Compression not supported\n break;\n }\n\n // Only lossless image compression is supported\n if (writeParam.isCompressionLossless()) {\n break;\n }\n writeFormats.remove(i);\n }\n }\n\n // Expicilty removing GIF and WBMP formats, as they use unsupported color models\n writeFormats.remove(\"gif\");\n writeFormats.remove(\"wbmp\");\n // Expicilty removing TIF(F) formats, as they are not working correctly - TODO check why\n writeFormats.remove(\"tif\");\n writeFormats.remove(\"tiff\");\n\n return writeFormats;\n }\n\n /**\n * Method to populate the standard command-line options used by this plugin\n *\n * @param options Existing command-line options. Plugin-specific options will get added to this list\n */\n @Override\n public void populateStdCmdLineOptions(CmdLineOptions options) {\n options.add(\"-b\", \"--maxBitsUsedPerChannel\", CmdLineOption.TYPE_OPTION, true);\n }\n\n /**\n * Method to create default configuration data (specific to this plugin)\n *\n * @return Configuration data\n */\n @Override\n protected LSBConfig createConfig() {\n return new LSBConfig();\n }\n\n /**\n * Method to create configuration data (specific to this plugin) based on the command-line options\n *\n * @param options Command-line options\n * @return Configuration data\n * @throws OpenStegoException Processing issues\n */\n @Override\n protected LSBConfig createConfig(CmdLineOptions options) throws OpenStegoException {\n LSBConfig config = new LSBConfig();\n config.initialize(options);\n return config;\n }\n\n /**\n * Method to get the usage details of the plugin\n *\n * @return Usage details of the plugin\n */\n @Override\n public String getUsage() {\n LSBConfig defaultConfig = new LSBConfig();\n return labelUtil.getString(\"plugin.usage\", defaultConfig.getMaxBitsUsedPerChannel());\n }\n}", "public class ImageHolder {\n private BufferedImage image;\n private IIOMetadata metadata;\n\n /**\n * Default constructor\n *\n * @param image Image\n * @param metadata Metadata\n */\n public ImageHolder(BufferedImage image, IIOMetadata metadata) {\n this.image = image;\n this.metadata = metadata;\n }\n\n /**\n * Getter method for image\n *\n * @return image\n */\n public BufferedImage getImage() {\n return this.image;\n }\n\n /**\n * Setter method for image\n *\n * @param image Value for image to be set\n */\n public void setImage(BufferedImage image) {\n this.image = image;\n }\n\n /**\n * Getter method for metadata\n *\n * @return metadata\n */\n public IIOMetadata getMetadata() {\n return this.metadata;\n }\n\n /**\n * Setter method for metadata\n *\n * @param metadata Value for metadata to be set\n */\n @SuppressWarnings(\"unused\")\n public void setMetadata(IIOMetadata metadata) {\n this.metadata = metadata;\n }\n}" ]
import com.openstego.desktop.OpenStegoException; import com.openstego.desktop.plugin.lsb.LSBConfig; import com.openstego.desktop.plugin.lsb.LSBDataHeader; import com.openstego.desktop.plugin.lsb.LSBErrors; import com.openstego.desktop.plugin.lsb.LSBPlugin; import com.openstego.desktop.util.ImageHolder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.awt.image.BufferedImage; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*;
/* * Steganography utility to hide messages into cover files * Author: Samir Vaidya (mailto:syvaidya@gmail.com) * Copyright (c) Samir Vaidya */ package com.openstego.desktop.plugin.randlsb; /** * Unit test class for {@link com.openstego.desktop.plugin.randlsb.RandomLSBOutputStream} */ public class RandomLSBOutputStreamTest { @BeforeEach public void setup() { RandomLSBPlugin plugin = new RandomLSBPlugin(); assertNotNull(plugin); } @Test public void testBestCase() throws Exception { BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); ImageHolder holder = new ImageHolder(image, null);
LSBConfig config = new LSBConfig();
1
RoboTricker/Transport-Pipes
src/main/java/de/robotricker/transportpipes/inventory/CraftingPipeSettingsInventory.java
[ "public class TransportPipes extends JavaPlugin {\n\n private Injector injector;\n\n private SentryService sentry;\n private ThreadService thread;\n private DiskService diskService;\n\n @Override\n public void onEnable() {\n\n if (Bukkit.getVersion().contains(\"1.13\")) {\n LegacyUtils.setInstance(new LegacyUtils_1_13());\n } else {\n System.err.println(\"------------------------------------------\");\n System.err.println(\"TransportPipes currently only works with Minecraft 1.13.1 and 1.13.2\");\n System.err.println(\"------------------------------------------\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n try {\n Class.forName(\"org.bukkit.inventory.RecipeChoice\");\n } catch (ClassNotFoundException e) {\n System.err.println(\"------------------------------------------\");\n System.err.println(\"TransportPipes currently only works with Minecraft 1.13.1 and 1.13.2\");\n System.err.println(\"------------------------------------------\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n if (Files.isRegularFile(Paths.get(getDataFolder().getPath(), \"recipes.yml\"))) {\n System.err.println(\"------------------------------------------\");\n System.err.println(\"Please delete the old plugins/TransportPipes directory so TransportPipes can recreate it with a bunch of new config values\");\n System.err.println(\"------------------------------------------\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n //Initialize dependency injector\n injector = new InjectorBuilder().addDefaultHandlers(\"de.robotricker.transportpipes\").create();\n injector.register(Logger.class, getLogger());\n injector.register(Plugin.class, this);\n injector.register(JavaPlugin.class, this);\n injector.register(TransportPipes.class, this);\n\n //Initialize logger\n LoggerService logger = injector.getSingleton(LoggerService.class);\n\n //Initialize sentry\n sentry = injector.getSingleton(SentryService.class);\n if (!sentry.init(\"https://84937d8c6bc2435d860021667341c87c@sentry.io/1281889?stacktrace.app.packages=de.robotricker&release=\" + getDescription().getVersion())) {\n logger.warning(\"Unable to initialize sentry!\");\n }\n sentry.addTag(\"thread\", Thread.currentThread().getName());\n sentry.injectThread(Thread.currentThread());\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"enabling plugin\");\n\n //Initialize configs\n injector.getSingleton(GeneralConf.class);\n injector.register(LangConf.class, new LangConf(this, injector.getSingleton(GeneralConf.class).getLanguage()));\n\n //Initialize API\n injector.getSingleton(TransportPipesAPI.class);\n\n //Initialize thread\n thread = injector.getSingleton(ThreadService.class);\n thread.start();\n\n //Register pipe\n BaseDuctType<Pipe> baseDuctType = injector.getSingleton(DuctRegister.class).registerBaseDuctType(\"Pipe\", PipeManager.class, PipeFactory.class, PipeItemManager.class);\n baseDuctType.setModelledRenderSystem(injector.newInstance(ModelledPipeRenderSystem.class));\n baseDuctType.setVanillaRenderSystem(injector.newInstance(VanillaPipeRenderSystem.class));\n\n //Register listeners\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(TPContainerListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(PlayerListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(DuctListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(WorldListener.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(PlayerSettingsInventory.class), this);\n Bukkit.getPluginManager().registerEvents(injector.getSingleton(ResourcepackService.class), this);\n\n //Register commands\n PaperCommandManager commandManager = new PaperCommandManager(this);\n commandManager.enableUnstableAPI(\"help\");\n commandManager.registerCommand(injector.getSingleton(TPCommand.class));\n commandManager.getCommandCompletions().registerCompletion(\"baseDuctType\", c -> injector.getSingleton(DuctRegister.class).baseDuctTypes().stream().map(BaseDuctType::getName).collect(Collectors.toList()));\n\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"enabled plugin\");\n\n diskService = injector.getSingleton(DiskService.class);\n\n TPContainerListener tpContainerListener = injector.getSingleton(TPContainerListener.class);\n runTaskSync(() -> {\n for (World world : Bukkit.getWorlds()) {\n for (Chunk loadedChunk : world.getLoadedChunks()) {\n tpContainerListener.handleChunkLoadSync(loadedChunk, true);\n }\n diskService.loadDuctsSync(world);\n }\n });\n\n if (Bukkit.getPluginManager().isPluginEnabled(\"LWC\")) {\n try {\n com.griefcraft.scripting.Module module = injector.getSingleton(LWCUtils.class);\n com.griefcraft.lwc.LWC.getInstance().getModuleLoader().registerModule(this, module);\n } catch (Exception e) {\n e.printStackTrace();\n sentry.record(e);\n }\n }\n\n }\n\n @Override\n public void onDisable() {\n if (sentry != null && thread != null) {\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"disabling plugin\");\n // Stop tpThread gracefully\n try {\n thread.stopRunning();\n thread.join();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n for (World world : Bukkit.getWorlds()) {\n saveWorld(world);\n }\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"disabled plugin\");\n }\n }\n\n public void saveWorld(World world) {\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"saving world \" + world.getName());\n diskService.saveDuctsSync(world);\n sentry.breadcrumb(Breadcrumb.Level.INFO, \"MAIN\", \"saved world \" + world.getName());\n }\n\n public void runTaskSync(Runnable task) {\n if (isEnabled()) {\n Bukkit.getScheduler().runTask(this, task);\n }\n }\n\n public void runTaskSyncLater(Runnable task, long delay) {\n if (isEnabled()) {\n Bukkit.getScheduler().runTaskLater(this, task, delay);\n }\n }\n\n public void runTaskAsync(Runnable runnable, long delay) {\n thread.getTasks().put(runnable, delay);\n }\n\n public Injector getInjector() {\n return injector;\n }\n\n public void changeRenderSystem(Player p, String newRenderSystemName) {\n PlayerSettingsConf playerSettingsConf = injector.getSingleton(PlayerSettingsService.class).getOrCreateSettingsConf(p);\n DuctRegister ductRegister = injector.getSingleton(DuctRegister.class);\n GlobalDuctManager globalDuctManager = injector.getSingleton(GlobalDuctManager.class);\n ProtocolService protocolService = injector.getSingleton(ProtocolService.class);\n\n // change render system\n String oldRenderSystemName = playerSettingsConf.getRenderSystemName();\n if (oldRenderSystemName.equalsIgnoreCase(newRenderSystemName)) {\n return;\n }\n playerSettingsConf.setRenderSystemName(newRenderSystemName);\n\n for (BaseDuctType baseDuctType : ductRegister.baseDuctTypes()) {\n RenderSystem oldRenderSystem = RenderSystem.getRenderSystem(oldRenderSystemName, baseDuctType);\n\n // switch render system\n synchronized (globalDuctManager.getPlayerDucts(p)) {\n Iterator<Duct> ductIt = globalDuctManager.getPlayerDucts(p).iterator();\n while (ductIt.hasNext()) {\n Duct nextDuct = ductIt.next();\n protocolService.removeASD(p, oldRenderSystem.getASDForDuct(nextDuct));\n ductIt.remove();\n }\n }\n\n }\n }\n\n public long convertVersionToLong(String version) {\n long versionLong = 0;\n try {\n if (version.contains(\"-\")) {\n for (String subVersion : version.split(\"-\")) {\n if (subVersion.startsWith(\"b\")) {\n int buildNumber = 0;\n String buildNumberString = subVersion.substring(1);\n if (!buildNumberString.equalsIgnoreCase(\"CUSTOM\")) {\n buildNumber = Integer.parseInt(buildNumberString);\n }\n versionLong |= buildNumber;\n } else if (!subVersion.equalsIgnoreCase(\"SNAPSHOT\")) {\n versionLong |= (long) convertMainVersionStringToInt(subVersion) << 32;\n }\n }\n } else {\n versionLong = (long) convertMainVersionStringToInt(version) << 32;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return versionLong;\n }\n\n private int convertMainVersionStringToInt(String mainVersion) {\n int versionInt = 0;\n if (mainVersion.contains(\".\")) {\n // shift for every version number 1 byte to the left\n int leftShift = (mainVersion.split(\"\\\\.\").length - 1) * 8;\n for (String subVersion : mainVersion.split(\"\\\\.\")) {\n byte v = Byte.parseByte(subVersion);\n versionInt |= ((int) v << leftShift);\n leftShift -= 8;\n }\n } else {\n versionInt = Byte.parseByte(mainVersion);\n }\n return versionInt;\n }\n\n}", "public class LangConf extends Conf {\n\n private static LangConf langConf;\n\n public LangConf(Plugin configPlugin, String language) {\n super(configPlugin, \"lang_\" + language.toLowerCase(Locale.ENGLISH) + \".yml\", \"lang.yml\", true);\n langConf = this;\n }\n\n public enum Key {\n\n PIPES_WHITE(\"pipes.white\"),\n PIPES_YELLOW(\"pipes.yellow\"),\n PIPES_GREEN(\"pipes.green\"),\n PIPES_BLUE(\"pipes.blue\"),\n PIPES_RED(\"pipes.red\"),\n PIPES_BLACK(\"pipes.black\"),\n PIPES_ICE(\"pipes.ice\"),\n PIPES_GOLDEN(\"pipes.golden\"),\n PIPES_IRON(\"pipes.iron\"),\n PIPES_VOID(\"pipes.void\"),\n PIPES_EXTRACTION(\"pipes.extraction\"),\n PIPES_CRAFTING(\"pipes.crafting\"),\n WRENCH(\"wrench\"),\n COLORS_WHITE(\"colors.white\"),\n COLORS_YELLOW(\"colors.yellow\"),\n COLORS_GREEN(\"colors.green\"),\n COLORS_BLUE(\"colors.blue\"),\n COLORS_RED(\"colors.red\"),\n COLORS_BLACK(\"colors.black\"),\n DIRECTIONS_EAST(\"directions.east\"),\n DIRECTIONS_WEST(\"directions.west\"),\n DIRECTIONS_SOUTH(\"directions.south\"),\n DIRECTIONS_NORTH(\"directions.north\"),\n DIRECTIONS_UP(\"directions.up\"),\n DIRECTIONS_DOWN(\"directions.down\"),\n DIRECTIONS_NONE(\"directions.none\"),\n RESOURCEPACK_FAIL(\"resourcepack_fail\"),\n RENDERSYSTEM_BLOCK(\"rendersystem_block\"),\n PROTECTED_BLOCK(\"protected_block\"),\n RENDERSYSTEM_NAME_VANILLA(\"rendersystem_name.vanilla\"),\n RENDERSYSTEM_NAME_MODELLED(\"rendersystem_name.modelled\"),\n PLAYER_SETTINGS_TITLE(\"player_settings.title\"),\n PLAYER_SETTINGS_RENDERDISTANCE(\"player_settings.renderdistance\"),\n PLAYER_SETTINGS_DECREASE_RENDERDISTANCE(\"player_settings.decrease_renderdistance\"),\n PLAYER_SETTINGS_INCREASE_RENDERDISTANCE(\"player_settings.increase_renderdistance\"),\n PLAYER_SETTINGS_RENDERSYSTEM(\"player_settings.rendersystem\"),\n PLAYER_SETTINGS_ITEM_VISIBILITY_SHOW(\"player_settings.item_visibility_show\"),\n PLAYER_SETTINGS_ITEM_VISIBILITY_HIDE(\"player_settings.item_visibility_hide\"),\n DUCT_INVENTORY_TITLE(\"duct_inventory.title\"),\n DUCT_INVENTORY_LEFTARROW(\"duct_inventory.leftarrow\"),\n DUCT_INVENTORY_RIGHTARROW(\"duct_inventory.rightarrow\"),\n DUCT_INVENTORY_FILTER_MODE_AND_STRICTNESS(\"duct_inventory.filter_mode_and_strictness\"),\n DUCT_INVENTORY_GOLDENPIPE_FILTERTITLE(\"duct_inventory.goldenpipe.filtertitle\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_EXTRACTDIRECTION(\"duct_inventory.extractionpipe.extractdirection\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_EXTRACTCONDITION(\"duct_inventory.extractionpipe.extractcondition\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_EXTRACTAMOUNT(\"duct_inventory.extractionpipe.extractamount\"),\n DUCT_INVENTORY_EXTRACTIONPIPE_FILTERTITLE(\"duct_inventory.extractionpipe.filtertitle\"),\n DUCT_INVENTORY_CRAFTINGPIPE_OUTPUTDIRECTION(\"duct_inventory.craftingpipe.outputdirection\"),\n DUCT_INVENTORY_CRAFTINGPIPE_RETRIEVECACHEDITEMS(\"duct_inventory.craftingpipe.retrievecacheditems\"),\n DUCT_INVENTORY_CREATIVE_INVENTORY_TITLE(\"duct_inventory.creative_inventory_title\"),\n FILTER_STRICTNESS_MATERIAL(\"filter_strictness.material\"),\n FILTER_STRICTNESS_MATERIAL_METADATA(\"filter_strictness.material_metadata\"),\n FILTER_MODE_NORMAL(\"filter_mode.normal\"),\n FILTER_MODE_INVERTED(\"filter_mode.inverted\"),\n FILTER_MODE_BLOCKALL(\"filter_mode.blockall\"),\n EXTRACT_CONDITION_NEEDS_REDSTONE(\"extract_condition.needs_redstone\"),\n EXTRACT_CONDITION_ALWAYS_EXTRACT(\"extract_condition.always_extract\"),\n EXTRACT_CONDITION_NEVER_EXTRACT(\"extract_condition.never_extract\"),\n EXTRACT_AMOUNT_EXTRACT_1(\"extract_amount.extract_1\"),\n EXTRACT_AMOUNT_EXTRACT_16(\"extract_amount.extract_16\"),\n SHOW_HIDDEN_DUCTS(\"show_hidden_ducts\");\n\n private String key;\n\n Key(String key) {\n this.key = key;\n }\n\n public String get(Object... replacements) {\n String value = (String) langConf.read(key);\n if (value == null) {\n value = \"&cMissing Language Entry: &4\" + key + \"&r\";\n }\n for (int i = 0; i < replacements.length; i++) {\n value = value.replaceAll(\"%\" + (i + 1) + \"%\", replacements[i].toString());\n }\n return ChatColor.translateAlternateColorCodes('&', value);\n }\n\n public List<String> getLines(Object... replacements) {\n return Arrays.asList(get(replacements).split(\"\\\\\\\\n\"));\n }\n\n public void sendMessage(Player p) {\n for (String line : getLines()) {\n p.sendMessage(line);\n }\n }\n\n }\n\n}", "public class CraftingPipe extends Pipe {\n\n private ItemData[] recipeItems;\n private Recipe recipe;\n private TPDirection outputDir;\n private List<ItemStack> cachedItems;\n\n public CraftingPipe(DuctType ductType, BlockLocation blockLoc, World world, Chunk chunk, DuctSettingsInventory settingsInv, GlobalDuctManager globalDuctManager, ItemDistributorService itemDistributor) {\n super(ductType, blockLoc, world, chunk, settingsInv, globalDuctManager, itemDistributor);\n recipeItems = new ItemData[9];\n outputDir = null;\n cachedItems = new ArrayList<>();\n }\n\n @Override\n public void tick(boolean bigTick, TransportPipes transportPipes, DuctManager ductManager) {\n super.tick(bigTick, transportPipes, ductManager);\n if (bigTick) {\n performCrafting((PipeManager) ductManager, transportPipes);\n }\n }\n\n @Override\n protected Map<TPDirection, Integer> calculateItemDistribution(PipeItem pipeItem, TPDirection movingDir, List<TPDirection> dirs, TransportPipes transportPipes) {\n ItemStack overflow = addCachedItem(pipeItem.getItem(), transportPipes);\n if (overflow != null) {\n transportPipes.runTaskSync(() -> getWorld().dropItem(getBlockLoc().toLocation(getWorld()), overflow));\n }\n return null;\n }\n\n public void performCrafting(PipeManager pipeManager, TransportPipes transportPipes) {\n if (outputDir != null && recipe != null) {\n ItemStack resultItem = recipe.getResult();\n\n List<RecipeChoice> ingredients = new ArrayList<>();\n if (recipe instanceof ShapelessRecipe) {\n ingredients.addAll(((ShapelessRecipe) recipe).getChoiceList());\n } else if (recipe instanceof ShapedRecipe) {\n Map<Character, Integer> charCounts = new HashMap<>();\n for (String row : ((ShapedRecipe) recipe).getShape()) {\n for (char c : row.toCharArray()) {\n charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);\n }\n }\n for (Character c : charCounts.keySet()) {\n RecipeChoice ingredientChoice = ((ShapedRecipe) recipe).getChoiceMap().get(c);\n if (ingredientChoice != null) {\n ingredients.addAll(Collections.nCopies(charCounts.get(c), ingredientChoice));\n }\n }\n }\n\n List<ItemStack> cachedItems = new ArrayList<>();\n for (ItemStack cachedItem : this.cachedItems) {\n cachedItems.add(cachedItem.clone());\n }\n\n //iterate needed ingredients\n Iterator<RecipeChoice> neededIngredientsIt = ingredients.iterator();\n while (neededIngredientsIt.hasNext()) {\n RecipeChoice neededIngredient = neededIngredientsIt.next();\n\n //iterate cached items\n for (int i = 0; i < cachedItems.size(); i++) {\n if (neededIngredient.test(cachedItems.get(i))) {\n if (cachedItems.get(i).getAmount() > 1) {\n cachedItems.get(i).setAmount(cachedItems.get(i).getAmount() - 1);\n } else {\n cachedItems.remove(i);\n }\n neededIngredientsIt.remove();\n break;\n }\n }\n\n }\n\n if (ingredients.isEmpty()) {\n // update real cachedItems list\n this.cachedItems.clear();\n this.cachedItems.addAll(cachedItems);\n\n transportPipes.runTaskSync(() -> {\n settingsInv.save(null);\n settingsInv.populate();\n });\n\n // output result item\n PipeItem pipeItem = new PipeItem(resultItem.clone(), getWorld(), getBlockLoc(), outputDir);\n pipeItem.getRelativeLocation().set(0.5d, 0.5d, 0.5d);\n pipeItem.resetOldRelativeLocation();\n pipeManager.spawnPipeItem(pipeItem);\n pipeManager.putPipeItemInPipe(pipeItem);\n\n }\n }\n }\n\n public int spaceForItem(ItemData data) {\n int space = 0;\n\n for (int i = 0; i < 9; i++) {\n if (i >= cachedItems.size()) {\n space += data.toItemStack().getMaxStackSize();\n } else {\n ItemStack item = cachedItems.get(i);\n if (item.isSimilar(data.toItemStack()) && item.getAmount() < item.getMaxStackSize()) {\n space += item.getMaxStackSize() - item.getAmount();\n }\n }\n }\n\n return space;\n }\n\n public ItemData[] getRecipeItems() {\n return recipeItems;\n }\n\n public TPDirection getOutputDir() {\n return outputDir;\n }\n\n public void setOutputDir(TPDirection outputDir) {\n this.outputDir = outputDir;\n }\n\n public Recipe getRecipe() {\n return recipe;\n }\n\n public void setRecipe(Recipe recipe) {\n this.recipe = recipe;\n }\n\n public List<ItemStack> getCachedItems() {\n return cachedItems;\n }\n\n public ItemStack addCachedItem(ItemStack item, TransportPipes transportPipes) {\n for (ItemStack cachedItem : cachedItems) {\n if (cachedItem.isSimilar(item)) {\n int cachedItemAmount = cachedItem.getAmount();\n cachedItem.setAmount(Math.min(cachedItem.getMaxStackSize(), cachedItemAmount + item.getAmount()));\n int overflow = cachedItemAmount + item.getAmount() - cachedItem.getMaxStackSize();\n if (overflow > 0) {\n item.setAmount(overflow);\n } else {\n item = null;\n break;\n }\n }\n }\n if (cachedItems.size() < 9 && item != null) {\n cachedItems.add(item);\n item = null;\n }\n\n transportPipes.runTaskSync(() -> {\n settingsInv.save(null);\n settingsInv.populate();\n });\n return item;\n }\n\n public void updateOutputDirection(boolean cycle) {\n TPDirection oldOutputDirection = getOutputDir();\n Set<TPDirection> connections = getAllConnections();\n if (connections.isEmpty()) {\n outputDir = null;\n } else if (cycle || outputDir == null || !connections.contains(outputDir)) {\n do {\n if (outputDir == null) {\n outputDir = TPDirection.NORTH;\n } else {\n outputDir = outputDir.next();\n }\n } while (!connections.contains(outputDir));\n }\n if (oldOutputDirection != outputDir) {\n settingsInv.populate();\n }\n }\n\n @Override\n public void notifyConnectionChange() {\n super.notifyConnectionChange();\n updateOutputDirection(false);\n }\n\n @Override\n public Material getBreakParticleData() {\n return Material.CRAFTING_TABLE;\n }\n\n @Override\n public void saveToNBTTag(CompoundTag compoundTag, ItemService itemService) {\n super.saveToNBTTag(compoundTag, itemService);\n\n compoundTag.putInt(\"outputDir\", outputDir != null ? outputDir.ordinal() : -1);\n\n ListTag<StringTag> recipeItemsListTag = new ListTag<>(StringTag.class);\n for (int i = 0; i < 9; i++) {\n ItemData itemData = recipeItems[i];\n if (itemData == null) {\n recipeItemsListTag.add(new StringTag(null));\n } else {\n recipeItemsListTag.addString(itemService.serializeItemStack(itemData.toItemStack()));\n }\n }\n compoundTag.put(\"recipeItems\", recipeItemsListTag);\n\n ListTag<StringTag> cachedItemsListTag = new ListTag<>(StringTag.class);\n for (int i = 0; i < cachedItems.size(); i++) {\n ItemStack itemStack = cachedItems.get(i);\n cachedItemsListTag.addString(itemService.serializeItemStack(itemStack));\n }\n compoundTag.put(\"cachedItems\", cachedItemsListTag);\n\n }\n\n @Override\n public void loadFromNBTTag(CompoundTag compoundTag, ItemService itemService) {\n super.loadFromNBTTag(compoundTag, itemService);\n\n outputDir = compoundTag.getInt(\"outputDir\") != -1 ? TPDirection.values()[compoundTag.getInt(\"outputDir\")] : null;\n\n ListTag<StringTag> recipeItemsListTag = (ListTag<StringTag>) compoundTag.getListTag(\"recipeItems\");\n for (int i = 0; i < 9; i++) {\n if (i >= recipeItemsListTag.size()) {\n recipeItems[i] = null;\n continue;\n }\n ItemStack deserialized = itemService.deserializeItemStack(recipeItemsListTag.get(i).getValue());\n recipeItems[i] = deserialized != null ? new ItemData(deserialized) : null;\n }\n\n cachedItems.clear();\n ListTag<StringTag> cachedItemsListTag = (ListTag<StringTag>) compoundTag.getListTag(\"cachedItems\");\n for (int i = 0; i < cachedItemsListTag.size(); i++) {\n ItemStack deserialized = itemService.deserializeItemStack(cachedItemsListTag.get(i).getValue());\n if (deserialized != null)\n cachedItems.add(deserialized);\n }\n\n settingsInv.populate();\n settingsInv.save(null);\n }\n\n @Override\n public List<ItemStack> destroyed(TransportPipes transportPipes, DuctManager ductManager, Player destroyer) {\n List<ItemStack> items = super.destroyed(transportPipes, ductManager, destroyer);\n for (int i = 0; i < 9; i++) {\n ItemData id = recipeItems[i];\n if (id != null) {\n items.add(id.toItemStack().clone());\n }\n }\n for (ItemStack cachedItem : cachedItems) {\n items.add(cachedItem.clone());\n }\n return items;\n }\n}", "public class ItemData {\n\n private ItemStack backedItem;\n\n public ItemData(ItemStack item) {\n this.backedItem = item.clone();\n this.backedItem.setAmount(1);\n }\n\n public ItemStack toItemStack() {\n return backedItem.clone();\n }\n\n @Override\n public int hashCode() {\n int hash = 1;\n\n hash = hash * 31 + backedItem.getType().ordinal();\n hash = hash * 31 + (backedItem.hasItemMeta() ? backedItem.getItemMeta().hashCode() : 0);\n\n return hash;\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 ItemData other = (ItemData) obj;\n if (backedItem == null) {\n return other.backedItem == null;\n } else return backedItem.isSimilar(other.backedItem);\n }\n\n @Override\n public String toString() {\n return backedItem.toString();\n }\n}", "public enum TPDirection {\n\n EAST(1, 0, 0, BlockFace.EAST, LangConf.Key.DIRECTIONS_EAST.get()),\n WEST(-1, 0, 0, BlockFace.WEST, LangConf.Key.DIRECTIONS_WEST.get()),\n SOUTH(0, 0, 1, BlockFace.SOUTH, LangConf.Key.DIRECTIONS_SOUTH.get()),\n NORTH(0, 0, -1, BlockFace.NORTH, LangConf.Key.DIRECTIONS_NORTH.get()),\n UP(0, 1, 0, BlockFace.UP, LangConf.Key.DIRECTIONS_UP.get()),\n DOWN(0, -1, 0, BlockFace.DOWN, LangConf.Key.DIRECTIONS_DOWN.get());\n\n private Vector vec;\n private BlockFace blockFace;\n private String displayName;\n\n TPDirection(int x, int y, int z, BlockFace blockFace, String displayName) {\n this.vec = new Vector(x, y, z);\n this.blockFace = blockFace;\n this.displayName = displayName;\n }\n\n public Vector getVector() {\n return vec.clone();\n }\n\n public int getX() {\n return vec.getBlockX();\n }\n\n public int getY() {\n return vec.getBlockY();\n }\n\n public int getZ() {\n return vec.getBlockZ();\n }\n\n public BlockFace getBlockFace() {\n return blockFace;\n }\n\n public TPDirection getOpposite() {\n return fromBlockFace(getBlockFace().getOppositeFace());\n }\n\n public boolean isSide() {\n return vec.getBlockY() == 0;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public TPDirection next() {\n int ordinal = ordinal();\n ordinal++;\n ordinal %= values().length;\n return values()[ordinal];\n }\n\n public static TPDirection fromBlockFace(BlockFace blockFace) {\n for (TPDirection tpDir : TPDirection.values()) {\n if (tpDir.getBlockFace().equals(blockFace)) {\n return tpDir;\n }\n }\n return null;\n }\n\n}" ]
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.Attribute; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.DragType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.PressurePlate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import de.robotricker.transportpipes.TransportPipes; import de.robotricker.transportpipes.config.LangConf; import de.robotricker.transportpipes.duct.pipe.CraftingPipe; import de.robotricker.transportpipes.duct.pipe.filter.ItemData; import de.robotricker.transportpipes.location.TPDirection;
package de.robotricker.transportpipes.inventory; public class CraftingPipeSettingsInventory extends DuctSettingsInventory { @Override public void create() { inv = Bukkit.createInventory(null, 6 * 9, LangConf.Key.DUCT_INVENTORY_TITLE.get(duct.getDuctType().getFormattedTypeName())); } @Override public void closeForAllPlayers(TransportPipes transportPipes) { save(null); super.closeForAllPlayers(transportPipes); } @Override public void populate() { CraftingPipe pipe = (CraftingPipe) duct; TPDirection outputDir = pipe.getOutputDir(); List<ItemStack> cachedItems = pipe.getCachedItems(); ItemStack glassPane = itemService.createWildcardItem(Material.GRAY_STAINED_GLASS_PANE); for (int i = 0; i < 9; i++) { inv.setItem(i, glassPane); } ItemStack outputDirectionItem = itemService.changeDisplayNameAndLoreConfig(new ItemStack(Material.TRIPWIRE_HOOK), LangConf.Key.DUCT_INVENTORY_CRAFTINGPIPE_OUTPUTDIRECTION.getLines(outputDir != null ? outputDir.getDisplayName() : LangConf.Key.DIRECTIONS_NONE.get())); inv.setItem(8, outputDirectionItem); for (int col = 0; col < 9; col += 4) { for (int row = 1; row < 4; row++) { inv.setItem(row * 9 + col, glassPane); } } for (int i = 0; i < 9; i++) {
ItemData id = pipe.getRecipeItems()[i];
3
mitdbg/AdaptDB
src/main/java/core/adapt/spark/join/SparkJoinQuery.java
[ "public static class PartitionSplit {\n\tprivate int[] partitionIds;\n\tprivate PartitionIterator iterator;\n\n\tpublic PartitionSplit(int[] partitionIds, PartitionIterator iterator) {\n\t\tthis.partitionIds = partitionIds;\n\t\tthis.iterator = iterator;\n\t}\n\n\tpublic int[] getPartitions() {\n\t\treturn this.partitionIds;\n\t}\n\n\tpublic PartitionIterator getIterator() {\n\t\treturn this.iterator;\n\t}\n}", "public class JoinQuery implements Serializable {\n private static final long serialVersionUID = 1L;\n\n private Predicate[] predicates;\n private String table;\n private int joinAttribute;\n\n public JoinQuery(String queryString) {\n String[] parts = queryString.split(\"\\\\|\");\n this.table = parts[0];\n this.joinAttribute = Integer.parseInt(parts[1]);\n if (parts.length > 2) {\n String predString = parts[2].trim();\n String[] predParts = predString.split(\";\");\n this.predicates = new Predicate[predParts.length];\n for (int i = 0; i < predParts.length; i++) {\n this.predicates[i] = new Predicate(predParts[i]);\n }\n } else {\n this.predicates = new Predicate[0];\n }\n }\n\n public JoinQuery(String table, int joinAttribute, Predicate[] predicates) {\n this.table = table;\n this.joinAttribute = joinAttribute;\n this.predicates = predicates;\n }\n\n public Predicate[] getPredicates() {\n return this.predicates;\n }\n\n public String getTable() {\n return this.table;\n }\n\n public int getJoinAttribute(){\n return this.joinAttribute;\n }\n\n public Query castToQuery(){\n return new Query(table, predicates);\n }\n\n public void write(DataOutput out) throws IOException {\n Text.writeString(out, toString());\n }\n\n\n\n @Override\n public String toString() {\n String stringPredicates = \"\";\n if (predicates.length != 0)\n stringPredicates = Joiner.on(\";\").join(predicates);\n return table + \"|\" + joinAttribute + \"|\" + stringPredicates;\n }\n}", "public class Globals {\n // Re-partition cost multiplier.\n static public final int c = 4;\n\n // Query window size.\n static public final int window_size = 20;\n static public final int QUERY_WINDOW_SIZE = 10;\n\n\tstatic Map<String, TableInfo> tableInfos = new HashMap<String, TableInfo>();\n\n public static TableInfo getTableInfo(String tableName) {\n return tableInfos.get(tableName);\n }\n\n public static void addTableInfo(TableInfo tableInfo) {\n tableInfos.put(tableInfo.tableName, tableInfo);\n }\n\n\tpublic static void saveTableInfo(String tableName, String hdfsWorkingDir, short replication, FileSystem fs) {\n TableInfo tableInfo = tableInfos.get(tableName);\n tableInfo.save(hdfsWorkingDir, replication, fs);\n\t}\n\n\tpublic static void loadTableInfo(String tableName, String hdfsWorkingDir, FileSystem fs) {\n if (tableInfos.get(tableName) == null) {\n TableInfo tableInfo = new TableInfo(tableName);\n tableInfo.load(hdfsWorkingDir, fs);\n tableInfos.put(tableName, tableInfo);\n }\n\t}\n}", "public class TableInfo {\n // Name of table.\n public String tableName;\n\n // Total number of tuples in dataset.\n public double numTuples;\n\n // TPC-H generated files use '|'. CSV uses ','.\n public char delimiter;\n\n // Schema of data set.\n public Schema schema;\n\n // -1 for non-join specific partition\n public int[] partitions;\n\n public int depth;\n\n public TableInfo(String tableName) {\n this(tableName, 0, '|', null);\n }\n\n public TableInfo(String tableName, double numTuples, char delimiter, Schema schema) {\n this.tableName = tableName;\n this.numTuples = numTuples;\n this.delimiter = delimiter;\n this.schema = schema;\n this.partitions = new int[]{-1};\n this.depth = 0;\n }\n\n private String partitionsString() {\n String res = \"\";\n for (int i = 0; i < partitions.length; i++) {\n if (i != 0) {\n res += \";\";\n }\n res += Integer.toString(partitions[i]);\n }\n return res;\n }\n\n public TypeUtils.TYPE[] getTypeArray() {\n return schema.getTypeArray();\n }\n\n public void save(String hdfsWorkingDir, short replication, FileSystem fs) {\n String saveContent = \"TOTAL_NUM_TUPLES: \" + numTuples + \"\\n\" +\n \"DELIMITER: \" + delimiter + \"\\n\" +\n \"SCHEMA: \" + schema.toString() + \"\\n\" +\n \"PARTITION: \" + partitionsString() + \"\\n\" +\n \"DEPTH: \" + depth + \"\\n\";\n byte[] saveContentBytes = saveContent.getBytes();\n String path = hdfsWorkingDir + \"/\" + tableName + \"/info\";\n HDFSUtils.writeFile(fs, path, replication,\n saveContentBytes, 0, saveContentBytes.length, false);\n }\n\n public void load(String hdfsWorkingDir, FileSystem fs) {\n String path = hdfsWorkingDir + \"/\" + tableName + \"/info\";\n byte[] fileContent = HDFSUtils.readFile(fs, path);\n String content = new String(fileContent);\n\n String[] settings = content.split(\"\\n\");\n\n if (settings.length != 5) {\n throw new RuntimeException();\n }\n\n for (int i = 0; i < settings.length; i++) {\n String setting = settings[i];\n String[] parts = setting.split(\":\");\n switch (parts[0].trim()) {\n case \"TOTAL_NUM_TUPLES\":\n numTuples = Double.parseDouble(parts[1].trim());\n break;\n case \"DELIMITER\":\n delimiter = parts[1].trim().charAt(0);\n break;\n case \"SCHEMA\":\n schema = Schema.createSchema(parts[1].trim());\n break;\n case \"PARTITION\":\n String[] strPartitions = parts[1].trim().split(\";\");\n partitions = new int[strPartitions.length];\n for (int k = 0; k < strPartitions.length; k++) {\n partitions[k] = Integer.parseInt(strPartitions[k]);\n }\n break;\n case \"DEPTH\":\n depth = Integer.parseInt(parts[1].trim());\n break;\n default:\n System.out.println(\"Unknown setting found: \" + parts[0].trim());\n }\n }\n }\n\n public void gc(String hdfsWorkingDir, FileSystem fs) {\n String path = hdfsWorkingDir + \"/\" + tableName;\n String pathToData = path + \"/data\";\n\n for (int i = 0; i < partitions.length; i++) {\n String pathToIndex;\n\n if (partitions[i] == -1) {\n pathToIndex = path + \"/index\";\n } else {\n pathToIndex = path + \"/index.\" + partitions[i];\n }\n\n byte[] indexBytes = HDFSUtils.readFile(fs, pathToIndex);\n JoinRobustTree rt = new JoinRobustTree(this);\n rt.unmarshall(indexBytes);\n int[] bids = rt.getAllBuckets();\n HashSet<Integer> buckets = new HashSet<Integer>();\n for (int k = 0; k < bids.length; k++) {\n buckets.add(bids[k]);\n }\n try {\n FileStatus[] existingFiles = fs.listStatus(new Path(pathToData));\n for (int k = 0; k < existingFiles.length; k++) {\n Path fp = existingFiles[k].getPath();\n String fileName = FilenameUtils.getName(fp.toString());\n int id = Integer.parseInt(fileName);\n if (buckets.contains(id) == false) {\n fs.delete(fp, false);\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}", "public interface MDIndex {\n\n\t/*\n\t * Placeholder class for the index leaves.\n\t */\n\tfinal class Bucket {\n\t\t/* Actual Values */\n\t\tint bucketId;\n\t\tParsedTupleList sample;\n\n\t\t/* Estimates */\n\t\tprivate double estimatedTuples = 0;\n\n\t\tpublic static int maxBucketId = 0;\n\n\t\tprivate static HashMap<Integer, Double> counter = new HashMap<Integer, Double>();\n\n\t\tpublic Bucket() {\n\t\t\tbucketId = maxBucketId;\n\t\t\tmaxBucketId += 1;\n\t\t}\n\n\t\tpublic Bucket(int id) {\n\t\t\tbucketId = id;\n\t\t\tmaxBucketId = Math.max(bucketId + 1, maxBucketId);\n\t\t}\n\n\t\tpublic double getEstimatedNumTuples() {\n\t\t\t// TODO: This call used when restoring a replaced tree in Optimizer.\n\t\t\t// Can't use the assert below.\n\t\t\t// Assert.assertNotEquals(estimatedTuples, 0.0);\n\t\t\treturn estimatedTuples;\n\t\t}\n\n\t\tpublic static double getEstimatedNumTuples(int bucketId) {\n\t\t\tDouble val = counter.get(bucketId);\n\t\t\treturn val;\n\t\t}\n\n\t\tpublic void setEstimatedNumTuples(double num) {\n\t\t\testimatedTuples = num;\n\t\t\tcounter.put(bucketId, num);\n\t\t}\n\n\t\tpublic int getBucketId() {\n\t\t\treturn bucketId;\n\t\t}\n\n\t\tpublic void updateId() {\n\t\t\tthis.bucketId = maxBucketId;\n\t\t\tmaxBucketId += 1;\n\t\t\testimatedTuples = 0;\n\t\t}\n\n\t\tpublic ParsedTupleList getSample() {\n\t\t\treturn sample;\n\t\t}\n\n\t\tpublic void setSample(ParsedTupleList sample) {\n\t\t\tthis.sample = sample;\n\t\t}\n\t}\n\n//\tpublic static class BucketCounts {\n//\n//\t\tprivate CuratorFramework client;\n//\t\tprivate String counterPathBase = \"/partition-count-\";\n//\n//\t\tpublic BucketCounts(String zookeeperHosts) {\n//\t\t\tclient = CuratorUtils.createAndStartClient(zookeeperHosts);\n//\t\t}\n//\n//\t\tpublic BucketCounts(CuratorFramework client) {\n//\t\t\tthis.client = client;\n//\t\t}\n//\n//\t\tpublic void addToBucketCount(int bucketId, int count) {\n//\t\t\tCuratorUtils.addCounter(client, counterPathBase + bucketId, count);\n//\t\t}\n//\n//\t\tpublic int getBucketCount(int bucketId) {\n//\t\t\treturn CuratorUtils.getCounter(client, counterPathBase + bucketId);\n//\t\t}\n//\n//\t\tpublic void setToBucketCount(int bucketId, int count) {\n//\t\t\tCuratorUtils.setCounter(client, counterPathBase + bucketId, count);\n//\t\t}\n//\n//\t\tpublic void removeBucketCount(int bucketId) {\n//\t\t\tCuratorUtils.setCounter(client, counterPathBase + bucketId, 0);\n//\t\t}\n//\n//\t\tpublic void close() {\n//\t\t\tclient.close();\n//\t\t}\n//\n//\t\tpublic CuratorFramework getClient() {\n//\t\t\treturn this.client;\n//\t\t}\n//\t}\n\n\tpublic MDIndex clone() throws CloneNotSupportedException;\n\n\t/*\n\t *\n\t * The Build phase of the index\n\t */\n\n\tvoid setMaxBuckets(int maxBuckets);\n\n\tint getMaxBuckets();\n\n\t/*\n\t *\n\t * The Probe phase of the index\n\t */\n\tpublic void initProbe();\n\n\tpublic void initProbe(int joinAttribute);\n\n\t/**\n\t * Get the bucket id, for a given key, from an existing index.\n\t *\n\t * @param key\n\t * @return\n\t */\n\tpublic Object getBucketId(RawIndexKey key);\n\n\t/**\n\t * Serialize the index into a byte array.\n\t *\n\t * @return serialized index.\n\t */\n\tpublic byte[] marshall();\n\n\t/**\n\t * Deserialize the index from a byte array.\n\t *\n\t * @param bytes\n\t */\n\tpublic void unmarshall(byte[] bytes);\n\n\t/**\n\t * Created by qui on 7/9/15.\n\t */\n\tclass BucketInfo extends Range {\n\n\t\tprivate int id;\n\n\t\tpublic BucketInfo(int id, TypeUtils.TYPE type, Object low, Object high) {\n\t\t\tsuper(type, low, high);\n\t\t\tthis.id = id;\n\t\t}\n\n\t\tpublic BucketInfo(TypeUtils.TYPE type, Object low, Object high) {\n\t\t\tthis(0, type, low, high);\n\t\t}\n\n\t\tpublic void setId(int id) {\n\t\t\tthis.id = id;\n\t\t}\n\n\t\tpublic int getId() {\n\t\t\treturn id;\n\t\t}\n\n\t\t@Override\n\t\tpublic BucketInfo clone() {\n\t\t\treturn new BucketInfo(id, getType(), getLow(), getHigh());\n\t\t}\n\t}\n}", "public class HDFSUtils {\n\n public static class HDFSData {\n protected static FileSystem fs;\n protected String hadoopConfDir;\n\n public HDFSData(FileSystem fs) {\n if (HDFSData.fs == null)\n HDFSData.fs = fs;\n }\n\n public HDFSData(String hadoopConfDir) {\n if (fs == null) {\n Configuration conf = new Configuration();\n conf.addResource(new Path(hadoopConfDir + \"/core-site.xml\"));\n conf.addResource(new Path(hadoopConfDir + \"/hdfs-site.xml\"));\n try {\n fs = FileSystem.get(conf);\n } catch (IOException e) {\n throw new RuntimeException(\"could not get the filesystem: \"\n + e.getMessage());\n }\n }\n this.hadoopConfDir = hadoopConfDir;\n }\n\n protected void delete(Path dataPath) {\n try {\n fs.delete(dataPath, true);\n } catch (IOException e) {\n throw new RuntimeException(\"could not delete the data path: \"\n + dataPath + \", \" + e.getMessage());\n }\n }\n }\n\n public static class HDFSDir extends HDFSData {\n private Path dataPath;\n\n public HDFSDir(String hadoopConfDir, String dataPath) {\n super(hadoopConfDir);\n this.dataPath = new Path(dataPath);\n }\n\n public List<HDFSFile> getFiles() {\n try {\n List<HDFSFile> files = Lists.newArrayList();\n for (FileStatus fileStatus : fs.listStatus(dataPath))\n files.add(new HDFSFile(hadoopConfDir, fileStatus));\n return files;\n } catch (IOException e) {\n throw new RuntimeException(\n \"failed to list the files in directory \" + dataPath\n + \" ! \" + e.getMessage());\n }\n }\n\n public void delete() {\n super.delete(dataPath);\n }\n }\n\n public static class HDFSFile extends HDFSData {\n private FileStatus status;\n\n public HDFSFile(String hadoopConfDir, FileStatus status) {\n super(hadoopConfDir);\n this.status = status;\n }\n\n public HDFSFile() {\n super(HDFSData.fs);\n }\n\n public boolean isCorrupted() {\n try {\n for (BlockLocation blk : fs.getFileBlockLocations(status, 0,\n status.getLen())) {\n if (blk.isCorrupt())\n return true;\n }\n return false;\n } catch (IOException e) {\n throw new RuntimeException(\n \"failed to get the blocks locations of file \"\n + status.getPath() + \" ! \" + e.getMessage());\n }\n }\n\n public void delete() {\n super.delete(status.getPath());\n }\n\n public List<HDFSFile> getSiblingFiles(String prefix) {\n final String siblingPrefix = prefix;\n String parentDir = FilenameUtils\n .getPath(status.getPath().getName());\n try {\n FileStatus[] siblingStatuses = fs.listStatus(\n new Path(parentDir), new PathFilter() {\n @Override\n public boolean accept(Path path) {\n return path.getName().startsWith(siblingPrefix);\n }\n });\n List<HDFSFile> siblingFiles = Lists.newArrayList();\n for (FileStatus status : siblingStatuses)\n siblingFiles.add(new HDFSFile(hadoopConfDir, status));\n return siblingFiles;\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to get the siblings of \"\n + status.getPath() + \", \" + e.getMessage());\n }\n }\n\n public String getPath() {\n return status.getPath().getName();\n }\n\n public void increaseReplication(int increment) {\n Path p = status.getPath();\n try {\n fs.setReplication(p,\n (short) (status.getReplication() + increment));\n } catch (IOException e) {\n throw new RuntimeException(\n \"Failed to increase the replication of \" + getPath()\n + \" by \" + increment + \", \" + e.getMessage());\n }\n }\n\n public byte[] getBytes() {\n return null; // TODO\n }\n\n public void putBytes(byte[] bytes) {\n // TODO\n }\n }\n\n private static FileSystem fs;\n\n private static FileSystem getFS(String coreSitePath) {\n if (fs == null) {\n try {\n Configuration conf = new Configuration();\n conf.addResource(new Path(coreSitePath));\n fs = FileSystem.get(conf);\n } catch (Exception e) {\n throw new RuntimeException(\n \"Failed to get the HDFS Filesystem! \" + e.getMessage());\n }\n }\n return fs;\n }\n\n public static FileSystem getFSByHadoopHome(String hadoopHome) {\n return getFS(hadoopHome + \"/etc/hadoop/core-site.xml\");\n }\n\n public static OutputStream getHDFSOutputStream(FileSystem hdfs,\n String filename, short replication, int bufferSize) {\n try {\n Path path = new Path(filename);\n if (hdfs.exists(path)) {\n return new BufferedOutputStream(hdfs.append(path, replication),\n bufferSize);\n } else {\n return new BufferedOutputStream(hdfs.create(path, replication),\n bufferSize);\n }\n } catch (FileNotFoundException e) {\n throw new RuntimeException(\"Could not open the file:\" + filename);\n } catch (IOException e) {\n throw new RuntimeException(\"Could not open the file:\" + filename\n + \", \" + e.getMessage());\n }\n }\n\n public static OutputStream getBufferedHDFSOutputStream(\n FileSystem fs, String filename, short replication, int bufferSize,\n CuratorFramework client) {\n return new HDFSBufferedOutputStream(fs, filename, replication,\n bufferSize, client);\n }\n\n public static InputStream getHDFSInputStream(FileSystem hdfs,\n String filename) {\n try {\n return hdfs.open(new Path(filename));\n } catch (IOException e) {\n e.printStackTrace();\n throw new RuntimeException(\"Could not read from file:\" + filename);\n }\n }\n\n public static void writeFile(FileSystem hdfs, String filename,\n short replication, byte[] bytes, int offset, int length,\n boolean append) {\n try {\n Path path = new Path(filename);\n FSDataOutputStream os;\n if (append && hdfs.exists(path))\n os = hdfs.append(path);\n else\n os = hdfs.create(new Path(filename), replication);\n os.write(bytes, offset, length);\n os.flush();\n os.close();\n } catch (IOException e) {\n e.printStackTrace();\n throw new RuntimeException(\"Could not write to file:\" + filename);\n }\n }\n\n public static byte[] readFile(FileSystem hdfs, String filename) {\n try {\n FSDataInputStream in = hdfs.open(new Path(filename));\n byte[] bytes = ByteStreams.toByteArray(in);\n in.close();\n return bytes;\n } catch (IOException e) {\n e.printStackTrace();\n throw new RuntimeException(\"Could not read from file:\" + filename);\n }\n }\n\n public static void closeHDFSInputStream(FSDataInputStream fsInputStream) {\n try {\n fsInputStream.close();\n } catch (IOException e) {\n throw new RuntimeException(\"Cannot close file. \" + e.getMessage());\n }\n }\n\n public static void safeCreateFile(FileSystem fs, String path,\n short replication) {\n try {\n Path e = new Path(path);\n FSDataOutputStream os = fs.create(e, false, fs.getConf().getInt(\"io.file.buffer.size\", 4096),\n replication, fs.getDefaultBlockSize(e));\n os.close();\n\n } catch (IOException e) {\n }\n }\n\n\n public static void safeCreateDirectory(FileSystem fs, String path) {\n try {\n Path p = new Path(path);\n if (!fs.exists(p)) {\n fs.mkdirs(p);\n }\n } catch (IOException e) {\n }\n }\n\n public static boolean deleteFile(FileSystem fs, String filename,\n boolean recursive) {\n try {\n return fs.delete(new Path(filename), recursive);\n } catch (IOException e) {\n return false;\n }\n }\n\n public static void copyFile(FileSystem fs, String origin, String destination,\n short replication) {\n byte[] contents = readFile(fs, origin);\n writeFile(fs, destination, replication, contents, 0, contents.length, false);\n }\n\n public static List<String> readHDFSLines(String hadoopHome, String filename) {\n try {\n Configuration conf = new Configuration();\n conf.addResource(new Path(hadoopHome + \"/etc/hadoop/core-site.xml\"));\n FileSystem fs = FileSystem.get(conf);\n Path path = new Path(filename);\n if (!fs.exists(path))\n return Lists.newArrayList();\n\n BufferedReader br = new BufferedReader(new InputStreamReader(\n fs.open(path)));\n String line;\n List<String> lines = Lists.newArrayList();\n while ((line = br.readLine()) != null)\n lines.add(line);\n br.close();\n\n return lines;\n } catch (IOException e) {\n throw new RuntimeException(\"could not read the inputstream!\");\n }\n }\n\n public static List<String> readHDFSLines(FileSystem fs, String filename) {\n try {\n Path path = new Path(filename);\n if (!fs.exists(path))\n return Lists.newArrayList();\n\n BufferedReader br = new BufferedReader(new InputStreamReader(\n fs.open(path)));\n String line;\n List<String> lines = Lists.newArrayList();\n while ((line = br.readLine()) != null)\n lines.add(line);\n br.close();\n\n return lines;\n } catch (IOException e) {\n throw new RuntimeException(\"could not read the inputstream!\");\n }\n }\n\n public static void appendLine(FileSystem fs, String filepath,\n String line) {\n try {\n FSDataOutputStream fout = fs.append(\n new Path(filepath));\n fout.write(line.getBytes());\n fout.write('\\n');\n fout.close();\n } catch (IOException e) {\n e.printStackTrace();\n throw new RuntimeException(\"could not append to file: \" + filepath);\n }\n }\n\n public static void appendBytes(String hadoopHome, String filePath,\n byte[] bytes, int start, int length) {\n appendBytes(getFSByHadoopHome(hadoopHome), filePath, bytes, start,\n length);\n }\n\n public static void appendBytes(FileSystem fs, String filepath,\n byte[] bytes, int start, int length) {\n try {\n FSDataOutputStream fout = fs.append(new Path(filepath));\n fout.write(bytes, start, length);\n fout.close();\n } catch (IOException e) {\n //e.printStackTrace();\n System.out.println(\"Could not append to file: \" + filepath);\n //throw new RuntimeException(\"Could not append to file: \" + filepath);\n }\n }\n\n public static void writeHDFSLines(String hadoopHome, String filename,\n List<String> lines) {\n try {\n Configuration conf = new Configuration();\n conf.addResource(new Path(hadoopHome + \"/etc/hadoop/core-site.xml\"));\n FileSystem fs = FileSystem.get(conf);\n Path path = new Path(filename);\n if (fs.exists(path))\n fs.delete(path, true);\n\n FSDataOutputStream fout = fs.create(path);\n for (String line : lines) {\n fout.write(line.getBytes());\n fout.write('\\n');\n }\n\n fout.close();\n fs.close();\n\n } catch (IOException e) {\n e.printStackTrace();\n throw new RuntimeException(\"failed to write the hdfs file: \"\n + filename + \", \" + e.getMessage());\n }\n }\n\n public static OutputStream getOutputStreamWithRetry(FileSystem fs,\n String filename, long retryIntervalMs, int maxRetryCount) {\n return getOutputStreamWithRetry(fs, filename, (short) 3,\n retryIntervalMs, maxRetryCount);\n }\n\n public static OutputStream getOutputStreamWithRetry(FileSystem fs,\n String filename, short replication, long retryIntervalMs,\n int maxRetryCount) {\n FSDataOutputStream fout = null;\n Path path = new Path(filename);\n\n int retryCount = 0;\n while (retryCount < maxRetryCount) {\n try {\n if (!fs.exists(path))\n fout = fs.create(path, replication);\n else\n fout = fs.append(path);\n break;\n } catch (IOException e) {\n try {\n Thread.sleep(retryIntervalMs);\n } catch (InterruptedException i) {\n throw new RuntimeException(\"Failed to sleep the thread: \"\n + i.getMessage());\n }\n }\n }\n if (fout == null)\n throw new RuntimeException(\"failed to write the hdfs file: \"\n + filename);\n else\n return fout;\n }\n\n\n public static List<String> getDataNodes(String hadoopHome) {\n List<String> lines = Lists.newArrayList();\n BufferedReader reader = null;\n try {\n reader = new BufferedReader(new FileReader(hadoopHome\n + \"/conf/slaves\"));\n } catch (FileNotFoundException e) {\n try {\n reader = new BufferedReader(new FileReader(hadoopHome\n + \"/etc/hadoop/slaves\"));\n } catch (FileNotFoundException e1) {\n throw new RuntimeException(\"Failed to read the slaves file: \"\n + e.getMessage());\n }\n } finally {\n try {\n String line;\n while ((line = reader.readLine()) != null)\n lines.add(line);\n reader.close();\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to read the slaves file: \"\n + e.getMessage());\n }\n }\n return lines;\n }\n}", "public class ConfUtils {\n\tprivate Properties p;\n\n\tpublic ConfUtils(String propertiesFile) {\n\t\tp = new Properties();\n\t\ttry {\n\t\t\tp.load(new FileInputStream(propertiesFile));\n\t\t} catch (FileNotFoundException e) {\n\t\t\tthrow new RuntimeException(\"could not read the properties file!\");\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(\"could not read the properties file!\");\n\t\t}\n\t}\n\n\t/**\n\t * Choose whether to enable optimizer If false, just runs the query If true,\n\t * tries to optimize the storage layout\n\t *\n\t * @return\n\t */\n\tpublic boolean getENABLE_OPTIMIZER() {\n\t\treturn Boolean.parseBoolean(p.getProperty(\"ENABLE_OPTIMIZER\").trim());\n\t}\n\n\tpublic String getMACHINE_ID() {\n\t\tString machineId = p.getProperty(\"MACHINE_ID\").trim()\n\t\t\t\t.replaceAll(\"\\\\W+\", \"\");\n\t\tassert !machineId.equals(\"\");\n\t\treturn machineId;\n\t}\n\n\t/********** SPARK CONFIG **************/\n\tpublic String getSPARK_MASTER() {\n\t\treturn p.getProperty(\"SPARK_MASTER\").trim();\n\t}\n\n\tpublic String getSPARK_HOME() {\n\t\treturn p.getProperty(\"SPARK_HOME\").trim();\n\t}\n\n\t/**\n\t * @return spark application jar filepath\n\t */\n\tpublic String getSPARK_APPLICATION_JAR() {\n\t\treturn p.getProperty(\"SPARK_APPLICATION_JAR\").trim();\n\t}\n\n\tpublic String getSPARK_EXECUTOR_MEMORY() {\n\t\treturn p.getProperty(\"SPARK_EXECUTOR_MEMORY\").trim();\n\t}\n\n\tpublic String getSPARK_DRIVER_MEMORY() {\n\t\treturn p.getProperty(\"SPARK_DRIVER_MEMORY\").trim();\n\t}\n\n\tpublic String getSPARK_TASK_CPUS() {\n\t\treturn p.getProperty(\"SPARK_TASK_CPUS\").trim();\n\t}\n\n\t/********** ZOOKEEPER CONFIG **************/\n\tpublic String getZOOKEEPER_HOSTS() {\n\t\treturn p.getProperty(\"ZOOKEEPER_HOSTS\").trim();\n\t}\n\n\t/********** HADOOP CONFIG **************/\n\t/**\n\t * Path to hadoop installation\n\t *\n\t * @return\n\t */\n\tpublic String getHADOOP_HOME() {\n\t\treturn p.getProperty(\"HADOOP_HOME\");\n\t}\n\n\t/**\n\t * Path to hadoop namenode, eg: hdfs://localhost:9000\n\t *\n\t * @return\n\t */\n\tpublic String getHADOOP_NAMENODE() {\n\t\treturn p.getProperty(\"HADOOP_NAMENODE\").trim();\n\t}\n\n\t/**\n\t * Get working directory in HDFS.\n\t *\n\t * @return filepath to hdfs working dir\n\t */\n\tpublic String getHDFS_WORKING_DIR() {\n\t\treturn p.getProperty(\"HDFS_WORKING_DIR\").trim();\n\t}\n\tpublic void setHDFS_WORKING_DIR(String path){\n\t\tp.setProperty(\"HDFS_WORKING_DIR\", path);\n\t}\n\n\t/**\n\t * Get HDFS Replication Factor\n\t *\n\t * @return\n\t */\n\tpublic short getHDFS_REPLICATION_FACTOR() {\n\t\treturn Short\n\t\t\t\t.parseShort(p.getProperty(\"HDFS_REPLICATION_FACTOR\").trim());\n\t}\n}" ]
import core.adapt.AccessMethod.PartitionSplit; import core.adapt.JoinQuery; import core.common.globals.Globals; import core.common.globals.TableInfo; import core.common.index.MDIndex; import core.utils.HDFSUtils; import core.utils.SparkUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaSparkContext; import core.utils.ConfUtils; import org.apache.spark.api.java.function.PairFunction; import scala.Tuple2; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package core.adapt.spark.join; /** * Created by ylu on 1/6/16. */ public class SparkJoinQuery { public static class Mapper implements PairFunction<Tuple2<LongWritable, Tuple2<Text, Text>>, LongWritable, Text> { String Delimiter; String Splitter; int partitionKey; public Mapper(String Delimiter, int partitionKey) { this.Delimiter = Delimiter; this.partitionKey = partitionKey; if (Delimiter.equals("|")) Splitter = "\\|"; else Splitter = Delimiter; } @Override public Tuple2<LongWritable, Text> call(Tuple2<LongWritable, Tuple2<Text, Text>> x) throws Exception { String s1 = x._2()._1().toString(); String s2 = x._2()._2().toString(); String value = s1 + Delimiter + s2; long key = Long.parseLong(value.split(Splitter)[partitionKey]); return new Tuple2<LongWritable, Text>(new LongWritable(key), new Text(value)); } } private SparkJoinQueryConf queryConf; private JavaSparkContext ctx; private ConfUtils cfg; private String Delimiter = "|"; private String joinStrategy = "Heuristic"; public SparkJoinQuery(ConfUtils config) { this.cfg = config; SparkConf sconf = SparkUtils.getSparkConf(this.getClass().getName(), config); try { sconf.registerKryoClasses(new Class<?>[]{ Class.forName("org.apache.hadoop.io.LongWritable"), Class.forName("org.apache.hadoop.io.Text") }); } catch (ClassNotFoundException e) { e.printStackTrace(); } ctx = new JavaSparkContext(sconf); ctx.hadoopConfiguration().setBoolean( FileInputFormat.INPUT_DIR_RECURSIVE, true); ctx.hadoopConfiguration().set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); queryConf = new SparkJoinQueryConf(ctx.hadoopConfiguration()); queryConf.setHDFSReplicationFactor(cfg.getHDFS_REPLICATION_FACTOR()); queryConf.setHadoopHome(cfg.getHADOOP_HOME()); queryConf.setZookeeperHosts(cfg.getZOOKEEPER_HOSTS()); queryConf.setMaxSplitSize(4L * 1024 * 1024 * 1024); // 4 GB //queryConf.setMaxSplitSize(400L * 1024 * 1024); // 400 MB queryConf.setWorkerNum(8); } public JavaSparkContext getSparkContext(){ return ctx; } public void setBufferSize(long size){ queryConf.setMaxSplitSize(size); } public void setDelimiter(String delimiter) { Delimiter = delimiter; } public String getDelimiter() { return Delimiter; } /* SparkJoinQuery */ public JavaPairRDD<LongWritable, Text> createJoinRDD(String hdfsPath) { queryConf.setReplicaId(0); return ctx.newAPIHadoopFile(cfg.getHADOOP_NAMENODE() + hdfsPath, SparkJoinInputFormat.class, LongWritable.class, Text.class, ctx.hadoopConfiguration()); } public JavaPairRDD<LongWritable, Text> createJoinRDD( String dataset1, JoinQuery dataset1_query, String dataset2, JoinQuery dataset2_query, int partitionKey) { // set SparkQuery conf String hdfsPath = cfg.getHDFS_WORKING_DIR(); queryConf.setWorkingDir(hdfsPath); queryConf.setJustAccess(false); Configuration conf = ctx.hadoopConfiguration(); conf.set("DATASET1", dataset1); conf.set("DATASET2", dataset2); conf.set("DATASET1_QUERY", dataset1_query.toString()); conf.set("DATASET2_QUERY", dataset2_query.toString()); conf.set("PARTITION_KEY", Integer.toString(partitionKey)) ; conf.set("JOINALGO", joinStrategy); conf.set("DELIMITER", Delimiter); JoinPlanner planner = new JoinPlanner(conf); String hyperJoinInput = planner.hyperjoin; System.out.println("hyperJoinInput: " + hyperJoinInput); conf.set("DATASETINFO",hyperJoinInput); JavaPairRDD<LongWritable, Text> hyperjoin_rdd = createJoinRDD(hdfsPath); String input1 = planner.shufflejoin1; String input2 = planner.shufflejoin2; System.out.println("shuffleInput1: " + input1); System.out.println("shuffleInput2: " + input2); // set conf input; conf.set("DATASET_QUERY", dataset1_query.toString()); conf.set("DATASETINFO", input1); conf.set("DATASET", dataset1); JavaPairRDD<LongWritable, Text> dataset1RDD = createSingleTableRDD(hdfsPath, dataset1_query); // set conf input; conf.set("DATASET_QUERY", dataset2_query.toString()); conf.set("DATASETINFO", input2); conf.set("DATASET", dataset2); JavaPairRDD<LongWritable, Text> dataset2RDD = createSingleTableRDD(hdfsPath, dataset2_query); int numPartitions = 2000; JavaPairRDD<LongWritable, Tuple2<Text,Text> > join_rdd = dataset1RDD.join(dataset2RDD, numPartitions); JavaPairRDD<LongWritable, Text> shufflejoin_rdd = join_rdd.mapToPair(new Mapper(Delimiter, partitionKey)); return hyperjoin_rdd.union(shufflejoin_rdd); } /* SingleTableScan */ public JavaPairRDD<LongWritable, Text> createSingleTableRDD(String hdfsPath, JoinQuery q) { queryConf.setWorkingDir(hdfsPath); queryConf.setJoinQuery(q); return ctx.newAPIHadoopFile(cfg.getHADOOP_NAMENODE() + hdfsPath + "/" + q.getTable() + "/data", SparkScanInputFormat.class, LongWritable.class, Text.class, ctx.hadoopConfiguration()); } /* for tpch 6 */ public JavaPairRDD<LongWritable, Text> createScanRDD(String dataset, JoinQuery q) { // set SparkQuery conf String hdfsPath = cfg.getHDFS_WORKING_DIR(); queryConf.setJustAccess(false); queryConf.setWorkingDir(hdfsPath); Configuration conf = ctx.hadoopConfiguration(); conf.set("DATASET", dataset); conf.set("DATASET_QUERY", q.toString()); conf.set("PARTITION_KEY", "0") ; conf.set("JOINALGO", joinStrategy); conf.set("DELIMITER", Delimiter); FileSystem fs = HDFSUtils.getFSByHadoopHome(queryConf.getHadoopHome()); String workingDir = queryConf.getWorkingDir(); //System.out.println("INFO working dir: " + workingDir); List<JoinQuery> dataset_queryWindow = JoinPlanner.loadQueries(dataset, queryConf); dataset_queryWindow.add(q); JoinPlanner.persistQueryToDisk(q, queryConf);
Globals.loadTableInfo(dataset, queryConf.getWorkingDir(), fs);
2
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/models/Item.java
[ "public class Application extends android.app.Application {\n private Tracker mTracker;\n private ClientWebView mWebView;\n\n @Override\n public void onCreate()\n {\n mWebView = new ClientWebView(getApplicationContext());\n ImageStorage.getInstance().setContext(getApplicationContext());\n Data.getInstance().setContext(getApplicationContext());\n super.onCreate();\n }\n\n public ClientWebView getWebView() {\n return mWebView;\n }\n\n\n public synchronized Tracker getTracker() {\n if(mTracker==null){\n GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);\n mTracker = analytics.newTracker(R.xml.global_tracker);\n }\n return mTracker;\n }\n}", "public class Characters {\n public static Characters mInstance = new Characters();\n private Characters(){}\n\n public static Characters getInstance(){\n return mInstance;\n }\n\n private List<Character> mCharacters;\n\n public void loadFromJson(JSONArray jsonArray) throws JSONException {\n mCharacters = Character.collectionFromJson(jsonArray);\n }\n\n public List<Character> all() {\n return mCharacters;\n }\n\n public void clean() {\n mCharacters=null;\n }\n\n public Character get(String id) {\n for (Character character : mCharacters) {\n if (character.getId().equals(id)) {\n return character;\n }\n }\n return null;\n }\n}", "public class ItemMonitor {\n private final Set<BaseAdapter> registeredAdapters = new HashSet<>();\n private static final ItemMonitor mInstance = new ItemMonitor();\n\n private ItemMonitor() {\n\n }\n\n static public ItemMonitor getInstance() {\n return mInstance;\n }\n\n public void registerAdapter(BaseAdapter adapter) {\n registeredAdapters.add(adapter);\n }\n\n public void unregisterAdapter(BaseAdapter adapter) {\n registeredAdapters.remove(adapter);\n }\n\n\n public void notifyChanged() {\n for (BaseAdapter adapter : registeredAdapters) {\n Log.v(\"ItemMonitor\", \"notifing: \"+adapter);\n adapter.notifyDataSetChanged();\n }\n }\n}", "public class Items {\n public static final String VAULT_ID = \"VAULT\";\n\n private Map<String, List<Item>> items = new HashMap<>();\n private Map<Item, String> itemsOwners = new HashMap<>();\n\n\n static public Items mInstance = new Items();\n\n private Items() {\n\n }\n\n static public Items getInstance() {\n return mInstance;\n }\n\n public Map<String, List<Item>> allAsMap() {\n return items;\n }\n\n public void put(String id, List<Item> items) {\n this.items.put(id, items);\n for (Item item : items) {\n this.itemsOwners.put(item, id);\n }\n }\n\n public List<Item> allNotFor(String key) {\n List<Item> allItems = new ArrayList<>();\n for (Map.Entry<String, List<Item>> entry : items.entrySet()) {\n if (Preferences.getInstance().showAll() || !entry.getKey().equals(key)) {\n for (Item i : entry.getValue()) {\n if (i.isVisible() && Filters.getInstance().isVisible(i))\n allItems.add(i);\n }\n }\n }\n Collections.sort(allItems);\n return allItems;\n }\n\n public List<Item> all() {\n List<Item> allItems = new ArrayList<>();\n\n for (Map.Entry<String, List<Item>> entry : items.entrySet()) {\n for (Item i : entry.getValue()) {\n if (i.isVisible() && Filters.getInstance().isVisible(i))\n allItems.add(i);\n }\n }\n Collections.sort(allItems);\n return allItems;\n }\n\n public List<Item> allWithoutFiltering() {\n List<Item> allItems = new ArrayList<>();\n\n for (Map.Entry<String, List<Item>> entry : items.entrySet()) {\n allItems.addAll(entry.getValue());\n }\n return allItems;\n }\n\n public void clean() {\n items = new HashMap<>();\n itemsOwners = new HashMap<>();\n }\n\n public String getItemOwner(Item item) {\n String owner = itemsOwners.get(item);\n if (owner == null) {\n for (Map.Entry<Item, String> entry : itemsOwners.entrySet()) {\n if (entry.getKey().getItemHash() == item.getItemHash()) {\n return entry.getValue();\n }\n }\n }\n return owner;\n }\n\n public String getItemOwnerName(Item item) {\n if (item.getLocation() == item.LOCATION_VENDOR) {\n return \"Vendor\";\n }\n if (item.getLocation() == item.LOCATION_POSTMASTER) {\n return \"Postmaster\";\n }\n String owner = getItemOwner(item);\n if (owner == null) {\n return \"None\";\n }\n if (owner.equals(VAULT_ID)) {\n return \"Vault\";\n }\n org.swistowski.vaulthelper.models.Character character = Characters.getInstance().get(owner);\n if (character != null) {\n return character.getLabel();\n }\n\n return \"None\";\n }\n\n\n public void changeOwner(Item item, String target, int stackSize) {\n if (item.getInstanceId() != 0) {\n String owner = getItemOwner(item);\n if (items.get(owner) != null) {\n items.get(owner).remove(item);\n items.get(target).add(item);\n itemsOwners.put(item, target);\n }\n\n } else {\n int leftOvers = item.getStackSize() - stackSize;\n boolean exists = false;\n /*\n Item new_item = item.make_clone();\n new_item.setStackSize(item.getStackSize()-stackSize);\n */\n for (Item tmp_item : items.get(target)) {\n if (tmp_item.getItemHash() == item.getItemHash()) {\n // exists!\n item.setStackSize(tmp_item.getStackSize() + stackSize);\n if (items.get(target) != null) {\n items.get(target).remove(tmp_item);\n itemsOwners.remove(tmp_item);\n exists = true;\n }\n break;\n\n }\n }\n // moved to fresh place\n if (!exists) {\n item.setStackSize(stackSize);\n }\n\n String owner = getItemOwner(item);\n if (items.get(owner) != null) {\n items.get(owner).remove(item);\n items.get(target).add(item);\n itemsOwners.put(item, target);\n }\n\n if (leftOvers > 0) {\n // recreate!\n Item new_item = item.make_clone();\n new_item.setStackSize(leftOvers);\n items.get(owner).add(new_item);\n itemsOwners.put(new_item, owner);\n }\n }\n ItemMonitor.getInstance().notifyChanged();\n }\n\n}", "public class Data implements Serializable {\n private static final String LOG_TAG = \"Database\";\n private static final Data ourInstance = new Data();\n\n private User mUser;\n private Membership mMembership;\n private boolean mShowAll = true;\n\n private Context context;\n\n\n private boolean mIsLoading = false;\n\n private Data() {\n }\n\n public static Data getInstance() {\n return ourInstance;\n }\n\n\n public User loadUserFromJson(JSONObject json) throws JSONException {\n mUser = User.fromJson(json);\n return mUser;\n }\n\n public User getUser() {\n return mUser;\n }\n\n public Membership loadMembershipFromJson(JSONObject json) {\n this.mMembership = Membership.fromJson(json);\n return mMembership;\n }\n\n\n public Membership getMembership() {\n return mMembership;\n }\n\n\n public void clean() {\n mUser = null;\n mMembership = null;\n Characters.getInstance().clean();\n Items.getInstance().clean();\n }\n\n public void cleanCharacters() {\n Characters.getInstance().clean();\n Items.getInstance().clean();\n }\n\n\n public synchronized void setIsLoading(boolean isLoading) {\n mIsLoading = isLoading;\n }\n\n public boolean getIsLoading() {\n return mIsLoading;\n }\n\n\n\n public Context getContext() {\n return context;\n }\n\n public void setContext(Context context) {\n this.context = context;\n Labels.getInstance().setContext(context);\n }\n}", "public class Labels {\n\n private DB mDb;\n private static Labels mInstance = new Labels();\n private Context context;\n private HashMap<Long, Set<Long>> items;\n private HashMap<Long, Label> labels;\n private HashMap<Long, Set<Long>> itemLabels;\n private List<Label> labelsList;\n\n private long current = -1;\n\n\n private Labels() {\n }\n\n public static Labels getInstance() {\n return mInstance;\n }\n\n public DB getDb() {\n if (mDb == null) {\n mDb = new DB(getContext());\n }\n return mDb;\n }\n\n private HashMap<Long, Set<Long>> getItems() {\n if (items == null) {\n items = getDb().getAllItems();\n }\n return items;\n }\n\n public List<Label> getLabelList() {\n if (labelsList == null) {\n Collection<Label> labelsFromDb = getDb().getLabels();\n labelsList = new ArrayList<>(labelsFromDb);\n }\n return labelsList;\n }\n\n\n public Map<Long, Label> getLabels() {\n if (labels == null) {\n labels = new HashMap<>();\n for (Label label : getLabelList()) {\n labels.put(label.getId(), label);\n }\n }\n return labels;\n }\n\n private Set<Long> getLabelItems(Long labelId) {\n if(!getItems().containsKey(labelId)){\n getItems().put(labelId, new HashSet<Long>());\n }\n return getItems().get(labelId);\n }\n\n public void addLabelToItem(long item, long labelId) {\n getDb().addItem(item, labelId);\n getLabelItems(labelId).add(item);\n }\n\n public void deleteLabelFromItem(long item, long labelId) {\n getDb().deleteItem(item, labelId);\n getLabelItems(labelId).remove(item);\n }\n\n public boolean hasLabel(long item, long labelId) {\n return getLabelItems(labelId).contains(item);\n }\n\n public void setContext(Context context) {\n this.context = context;\n }\n\n public Context getContext() {\n return context;\n }\n\n public int count() {\n return getItems().size();\n }\n\n public long getCurrent() {\n if(current==-1){\n current = getLabelList().get(0).getId();\n }\n return current;\n }\n\n public void setCurrent(long current){\n this.current = current;\n ItemMonitor.getInstance().notifyChanged();\n //LabelMonitor.getInstance().notifyChanged();\n }\n\n\n public Label add(Label label) {\n label.setId(getDb().addLabel(label.getName(), label.getColor()));\n cleanLocalCache();\n LabelMonitor.getInstance().notifyChanged();\n return label;\n }\n\n private void cleanLocalCache() {\n labelsList = null;\n labels = null;\n items = null;\n itemLabels = null;\n }\n\n public void update(Label label) {\n getDb().updateLabel(label.getId(), label.getName(), label.getColor());\n LabelMonitor.getInstance().notifyChanged();\n }\n\n public void delete(Label label) {\n getDb().deleteLabel(label.getId());\n cleanLocalCache();\n if(current==label.getId()){\n current = -1;\n }\n LabelMonitor.getInstance().notifyChanged();\n }\n\n private Map<Long, Set<Long>> getItemLabels(){\n if(itemLabels==null) {\n itemLabels = new HashMap<>();\n for(Map.Entry<Long, Set<Long>> entry: getItems().entrySet()){\n for (Long itemId : entry.getValue()) {\n if(!itemLabels.containsKey(itemId)){\n itemLabels.put(itemId, new HashSet<Long>());\n }\n itemLabels.get(itemId).add(entry.getKey());\n }\n }\n }\n return itemLabels;\n }\n\n public List<Label> getLabelsForItem(long itemId) {\n LinkedList<Label> labels = new LinkedList<>();\n if(getItemLabels().containsKey(itemId)){\n for (Long labelId : getItemLabels().get(itemId)) {\n labels.add(getLabels().get(labelId));\n }\n }\n return labels;\n }\n}", "public class ClientWebView extends WebView {\n public void setErrorHandler(ErrorHandler errorHandler) {\n this.errorHandler = errorHandler;\n }\n\n public interface ErrorHandler {\n boolean processError(ConsoleMessage cm);\n }\n\n private ErrorHandler errorHandler;\n private final String LOG_TAG = \"ClientWebView\";\n private boolean mPrepared = false;\n private boolean mInitialized = false;\n private final Map<String, Promise> mPromises = new HashMap<>();\n private final Handler mHandler = new Handler(Looper.getMainLooper());\n private Activity currentActivity;\n\n public ClientWebView(Context context) {\n super(context);\n init(context);\n }\n\n public ClientWebView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context);\n }\n\n public ClientWebView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(context);\n }\n\n private void init(Context context) {\n\n }\n\n @SuppressLint(\"AddJavascriptInterface\")\n public void prepare(final Runnable onInit) {\n\n if (!mPrepared) {\n\n mPrepared = true;\n setWebChromeClient(new WebChromeClient() {\n public boolean onConsoleMessage(ConsoleMessage cm) {\n if (errorHandler != null) {\n errorHandler.processError(cm);\n }\n if (errorHandler == null)\n Log.d(LOG_TAG, \"Does not have error handler\");\n else\n Log.d(LOG_TAG, \"Have error handler\");\n Log.d(LOG_TAG + \" js\", cm.message() + \" -- From line \"\n + cm.lineNumber() + \" of \"\n + cm.sourceId());\n return true;\n }\n });\n\n setWebViewClient(new WebViewClient() {\n @Override\n public void onPageFinished(WebView view, String url) {\n if (!mInitialized) {\n mInitialized = true;\n onInit.run();\n }\n super.onPageFinished(view, url);\n }\n\n @Override\n public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {\n if (currentActivity != null) {\n new AlertDialog.Builder(currentActivity).setTitle(getContext().getString(R.string.critical_error)).setMessage(\n String.format(getContext().getString(R.string.no_url_error), failingUrl)\n ).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n System.exit(0);\n }\n }).setIcon(android.R.drawable.ic_dialog_alert)\n .show();\n } else {\n System.exit(0);\n }\n\n super.onReceivedError(view, errorCode, description, failingUrl);\n }\n });\n getSettings().setJavaScriptEnabled(true);\n addJavascriptInterface(new JsObject(mPromises), \"clientHandler\");\n loadUrl(\"http://www.bungie.net/\");\n\n } else\n onInit.run();\n\n }\n\n\n public boolean isPrepared() {\n return mPrepared;\n }\n\n public Promise callAny(String javascript) {\n final Promise p = new Promise();\n final int promiseId = identityHashCode(p);\n mPromises.put(\"\" + promiseId, p);\n queueJavascript(\"window.clientHandler.accept(\\\"\" + promiseId + \"\\\", \" + javascript + \")\");\n return p;\n }\n\n public Promise call(String methodName, JSONObject parameters) {\n final Promise p = new Promise();\n final int promiseId = identityHashCode(p);\n mPromises.put(\"\" + promiseId, p);\n queueJavascript(\"bungieNetPlatform.\" + methodName + \"(\" + parameters.toString() + \" , function(data){window.clientHandler.accept(\\\"\" + promiseId + \"\\\", JSON.stringify(data))}, function(data){window.clientHandler.error(\\\"\" + promiseId + \"\\\", JSON.stringify(data))})\");\n return p;\n }\n\n public Promise call(String methodName, String... arguments) {\n final Promise p = new Promise();\n final int promiseId = identityHashCode(p);\n\n String tmp = \"\";\n for (String argument : arguments) {\n tmp += argument + \" \";\n }\n String processedArguments = \"\";\n for (String arg : arguments) {\n if (!processedArguments.equals(\"\")) {\n processedArguments += \",\";\n }\n processedArguments += '\"' + arg + '\"';\n }\n mPromises.put(\"\" + promiseId, p);\n queueJavascript(\"bungieNetPlatform.\" + methodName + \"(\" + processedArguments + (!processedArguments.equals(\"\") ? \", \" : \"\") + \"function(data){window.clientHandler.accept(\" + '\"' + promiseId + '\"' + \", JSON.stringify(data))}, function(data){window.clientHandler.error(\\\"\" + promiseId + \"\\\", JSON.stringify(data))})\");\n return p;\n }\n\n private void queueJavascript(final String javascript) {\n mHandler.post(new Runnable() {\n @Override\n public void run() {\n loadUrl(\"javascript:\" + \"window.clientHandler.log(\\\"\\\"+ \" + javascript + \")\");\n }\n });\n }\n\n public void queueRunnable(Runnable r) {\n mHandler.post(r);\n }\n\n public void setCurrentActivity(Activity currentActivity) {\n this.currentActivity = currentActivity;\n }\n\n public interface Callback {\n public void onAccept(String result);\n\n public void onError(String result);\n }\n\n private class JsObject {\n private final Map<String, Promise> mPromises;\n\n public JsObject(Map<String, Promise> promises) {\n mPromises = promises;\n }\n\n @JavascriptInterface\n public void accept(String promiseId, String result) {\n mPromises.get(promiseId).accept(result);\n mPromises.remove(promiseId);\n }\n\n @JavascriptInterface\n public void error(String promiseId, String result) {\n mPromises.get(promiseId).error(result);\n mPromises.remove(promiseId);\n }\n\n @JavascriptInterface\n public boolean log(String data) {\n return true;\n }\n\n public String getString(String value) {\n return value;\n }\n }\n\n public class Promise {\n private Callback mCallback;\n\n public void then(Callback callback) {\n mCallback = callback;\n }\n\n public void accept(String result) {\n mCallback.onAccept(result);\n }\n\n public void error(String result) {\n mCallback.onError(result);\n }\n }\n}", "public class QuantitySelectView extends FrameLayout {\n private static int MIN = 1;\n private TextView mLabel;\n private SeekBar mSeekbar;\n\n static public void getStackValue(Context context, int stackSize, final OnStackSelectInterface onStackSelectInterface) {\n final QuantitySelectView selectView = new QuantitySelectView(context);\n selectView.setMax(stackSize);\n\n new AlertDialog.Builder(context)\n .setTitle(R.string.please_select_a_quantity)\n .setView(selectView)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n onStackSelectInterface.onStackSizeSelect(selectView.getValue());\n }\n })\n .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n }\n })\n .setIcon(android.R.drawable.ic_dialog_info)\n .show();\n }\n\n public QuantitySelectView(Context context) {\n super(context);\n init();\n }\n\n public QuantitySelectView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init();\n }\n\n public QuantitySelectView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init();\n }\n\n private void init() {\n LayoutInflater.from(getContext()).inflate(R.layout.quantyty_select, this, true);\n mLabel = (TextView) findViewById(R.id.quantytySelectLabel);\n mSeekbar = (SeekBar) findViewById(R.id.quantytySelectSeekBar);\n setMax(2);\n mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {\n @Override\n public void onProgressChanged(SeekBar seekBar, int i, boolean b) {\n mLabel.setText(Integer.toString(i + MIN));\n }\n\n @Override\n public void onStartTrackingTouch(SeekBar seekBar) {\n\n }\n\n @Override\n public void onStopTrackingTouch(SeekBar seekBar) {\n\n }\n });\n }\n\n public void setMax(int max) {\n mSeekbar.setMax(max - MIN);\n mSeekbar.setProgress(max - MIN);\n }\n\n public int getValue() {\n return mSeekbar.getProgress() + MIN;\n }\n\n public interface OnStackSelectInterface {\n void onStackSizeSelect(int i);\n }\n}" ]
import android.app.Activity; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.Application; import org.swistowski.vaulthelper.R; import org.swistowski.vaulthelper.storage.Characters; import org.swistowski.vaulthelper.storage.ItemMonitor; import org.swistowski.vaulthelper.storage.Items; import org.swistowski.vaulthelper.storage.Data; import org.swistowski.vaulthelper.storage.Labels; import org.swistowski.vaulthelper.views.ClientWebView; import org.swistowski.vaulthelper.views.QuantitySelectView; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map;
@Override public int compareTo(Item another) { return Ordering.getInstance().doOrder(this, another); //return orderFunctionMap.get(Preferences.getInstance().getOrdering()).doOrder(this, another); } public String[] debugAttrs() { String[] ret = new String[]{}; return ret; } public String toString() { return mName; } public long getItemHash() { return mItemHash; } public int getLocation() { return mLocation; } public String getName() { return mName; } public String getIcon() { return mIcon; } public void setIcon(String icon) { mIcon = icon; } public boolean isVisible() { if (getStackSize() == 0) { return false; } return true; } public String getItemId() { return mItemInstanceId; } public String getDetails() { return mItemDescription; } public void moveTo(String target, int stackSize) { Items.getInstance().changeOwner(this, target, stackSize); } public boolean isEquipped() { return mIsEquipped; } public long getBucketTypeHash() { return mBucketTypeHash; } public void setIsEquipped(boolean isEquipped) { mIsEquipped = isEquipped; } public int getPrimaryStatValue() { return mPrimaryStatValue; } public int getDamageType() { return mDamageType; } public String getDamageTypeName() { if (mDamageType == DAMAGE_TYPE_SOLAR) { return "Solar"; } else if (mDamageType == DAMAGE_TYPE_ARC) { return "Arc"; } else if (mDamageType == DAMAGE_TYPE_VOID) { return "Void"; } return ""; } public int getType() { return mItemType; } public int getStackSize() { return mStackSize; } public String getBucketName() { return mBucketName; } public boolean getIsCompleted() { return mIsGridComplete; } public long getInstanceId() { return Long.valueOf(mItemInstanceId); } public boolean getCanEquip() { return mCanEquip; } public void setCanEquip(boolean canEquip) { mCanEquip = canEquip; } public boolean isMoveable() { return mLocation == LOCATION_INVENTORY || mLocation == LOCATION_VAULT; } private void doMove(final Activity activity, final Item finalItem, final String owner, int stackSize) {
ItemMover.move(((Application) activity.getApplication()).getWebView(), finalItem, owner, stackSize).then(
0
wix/wix-embedded-mysql
wix-embedded-mysql/src/main/java/com/wix/mysql/store/SafeExtractedArtifactStoreBuilder.java
[ "public class DownloadConfig implements AdditionalConfig {\n private final String cacheDir;\n private final String baseUrl;\n private final IProxyFactory proxyFactory;\n\n private DownloadConfig(\n final String cacheDir,\n final String baseUrl,\n final IProxyFactory proxy) {\n this.cacheDir = cacheDir;\n this.baseUrl = baseUrl;\n this.proxyFactory = proxy;\n }\n\n public IProxyFactory getProxyFactory() {\n return proxyFactory;\n }\n\n /**\n * @deprecated in favour of getCacheDir\n */\n @Deprecated\n public String getDownloadCacheDir() {\n return cacheDir;\n }\n\n public String getCacheDir() {\n return cacheDir;\n }\n\n public String getBaseUrl() {\n return baseUrl;\n }\n\n public static Builder aDownloadConfig() {\n return new Builder();\n }\n\n public static class Builder {\n private IProxyFactory proxyFactory = new NoProxyFactory();\n private String cacheDir = new File(System.getProperty(\"user.home\"), \".embedmysql\").getPath();\n private String baseUrl = \"https://dev.mysql.com/get/Downloads/\";\n\n /**\n * Download cache location override that by default is set to '~/.embedmysql'.\n *\n * @deprecated in favor of withCacheDir\n *\n * @param downloadCacheDir custom path\n * @return Builder\n */\n @Deprecated\n public Builder withDownloadCacheDir(String downloadCacheDir) {\n this.cacheDir = downloadCacheDir;\n return this;\n }\n\n /**\n * Download cache location override that by default is set to '~/.embedmysql'.\n *\n * @param cacheDir custom path\n * @return Builder\n */\n public Builder withCacheDir(String cacheDir) {\n this.cacheDir = cacheDir;\n return this;\n }\n\n\n /**\n * base url override that defaults to \"https://dev.mysql.com/get/Downloads\" where actual mysql binary path must conform to\n * what mysql provides (or otherwise is stored in ~/.embedmysql) - ex. https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.18-macos10.12-x86_64.dmg\n *\n * @param baseUrl custom download url\n * @return Builder\n */\n public Builder withBaseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n return this;\n }\n\n public Builder withProxy(final IProxyFactory proxy) {\n this.proxyFactory = proxy;\n return this;\n }\n\n public DownloadConfig build() {\n return new DownloadConfig(cacheDir, baseUrl, proxyFactory);\n\n }\n }\n}", "public class DownloadConfigBuilder extends de.flapdoodle.embed.process.config.store.DownloadConfigBuilder {\n\n public DownloadConfigBuilder defaults(\n final DownloadConfig downloadConfig) {\n fileNaming().setDefault(new UUIDTempNaming());\n downloadPath().setDefault(new DownloadPath(downloadConfig.getBaseUrl()));\n progressListener().setDefault(new ConsoleProgressListener());\n artifactStorePath().setDefault(new FixedPath(downloadConfig.getCacheDir()));\n downloadPrefix().setDefault(new DownloadPrefix(\"embedmysql-download\"));\n userAgent().setDefault(new UserAgent(\"Mozilla/5.0 (compatible; Embedded MySql; +https://github.com/wix/wix-embedded-mysql)\"));\n packageResolver().setDefault(new PackagePaths());\n timeoutConfig().setDefault(new TimeoutConfigBuilder().connectionTimeout(10000).readTimeout(60000).build());\n proxyFactory().setDefault(downloadConfig.getProxyFactory());\n return this;\n }\n}", "public class MysqldConfig extends ExecutableProcessConfig {\n\n private final int port;\n private final Charset charset;\n private final User user;\n private final TimeZone timeZone;\n private final Timeout timeout;\n private final List<ServerVariable> serverVariables;\n private final String tempDir;\n\n protected MysqldConfig(\n final IVersion version,\n final int port,\n final Charset charset,\n final User user,\n final TimeZone timeZone,\n final Timeout timeout,\n final List<ServerVariable> serverVariables,\n final String tempDir) {\n super(version, new ISupportConfig() {\n public String getName() {\n return \"mysqld\";\n }\n\n public String getSupportUrl() {\n return \"https://github.com/wix/wix-embedded-mysql/issues\";\n }\n\n public String messageOnException(Class<?> context, Exception exception) {\n return \"no message\";\n }\n });\n\n if (user.name.equals(\"root\")) {\n throw new IllegalArgumentException(\"Usage of username 'root' is forbidden as it's reserved for system use\");\n }\n\n this.port = port;\n this.charset = charset;\n this.user = user;\n this.timeZone = timeZone;\n this.timeout = timeout;\n this.serverVariables = serverVariables;\n this.tempDir = tempDir;\n }\n\n public Version getVersion() {\n return (Version) version;\n }\n\n public Charset getCharset() {\n return charset;\n }\n\n public int getPort() {\n return port;\n }\n\n public long getTimeout(TimeUnit target) {\n return this.timeout.to(target);\n }\n\n public String getUsername() {\n return user.name;\n }\n\n public String getPassword() {\n return user.password;\n }\n\n public TimeZone getTimeZone() {\n return timeZone;\n }\n\n public List<ServerVariable> getServerVariables() {\n return serverVariables;\n }\n\n public String getTempDir() {\n return tempDir;\n }\n\n public static Builder aMysqldConfig(final Version version) {\n return new Builder(version);\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n\n public static class Builder {\n private IVersion version;\n private int port = 3310;\n private Charset charset = Charset.defaults();\n private User user = new User(\"auser\", \"sa\");\n private TimeZone timeZone = TimeZone.getTimeZone(\"UTC\");\n private Timeout timeout = new Timeout(30, SECONDS);\n private final List<ServerVariable> serverVariables = new ArrayList<>();\n private String tempDir = \"target/\";\n\n public Builder(IVersion version) {\n this.version = version;\n }\n\n public Builder withPort(int port) {\n this.port = port;\n return this;\n }\n\n public Builder withFreePort() throws IOException {\n try (ServerSocket socket = new ServerSocket(0)) {\n socket.setReuseAddress(true);\n return withPort(socket.getLocalPort());\n }\n }\n\n public Builder withTimeout(long length, TimeUnit unit) {\n this.timeout = new Timeout(length, unit);\n return this;\n }\n\n public Builder withCharset(Charset charset) {\n this.charset = charset;\n return this;\n }\n\n public Builder withUser(String username, String password) {\n this.user = new User(username, password);\n return this;\n }\n\n public Builder withTimeZone(TimeZone timeZone) {\n this.timeZone = timeZone;\n return this;\n }\n\n public Builder withTimeZone(String timeZoneId) {\n return withTimeZone(TimeZone.getTimeZone(timeZoneId));\n }\n\n /**\n * Provide mysql server option\n *\n * See <a href=\"mysqld-option-tables\">http://dev.mysql.com/doc/refman/5.7/en/mysqld-option-tables.html</a>\n */\n public Builder withServerVariable(String name, boolean value) {\n serverVariables.add(new ServerVariable<>(name, value));\n return this;\n }\n\n /**\n * Provide mysql server int variable\n *\n * See <a href=\"mysqld-option-tables\">http://dev.mysql.com/doc/refman/5.7/en/mysqld-option-tables.html</a>\n */\n public Builder withServerVariable(String name, int value) {\n serverVariables.add(new ServerVariable<>(name, value));\n return this;\n }\n\n /**\n * Provide mysql server string or enum variable\n *\n * See <a href=\"mysqld-option-tables\">http://dev.mysql.com/doc/refman/5.7/en/mysqld-option-tables.html</a>\n */\n public Builder withServerVariable(String name, String value) {\n serverVariables.add(new ServerVariable<>(name, value));\n return this;\n }\n\n public Builder withTempDir(String tempDir) {\n this.tempDir = tempDir;\n return this;\n }\n\n\n public MysqldConfig build() {\n return new MysqldConfig(version, port, charset, user, timeZone, timeout, serverVariables, tempDir);\n }\n }\n\n private static class User {\n private final String name;\n private final String password;\n\n User(String name, String password) {\n this.name = name;\n this.password = password;\n }\n\n @Override\n public String toString() {\n return ReflectionToStringBuilder.toStringExclude(this, \"password\");\n }\n }\n\n private static class Timeout {\n private final long length;\n private final TimeUnit unit;\n\n Timeout(long length, TimeUnit unit) {\n this.length = length;\n this.unit = unit;\n }\n\n long to(TimeUnit target) {\n return target.convert(length, unit);\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n }\n\n public static class ServerVariable<T> {\n private final String name;\n private final T value;\n\n ServerVariable(final String name, final T value) {\n this.name = name;\n this.value = value;\n }\n\n public String toCommandLineArgument() {\n return String.format(\"--%s=%s\", name, value);\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n }\n\n public static class SystemDefaults {\n public final static String USERNAME = \"root\";\n public final static String SCHEMA = \"information_schema\";\n }\n\n}", "public class TargetGeneratedFixedPath implements IDirectory {\n\n private final String baseDir;\n\n public TargetGeneratedFixedPath(String baseDir) {\n this.baseDir = baseDir;\n }\n\n @Override\n public File asFile() {\n generateNeededDirs();\n return new File(baseDir).getAbsoluteFile();\n }\n\n private void generateNeededDirs() {\n String[] paths;\n\n if (Platform.detect() == Platform.Windows ) {\n paths = new String[]{\"bin\", \"share/english\", \"data/test\", \"data/mysql\", \"data/performance_schema\"};\n } else {\n paths = new String[]{\"bin\", \"scripts\", \"lib/plugin\", \"share/english\", \"share\", \"support-files\"};\n }\n\n for (String dir : paths) {\n new File(baseDir + \"/\" + dir).mkdirs();\n }\n }\n\n @Override\n public boolean isGenerated() {\n return true;\n }\n}", "public class NoopNaming implements ITempNaming {\n\n @Override\n public String nameFor(String prefix, String postfix) {\n return postfix;\n }\n}", "public class PathPrefixingNaming implements ITempNaming {\n\n private final String basePath;\n\n public PathPrefixingNaming(String basePath) {\n this.basePath = basePath;\n }\n\n @Override\n public String nameFor(String prefix, String postfix) {\n return basePath + postfix;\n }\n}" ]
import com.wix.mysql.config.DownloadConfig; import com.wix.mysql.config.DownloadConfigBuilder; import com.wix.mysql.config.MysqldConfig; import com.wix.mysql.config.directories.TargetGeneratedFixedPath; import com.wix.mysql.config.extract.NoopNaming; import com.wix.mysql.config.extract.PathPrefixingNaming; import de.flapdoodle.embed.process.extract.DirectoryAndExecutableNaming; import de.flapdoodle.embed.process.io.directories.FixedPath; import de.flapdoodle.embed.process.io.directories.IDirectory; import de.flapdoodle.embed.process.store.Downloader; import de.flapdoodle.embed.process.store.IArtifactStore; import java.io.File; import java.util.UUID;
package com.wix.mysql.store; public class SafeExtractedArtifactStoreBuilder extends de.flapdoodle.embed.process.store.ExtractedArtifactStoreBuilder { public SafeExtractedArtifactStoreBuilder defaults( final MysqldConfig mysqldConfig, final DownloadConfig downloadConfig) { String tempExtractDir = String.format("mysql-%s-%s", mysqldConfig.getVersion().getMajorVersion(), UUID.randomUUID()); String combinedPath = new File(mysqldConfig.getTempDir(), tempExtractDir).getPath(); IDirectory preExtractDir = new FixedPath(new File(downloadConfig.getCacheDir(), "extracted").getPath()); executableNaming().setDefault(new PathPrefixingNaming("bin/")); download().setDefault(new DownloadConfigBuilder().defaults(downloadConfig).build()); downloader().setDefault(new Downloader()); extractDir().setDefault(preExtractDir); extractExecutableNaming().setDefault(new NoopNaming());
tempDir().setDefault(new TargetGeneratedFixedPath(combinedPath));
3
steeleforge/ironsites
core/src/main/java/com/steeleforge/aem/ironsites/wcm/components/LinkUse.java
[ "public enum WCMConstants {\n INSTANCE;\n public static final String HTTP = \"http\";\n public static final String HTTPS = \"https\";\n public static final String PROTOCOL_RELATIVE = \"//\";\n public static final String DELIMITER_QUERY = \"?\";\n public static final String DELIMITER_FRAGMENT = \"#\";\n public static final String DELIMITER_PORT = \":\";\n public static final String DELIMITER_PATH = \"/\";\n public static final String DELIMITER_PATH_IDENTIFIER = \"--\";\n public static final String DELIMITER_SUFFIX = DELIMITER_PATH;\n public static final String DELIMITER_EXTENSION = \".\";\n public static final String DELIMITER_SELECTOR = DELIMITER_EXTENSION;\n public static final String DELIMITER_COMMA = \",\";\n public static final String DELIMITER_COMMA_SPACED = \",\";\n public static final String DELIMITER_MULTIFIELD = \"|\";\n public static final String PATH_FAVICON = \"/favicon.ico\";\n public static final String HTML = \"html\";\n public static final String HEADER_LOCATION = \"Location\";\n}", "public class WCMURLBuilder {\n private SlingHttpServletRequest request;\n private String url = StringUtils.EMPTY;\n private String path;\n private String selectors;\n private String extension;\n private String suffix;\n private String domain;\n private String protocol;\n private String fragment;\n private String query;\n private boolean extensionSuffix = true;\n private boolean jcrMangle = true;\n private boolean resolverMap = true;\n private boolean sanitize = false;\n private boolean protocolRelative = false;\n \n public WCMURLBuilder(final SlingHttpServletRequest request) {\n super();\n this.request = request;\n }\n \n public String toString() {\n return getUrl();\n }\n \n public String getUrl() {\n if (StringUtils.isBlank(this.url)) {\n build();\n }\n return this.url;\n }\n \n /**\n * @return the url\n */\n public String build() {\n if (isExternal()) {\n this.url = WCMUtil.getExternalURL(this.request, this.path, this.protocol, this.domain);\n if (isProtocolRelative()) {\n this.url = WCMUtil.getProtocolRelativeURL(this.url);\n }\n } else {\n this.url = WCMUtil.getRelativeURL(this.request, \n this.path, \n this.selectors, \n this.extension, \n this.suffix, \n this.extensionSuffix, \n this.jcrMangle, \n this.resolverMap, \n this.sanitize);\n }\n if (StringUtils.isNotBlank(this.fragment)) {\n if (!StringUtils.startsWith(this.fragment, WCMConstants.DELIMITER_FRAGMENT)) {\n this.url += WCMConstants.DELIMITER_FRAGMENT;\n }\n this.url += fragment;\n }\n\n if (StringUtils.isNotBlank(this.query)) {\n this.url += WCMConstants.DELIMITER_QUERY + WCMUtil.getURLEncoded(query);\n }\n return this.url;\n }\n\n /**\n * @return the path\n */\n public String getPath() {\n return path;\n }\n\n /**\n * @param path the path to set\n */\n public WCMURLBuilder setPath(String path) {\n this.path = path;\n return this;\n }\n\n /**\n * @return the selectors\n */\n public String getSelectors() {\n return selectors;\n }\n\n /**\n * @param selectors the selectors to set\n */\n public WCMURLBuilder setSelectors(String selectors) {\n this.selectors = selectors;\n return this;\n }\n\n /**\n * @return the extension\n */\n public String getExtension() {\n return extension;\n }\n\n /**\n * @param extension the extension to set\n */\n public WCMURLBuilder setExtension(String extension) {\n this.extension = extension;\n return this;\n }\n\n /**\n * @return the suffix\n */\n public String getSuffix() {\n return suffix;\n }\n\n /**\n * @param suffix the suffix to set\n */\n public WCMURLBuilder setSuffix(String suffix) {\n this.suffix = suffix;\n return this;\n }\n\n /**\n * @return the domain\n */\n public String getDomain() {\n return domain;\n }\n\n /**\n * @param domain the domain to set\n */\n public WCMURLBuilder setDomain(String domain) {\n this.domain = domain;\n return this;\n }\n\n /**\n * @return the protocol\n */\n public String getProtocol() {\n return protocol;\n }\n\n /**\n * @param protocol the protocol to set\n */\n public void setProtocol(String protocol) {\n this.protocol = protocol;\n }\n\n /**\n * @return the fragment\n */\n public String getFragment() {\n return fragment;\n }\n\n /**\n * @param fragment the fragment to set\n */\n public WCMURLBuilder setFragment(String fragment) {\n this.fragment = fragment;\n return this;\n }\n\n /**\n * @return the query string\n */\n public String getQuery() {\n return query;\n }\n\n /**\n * @param query the querystring to set\n */\n public WCMURLBuilder setQuery(String query) {\n this.query = query;\n return this;\n }\n\n /**\n * @return the extensionSuffix\n */\n public boolean isExtensionSuffix() {\n return extensionSuffix;\n }\n\n /**\n * @param extensionSuffix the extensionSuffix to set\n */\n public WCMURLBuilder setExtensionSuffix(boolean extensionSuffix) {\n this.extensionSuffix = extensionSuffix;\n return this;\n }\n\n /**\n * @param extensionSuffix the extensionSuffix to set\n */\n public WCMURLBuilder isExtensionSuffix(boolean extensionSuffix) {\n return setExtensionSuffix(extensionSuffix);\n }\n\n /**\n * @return the jcrMangle\n */\n public boolean isJcrMangle() {\n return jcrMangle;\n }\n\n /**\n * @param jcrMangle the jcrMangle to set\n */\n public WCMURLBuilder setJcrMangle(boolean jcrMangle) {\n this.jcrMangle = jcrMangle;\n return this;\n }\n \n /**\n * @param jcrMangle the jcrMangle to set\n */\n public WCMURLBuilder isJcrMangle(boolean jcrMangle) {\n return setJcrMangle(jcrMangle);\n }\n\n /**\n * @return the resolverMap\n */\n public boolean isResolverMap() {\n return resolverMap;\n }\n\n /**\n * @param resolverMap the resolverMap to set\n */\n public WCMURLBuilder setResolverMap(boolean resolverMap) {\n this.resolverMap = resolverMap;\n return this;\n }\n\n /**\n * @param resolverMap the resolverMap to set\n */\n public WCMURLBuilder isResolverMap(boolean resolverMap) {\n return setResolverMap(resolverMap);\n }\n\n\n /**\n * @return the sanitize\n */\n public boolean isSanitize() {\n return sanitize;\n }\n\n /**\n * @param sanitize the sanitize to set\n */\n public WCMURLBuilder setSanitize(boolean sanitize) {\n this.sanitize = sanitize;\n return this;\n }\n\n /**\n * @param sanitize the sanitize to set\n */\n public WCMURLBuilder isSanitize(boolean sanitize) {\n return setSanitize(sanitize);\n }\n \n /**\n * @return the external\n */\n public boolean isExternal() {\n return StringUtils.isNotBlank(domain);\n }\n\n /**\n * @param domain the externalizer domain to set\n */\n public WCMURLBuilder isExternal(String domain) {\n this.domain = domain;\n return this;\n }\n\n /**\n * @return the protocolRelative\n */\n public boolean isProtocolRelative() {\n return protocolRelative;\n }\n\n /**\n * @param protocolRelative the protocolRelative to set\n */\n public WCMURLBuilder setProtocolRelative(boolean protocolRelative) {\n this.protocolRelative = protocolRelative;\n return this;\n }\n\n /**\n * @param protocolRelative the protocolRelative to set\n */\n public WCMURLBuilder isProtocolRelative(boolean protocolRelative) {\n return isProtocolRelative(protocolRelative);\n }\n}", "public enum WCMUtil {\n INSTANCE;\n private static final Logger LOG = LoggerFactory.getLogger(WCMUtil.class);\n \n /**\n * Utility method to extract sling request from JSP page context\n * \n * @param pageContext\n * @return SlingHttpServletRequest instance\n */\n public static SlingHttpServletRequest getSlingRequest(final PageContext pageContext) {\n return TagUtil.getRequest(pageContext);\n }\n \n /**\n * Utility method to extract sling script helper from SlingHttpServletRequest\n * \n * @param request\n * @return SlingScriptHelper instance\n */\n public static SlingScriptHelper getSlingScriptHelper(final SlingHttpServletRequest request) {\n SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());\n return bindings.getSling();\n }\n \n /**\n * Utility method to extract sling script helper from JSP page context\n * \n * @param pageContext\n * @return SlingScriptHelper instance\n */\n public static SlingScriptHelper getSlingScriptHelper(final PageContext pageContext) {\n SlingHttpServletRequest request = getSlingRequest(pageContext);\n return getSlingScriptHelper(request);\n }\n\n /**\n * Given a class and sling request, return an OSGi service\n * @param request\n * @param clazz\n * @return\n */\n public static <T> T getService(final SlingHttpServletRequest request, final Class<T> clazz) {\n return getSlingScriptHelper(request).getService(clazz);\n }\n \n /**\n * Given a class and PageContext, return an OSGi service\n * @param pageContext\n * @param clazz\n * @return\n */\n public static <T> T getService(final PageContext pageContext, final Class<T> clazz) {\n return getService(getSlingRequest(pageContext), clazz);\n }\n \n /**\n * General purpose hashing for Strings such as node path.\n * \n * @param token String to hash\n * @param minimumLength minimum length of hash\n * @return hashed value\n * @see <a href=\"http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/hash/HashCode.html\">HashCode</a>\n */\n public static String getFastHash(final String token, final int minimumLength) {\n HashFunction hf = Hashing.goodFastHash(minimumLength);\n HashCode hc = hf.newHasher()\n .putString(token, Charsets.UTF_8)\n .hash();\n return hc.toString();\n }\n \n /**\n * General purpose hashing for Strings such as node path. \n * Defaults to minimum length of 5.\n * \n * @param token String to hash\n * @see WCMUtil#getFastHash(String, int)\n */\n public static String getFastHash(final String token) {\n return getFastHash(token, 5);\n }\n \n /**\n * URL encode a given String, per a given encoding\n * \n * @param token\n * @param encoding, default to UTF-8\n * @return URL encoded String\n */\n public static String getURLEncoded(final String token, final String encoding) {\n if (StringUtils.isNotEmpty(token)) {\n try {\n if (StringUtils.isNotEmpty(encoding)) {\n return URLEncoder.encode(token, encoding);\n }\n return URLEncoder.encode(token, CharEncoding.UTF_8);\n } catch(UnsupportedEncodingException uee) {\n LOG.debug(uee.getMessage());\n }\n }\n return token;\n }\n\n\n /**\n * URL encode a given String, assuming UTF-8\n * \n * @param token\n * @return URL encoded String\n */\n public static String getURLEncoded(final String token) {\n return getURLEncoded(token, CharEncoding.UTF_8);\n }\n \n /**\n * Retrieve AEM Page from PageManager based on path\n * \n * @param request\n * @param path\n * @return Page, null if request or path are empty, or if path doesn't resolve\n */\n public static Page getPage(final SlingHttpServletRequest request, final String path) {\n Page page = null;\n if (null == request) {\n return page;\n }\n ResourceResolver resolver = request.getResourceResolver();\n if (StringUtils.startsWith(path, \"/\") && null != resolver) {\n PageManager pageManager = resolver.adaptTo(PageManager.class);\n page = pageManager.getContainingPage(path);\n pageManager = null;\n }\n return page;\n }\n\n /**\n * Retrieve AEM Page from Sling Request\n * \n * @param request\n * @return Page, null if request is null\n */\n public static Page getPage(final SlingHttpServletRequest request) {\n Page page = null;\n if (null != request) {\n page = getPage(request, request.getResource().getPath());\n }\n return page;\n }\n \n /**\n * If page title is null, use navigation title. If that is null, use name.\n * \n * @param page\n * @return page title, nav title, or null\n */\n public static String getPageTitle(final Page page) {\n String title = null;\n if (null != page) {\n if (null != page.getPageTitle()) {\n title = page.getPageTitle();\n } else if (null != page.getTitle()) {\n title = page.getTitle();\n } else if (null != page.getNavigationTitle()) {\n title = page.getNavigationTitle();\n } else {\n title = page.getName();\n }\n }\n return title;\n }\n\n /**\n * If page navigation is null, use page title. If that is null, use name.\n * \n * @param page\n * @return nav title, page title, or null\n */\n public static String getPageNavigationTitle(final Page page) {\n String title = null;\n if (null != page) {\n if (null != page.getNavigationTitle()) {\n title = page.getNavigationTitle();\n }\n title = getPageTitle(page);\n }\n return title;\n }\n\n /**\n * Based on a given resource path, extract locale/language level\n * agnostic to a AEM Launches based path\n * \n * @param path\n * @return locale level resource path\n */\n public static String getLanguageRoot(final String path) {\n return LaunchUtils.getProductionResourcePath(LanguageUtil\n .getLanguageRoot(path));\n }\n /**\n * Attempt to acquire a locale based on the requested resource.\n * \n * @param request\n * @return\n */\n public static Locale getLocale(final SlingHttpServletRequest request) {\n PageManager pageManager = (PageManager)request.getResourceResolver().adaptTo(PageManager.class);\n if (null == pageManager) {\n return Locale.getDefault();\n }\n Page page = pageManager.getContainingPage(request.getResource());\n return page.getLanguage(false);\n }\n \n /**\n * JCR Manlged path (i.e. jcr:content to _jcr_content)\n * \n * @param path\n * @return\n */\n public static String getMangledPath(final String path) {\n if (StringUtils.isBlank(path)) {\n return path;\n }\n return path.replaceAll(\"\\\\/(\\\\w+):(\\\\w+)\", \"/_$1_$2\");\n }\n \n /**\n * Avoids repeat delimiters\n * \n * @param token\n * @param delimiter\n * @return\n */\n public static String getDelimitered(final String token, final String delimiter) {\n if (StringUtils.isNotBlank(token) && !StringUtils.startsWith(token, delimiter)) {\n return delimiter + token;\n }\n return token;\n }\n \n \n /**\n * Given a relative path, this method can resolve mappings, append suffix\n * mangle JCR paths, XSS cleanse, append selectors, and apply extension(s).\n * \n * @param request\n * @param path\n * @param selectors\n * @param extension\n * @param suffix\n * @param extensionSuffix\n * @param jcrMangle\n * @param resolverMap\n * @param sanitize\n * @return\n */\n public static String getRelativeURL(final SlingHttpServletRequest request, \n final String path,\n final String selectors, \n final String extension, \n final String suffix,\n final boolean extensionSuffix,\n final boolean jcrMangle, \n final boolean resolverMap,\n final boolean sanitize) {\n String href = path;\n SlingScriptHelper sling = WCMUtil.getSlingScriptHelper(request);\n ResourceResolver resolver = request.getResourceResolver();\n \n // fail fast if path input doesn't appear to be relative\n // nor internal\n if (!StringUtils.startsWith(path, \"/\") || null == resolver.resolve(path)) {\n return href;\n }\n \n // check for resolver mapping if requested as parameter\n href = (resolverMap) ? resolver.map(path) : path;\n // mangle sling resource paths if necessary (e.g. jcr:content -> _jcr:content))\n if (jcrMangle) {\n href = getMangledPath(href);\n }\n StringBuilder sb = new StringBuilder(href);\n \n // selectors, if provided\n if (StringUtils.isNotBlank(selectors)) {\n sb.append(getDelimitered(selectors, WCMConstants.DELIMITER_SELECTOR));\n }\n \n // base resource path extension is presumably \".html\" by default\n String ext = (StringUtils.isNotBlank(extension)) ? extension\n : WCMConstants.HTML;\n sb.append(getDelimitered(ext, \n WCMConstants.DELIMITER_EXTENSION));\n \n // suffix (and extension) if provided\n if (StringUtils.isNotBlank(suffix)) {\n sb.append(getDelimitered(suffix, WCMConstants.DELIMITER_SUFFIX));\n if (extensionSuffix) {\n sb.append(ext);\n }\n }\n href = sb.toString();\n if (sanitize) {\n XSSAPI xss = (XSSAPI) sling.getService(XSSAPI.class);\n xss = xss.getRequestSpecificAPI(request);\n return xss.getValidHref(href);\n }\n return href;\n }\n \n /**\n * Use of AEM Externalizer service to product fully qualified URLs \n * including protocol specification and environment specific domains\n * \n * @param request\n * @param path relative path\n * @param protocol http/https\n * @param domain domain or Externalizer profile\n * @param sanitize with XSS API\n * @return fully qualified URL\n */\n public static String getExternalURL(final SlingHttpServletRequest request,\n final String relativePath,\n final String protocol,\n final String domain,\n final boolean sanitize) {\n String href = relativePath;\n SlingScriptHelper sling = getSlingScriptHelper(request);\n ResourceResolver resolver = request.getResourceResolver();\n \n Externalizer externalizer = sling.getService(Externalizer.class);\n if (StringUtils.isNotBlank(protocol)) {\n href = externalizer.externalLink(resolver, domain, protocol, relativePath);\n } else {\n href = externalizer.externalLink(resolver, domain, relativePath);\n }\n // relative path may already be sanitized through xss\n if (sanitize) {\n XSSAPI xss = (XSSAPI) sling.getService(XSSAPI.class);\n xss = xss.getRequestSpecificAPI(request);\n return xss.getValidHref(href);\n }\n return href;\n }\n \n /**\n * Use of AEM Externalizer service to product fully qualified URLs \n * including protocol specification and environment specific domains\n * \n * @param request\n * @param path relative path\n * @param protocol http/https\n * @param domain domain:port or Externalizer profile, both with port\n * @return fully qualified URL\n */\n public static String getExternalURL(final SlingHttpServletRequest request,\n final String relativePath,\n final String protocol,\n final String domain) {\n return getExternalURL(request, relativePath, protocol, domain, true);\n }\n\n \n /**\n * Most sling resource hrefs will not need suffixes, additional reasonable\n * default parameters are assumed for getRelativeURL\n * \n * @param request\n * @param path\n * @param selectors\n * @param extension\n * @return\n */\n public static String getResourceURL(final SlingHttpServletRequest request, \n final String path,\n final String selectors, \n final String extension) {\n return getRelativeURL(request, path, selectors, extension, null, true, true, true, true);\n }\n \n /**\n * Utility for common case for externalized resource paths\n * \n * @param request\n * \n * @param protocol\n * @param domain\n * @param path\n * @return\n */\n public static String getExternalResourceURL(final SlingHttpServletRequest request, \n final String path,\n final String protocol,\n final String domain,\n final String selectors,\n final String extension) {\n return getExternalURL(request, \n getResourceURL(request, path, selectors, extension), \n protocol, \n domain, \n true);\n }\n \n /**\n * Most CQ Page hrefs will not need suffixes, additional reasonable\n * default parameters are assumed for getRelativeURL\n * \n * @param request\n * @param path\n * @param selectors\n * @param extension\n * @return\n */\n public static String getPageURL(final SlingHttpServletRequest request, \n final String path) {\n Page page = getPage(request, path);\n if (null == page) {\n return path;\n }\n return getRelativeURL(request, \n page.getPath(), \n null, WCMConstants.HTML, null, true, true, true, true);\n }\n \n /**\n * Utility for common case for externalized page paths\n * \n * @param request\n * @param protocol\n * @param domain\n * @param path\n * @return\n */\n public static String getExternalPageURL(final SlingHttpServletRequest request, \n final String path,\n final String protocol,\n final String domain) {\n return getExternalURL(request, \n getPageURL(request, path), \n protocol, \n domain, \n true);\n }\n\n /**\n * For non HTTPS fully qualified URLs, ensure HTTPS\n * \n * @param fullyQualifiedURL\n * @return\n */\n public static String getSecureURL(final String fullyQualifiedURL) {\n if (!StringUtils.startsWith(fullyQualifiedURL, WCMConstants.HTTPS)) {\n return WCMConstants.HTTPS + WCMConstants.DELIMITER_PORT + \n StringUtils.substringAfter(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE);\n }\n return fullyQualifiedURL;\n }\n \n /**\n * For protocol specific fully qualified URLs, ensure protocol relativity\n * \n * @param fullyQualifiedURL\n * @return\n */\n public static String getProtocolRelativeURL(final String fullyQualifiedURL) {\n if (!StringUtils.startsWith(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE)) {\n return WCMConstants.PROTOCOL_RELATIVE + StringUtils.substringAfter(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE);\n }\n return fullyQualifiedURL;\n }\n \n /** \n * Generate mangled path based identifier replacing \"/\" for WCMConstants.DELIMITER_PATH_IDENTIFIER\n * \n * @param path\n * @return identifier\n */\n public static String getPathBasedIdentifier(final String path) {\n String mangled = getMangledPath(path);\n if (StringUtils.isBlank(mangled)) {\n return mangled;\n }\n return StringUtils.replace(mangled, WCMConstants.DELIMITER_PATH, WCMConstants.DELIMITER_PATH_IDENTIFIER); \n }\n}", "public class HidePageFilter extends AndPageFilter {\n public static final String DEFAULT_HIDE_PROPERTY = \"hideInNav\";\n private boolean includeInvalid;\n private boolean includeHidden;\n private String property = DEFAULT_HIDE_PROPERTY;\n \n public static final BooleanEqualsFilter PAGE_NOT_HIDDEN_FILTER = new BooleanEqualsFilter(DEFAULT_HIDE_PROPERTY, Boolean.TRUE, Boolean.TRUE);\n public static final HidePageFilter HIDE_IN_NAVIGATION_FILTER = new HidePageFilter(DEFAULT_HIDE_PROPERTY);\n \n public HidePageFilter(boolean includeInvalid, boolean includeHidden, String property) {\n super(null);\n this.includeInvalid = includeInvalid;\n this.includeHidden = includeHidden;\n this.property = property;\n \n if (!this.includeInvalid) {\n addFilter(InvalidPageFilter.INVALID_PAGE_FILTER);\n }\n if (!this.includeHidden) {\n if (StringUtils.isBlank(property)) {\n addFilter(PAGE_NOT_HIDDEN_FILTER);\n } else {\n addFilter(new BooleanEqualsFilter(this.property, Boolean.TRUE, Boolean.TRUE));\n }\n }\n }\n\n public HidePageFilter(String property) {\n this(false, false, property);\n }\n}", "public class InvalidPageFilter implements Filter<Page> {\n public static final InvalidPageFilter INVALID_PAGE_FILTER = new InvalidPageFilter();\n public boolean includes(Page page) {\n if (null == page) {\n return false;\n }\n return page.isValid();\n }\n}" ]
import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import com.adobe.cq.sightly.WCMUse; import com.day.cq.wcm.api.Page; import com.steeleforge.aem.ironsites.wcm.WCMConstants; import com.steeleforge.aem.ironsites.wcm.WCMURLBuilder; import com.steeleforge.aem.ironsites.wcm.WCMUtil; import com.steeleforge.aem.ironsites.wcm.page.filter.HidePageFilter; import com.steeleforge.aem.ironsites.wcm.page.filter.InvalidPageFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List;
/** * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org/> */ package com.steeleforge.aem.ironsites.wcm.components; public class LinkUse extends WCMUse { // statics public static final String PN_PATH = "path"; public static final String PN_TEXT = "text"; public static final String PN_NAVTITLE = "navTitle"; public static final String PN_HIDEINNAV = "hideInNav"; // local private String path; private Link link; private Page page; private Boolean navTitle = false; private Boolean hideInNav = true; private String id; private String href; private String name; private String styles; private String target; private String rel; private String download; private String media; private String hreflang; private String type; private Boolean ping; private String text; @Override public void activate() throws Exception { path = get(PN_PATH, String.class); if (null == path) path = getProperties().get(PN_PATH, String.class); page = WCMUtil.getPage(getRequest(), path); navTitle = get(PN_NAVTITLE, Boolean.class); navTitle = (null == navTitle)? false : true; hideInNav = get(PN_HIDEINNAV, Boolean.class); hideInNav = (null == hideInNav)? true : false; id = get(Link.PN_ID, String.class); href = get(Link.PN_HREF, String.class); name = get(Link.PN_NAME, String.class); styles = get(Link.PN_STYLES, String.class); target = get(Link.PN_TARGET, String.class); rel = get(Link.PN_REL, String.class); download = get(Link.PN_DOWNLOAD, String.class); media = get(Link.PN_MEDIA, String.class); hreflang = get(Link.PN_HREFLANG, String.class); type = get(Link.PN_TYPE, String.class); ping = get(Link.PN_PING, Boolean.class); text = get(Link.PN_TEXT, String.class); if (null == text) text = getProperties().get(PN_TEXT, String.class); link = setLink(); } private Link setLink() { link = (null != page)? new Link(getRequest(), page) : new Link(); if (null != page) { link.setPage(page.getPath()); if (getCurrentPage().getPath().equals(page.getPath())) { link.setCurrent(true); } if (StringUtils.startsWith(getCurrentPage().getPath(), page.getPath() + WCMConstants.DELIMITER_PATH)) { link.setDescendent(true); } if (navTitle) { text = WCMUtil.getPageNavigationTitle(page); } else { text = WCMUtil.getPageTitle(page); } } else { final String[] pathTokens = StringUtils.split(path, WCMConstants.DELIMITER_MULTIFIELD); if (ArrayUtils.getLength(pathTokens) > 1) { // <path>|<title> path = pathTokens[0]; if (StringUtils.isBlank(text)) text = pathTokens[1]; } else { text = path; } } link.setText(text); path = new WCMURLBuilder(getRequest()).setPath(path).build(); link.setHref(path); if (null != id) link.setId(id); if (null != href) link.setHref(href); if (null != name) link.setName(name); if (null != styles) link.setStyles(styles); if (null != target) link.setTarget(target); if (null != rel) link.setRel(rel); if (null != download) link.setDownload(download); if (null != media) link.setMedia(media); if (null != hreflang) link.setHreflang(hreflang); if (null != type) link.setType(type); if (null != ping) link.setPing(ping); return link; } public Link getLink() { return link; } public List<Link> getLinks() { if (null != page) { List<Link> links = new ArrayList<Link>(); Iterator<Page> children = (hideInNav)?
page.listChildren(HidePageFilter.HIDE_IN_NAVIGATION_FILTER)
3
JoeSteven/BiBi
app/src/main/java/com/joe/bibi/activity/DebateActivity.java
[ "public class BBApplication extends Application{\n public static BBApplication mInstance;\n\n public List<BmobChatUser> getContactList() {\n return ContactList;\n }\n\n public void setContactList(List<BmobChatUser> contactList) {\n ContactList = contactList;\n }\n\n public List<BmobChatUser> ContactList;\n\n public boolean isCommentAllowed;\n public boolean isVoiceAllowed;\n public boolean isVibrateAllowed;\n public boolean isMessageAllowed;\n @Override\n public void onCreate() {\n super.onCreate();\n x.Ext.init(this);\n x.Ext.setDebug(true);\n initBmob();\n mInstance=this;\n isCommentAllowed=PrefUtils.getBoolean(this, ConsUtils.IS_COMMENT_ALLOWED,true);\n isVoiceAllowed=PrefUtils.getBoolean(this, ConsUtils.IS_VOICE_ALLOWED, true);\n isVibrateAllowed=PrefUtils.getBoolean(this, ConsUtils.IS_VIBRATE_ALLOWED,true);\n isMessageAllowed=PrefUtils.getBoolean(this, ConsUtils.IS_MESSAGE_ALLOWED,true);\n BmobUserManager.getInstance(this).queryCurrentContactList(new FindListener<BmobChatUser>() {\n @Override\n public void onSuccess(List<BmobChatUser> list) {\n setContactList(list);\n }\n\n @Override\n public void onError(int i, String s) {\n setContactList(new ArrayList<BmobChatUser>());\n }\n });\n }\n private void initBmob() {\n BmobChat.DEBUG_MODE = true;\n //BmobIM SDK初始化--只需要这一段代码即可完成初始化\n BmobChat.getInstance(this).init(ConsUtils.APPLICATION_ID);\n // 使用推送服务时的初始化操作\n BmobInstallation.getCurrentInstallation(this).save();\n // 启动推送服务\n BmobChat.DEBUG_MODE = true;\n //BmobIM SDK初始化--只需要这一段代码即可完成初始化\n BmobChat.getInstance(this).init(ConsUtils.APPLICATION_ID);\n }\n public static BBApplication getInstance(){\n return mInstance;\n }\n\n public void updateContactList(){\n BmobUserManager.getInstance(this).queryCurrentContactList(new FindListener<BmobChatUser>() {\n @Override\n public void onSuccess(List<BmobChatUser> list) {\n setContactList(list);\n }\n\n @Override\n public void onError(int i, String s) {\n\n }\n });\n }\n\n public void addContactList(List<BmobChatUser> user){\n ContactList.addAll(user);\n }\n}", "public class BBUser extends BmobChatUser implements Serializable{\n private String Desc;//简介\n private String Tag;//标签\n private String AvatarName;\n private String AvatarUrl;\n\n public String getAvatarUrl() {\n return AvatarUrl;\n }\n\n public void setAvatarUrl(String avatarUrl) {\n AvatarUrl = avatarUrl;\n }\n\n public String getAvatarName() {\n return AvatarName;\n }\n\n public void setAvatarName(String avatarName) {\n AvatarName = avatarName;\n }\n\n public String getTag() {\n return Tag;\n }\n\n public void setTag(String tag) {\n Tag = tag;\n }\n\n public String getDesc() {\n return Desc;\n }\n\n public void setDesc(String desc) {\n Desc = desc;\n }\n\n\n}", "public class Comment extends BmobObject implements Serializable{\n private String BelongTo;//属于哪个话题\n private String Content;//评论内容\n private String UserName;//评论人的用户名\n private String Avatar;//评论人头像\n private String Nick;//评论人的昵称\n private Integer Like;//评论的赞同数\n private Integer UnLike;//评论的差评数\n private Integer Point;//评论所支持的观点 三种 正方,反方 中立\n private String Title;\n\n public String getTitle() {\n return Title;\n }\n\n public void setTitle(String title) {\n Title = title;\n }\n\n public static final int POSITIVE_COMMENT=0;\n public static final int NEGATIVE_COMMENT=2;\n public static final int NEUTRAL_COMMENT=1;\n\n public String getBelongTo() {\n return BelongTo;\n }\n\n public void setBelongTo(String belongTo) {\n BelongTo = belongTo;\n }\n\n public String getContent() {\n return Content;\n }\n\n public void setContent(String content) {\n Content = content;\n }\n\n public String getUserName() {\n return UserName;\n }\n\n public void setUserName(String userName) {\n UserName = userName;\n }\n\n public String getAvatar() {\n return Avatar;\n }\n\n public void setAvatar(String avatar) {\n Avatar = avatar;\n }\n\n public String getNick() {\n return Nick;\n }\n\n public void setNick(String nick) {\n Nick = nick;\n }\n\n public Integer getLike() {\n return Like;\n }\n\n public void setLike(Integer like) {\n Like = like;\n }\n\n public Integer getUnLike() {\n return UnLike;\n }\n\n public void setUnLike(Integer unLike) {\n UnLike = unLike;\n }\n\n public Integer getPoint() {\n return Point;\n }\n\n public void setPoint(Integer point) {\n Point = point;\n }\n}", "public class Debate extends BmobObject implements Serializable{\n private String publisher;\n private String title;\n private String desc;\n private Integer positive;\n private Integer negative;\n private Integer total;\n private String image;\n private String avatar;\n private String positiveop;\n private String negativeop;\n private Integer comment;\n\n public Integer getComment() {\n return comment;\n }\n\n public void setComment(Integer comment) {\n this.comment = comment;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public String getPositiveop() {\n return positiveop;\n }\n\n public void setPositiveop(String positiveop) {\n this.positiveop = positiveop;\n }\n\n public String getNegativeop() {\n return negativeop;\n }\n\n public void setNegativeop(String negativeop) {\n this.negativeop = negativeop;\n }\n\n public String getPublisher() {\n return publisher;\n }\n\n public void setPublisher(String publisher) {\n this.publisher = publisher;\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 getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n public Integer getPositive() {\n return positive;\n }\n\n public void setPositive(Integer positive) {\n this.positive = positive;\n }\n\n public Integer getNegative() {\n return negative;\n }\n\n public void setNegative(Integer negative) {\n this.negative = negative;\n }\n\n public Integer getTotal() {\n return total;\n }\n\n public void setTotal(Integer total) {\n this.total = total;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n}", "public class Follow extends BmobObject {\n private String followerId;\n private String debateId;\n private String followerUserName;\n private String followerInstallationId;\n\n public String getFollowerInstallationId() {\n return followerInstallationId;\n }\n\n public void setFollowerInstallationId(String followerInstallationId) {\n this.followerInstallationId = followerInstallationId;\n }\n\n public String getFollowerUserName() {\n return followerUserName;\n }\n\n public void setFollowerUserName(String followerUserName) {\n this.followerUserName = followerUserName;\n }\n\n public String getFollowerId() {\n return followerId;\n }\n\n public void setFollowerId(String followerId) {\n this.followerId = followerId;\n }\n\n public String getDebateId() {\n return debateId;\n }\n\n public void setDebateId(String debateId) {\n this.debateId = debateId;\n }\n}", "public class AnimUtils {\n\n public static TranslateAnimation TaAnimSelf(float fromX,float toX,float fromY,float toY,long duration,boolean fillafter){\n TranslateAnimation ta=new TranslateAnimation(Animation.RELATIVE_TO_SELF,fromX,Animation.RELATIVE_TO_SELF,toX,\n Animation.RELATIVE_TO_SELF,fromY,Animation.RELATIVE_TO_SELF,toY);\n if(duration!=0){\n ta.setDuration(duration);\n }else{\n ta.setDuration(500);\n }\n ta.setFillAfter(fillafter);\n return ta;\n }\n\n public static RotateAnimation RoAnimSelf(float fromDegree,float toDegree,long duration,boolean fillafter){\n RotateAnimation sa=new RotateAnimation(fromDegree,toDegree,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);\n if(duration!=0){\n sa.setDuration(duration);\n }else{\n sa.setDuration(500);\n }\n sa.setFillAfter(fillafter);\n return sa;\n }\n}", "public class PrefUtils {\n\tprivate static SharedPreferences mPref;\n\n\t//记录布尔类型\n\tpublic static void putBoolean(Context context,String key,Boolean value){\n\t\tmPref = context.getSharedPreferences(ConsUtils.SHARED_CONFIG, Context.MODE_PRIVATE);\n\t\tmPref.edit().putBoolean(key, value).commit();\n\t}\n\tpublic static Boolean getBoolean(Context context,String key,Boolean defValue){\n\t\tmPref = context.getSharedPreferences(ConsUtils.SHARED_CONFIG, Context.MODE_PRIVATE);\n\t\treturn mPref.getBoolean(key, defValue);\n\t}\n\tpublic static void putString(Context context,String key,String value){\n\t\tmPref = context.getSharedPreferences(ConsUtils.SHARED_CONFIG, Context.MODE_PRIVATE);\n\t\tmPref.edit().putString(key, value).commit();\n\t}\n\t//记录String类型\n\tpublic static String getString(Context context,String key,String defValue){\n\t\tmPref = context.getSharedPreferences(ConsUtils.SHARED_CONFIG, Context.MODE_PRIVATE);\n\t\treturn mPref.getString(key, defValue);\n\t}\n\n\tpublic static void putInt(Context context,String key,int value){\n\t\tmPref = context.getSharedPreferences(ConsUtils.SHARED_CONFIG, Context.MODE_PRIVATE);\n\t\tmPref.edit().putInt(key, value).commit();\n\t}\n\t//记录int类型\n\tpublic static int getInt(Context context,String key,int defValue){\n\t\tmPref = context.getSharedPreferences(ConsUtils.SHARED_CONFIG, Context.MODE_PRIVATE);\n\t\treturn mPref.getInt(key, defValue);\n\t}\n}", "public class ToastUtils {\n public static void make(Context context,String msg){\n Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();\n }\n}", "public class PullUpListView extends ListView implements AbsListView.OnScrollListener{\n\n private View mFooter;\n private int mFooterViewHeight;\n\n public PullUpListView(Context context) {\n super(context);\n initFootView();\n }\n\n public PullUpListView(Context context, AttributeSet attrs) {\n super(context, attrs);\n initFootView();\n }\n\n public PullUpListView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initFootView();\n }\n\n private void initFootView() {\n mFooter = View.inflate(getContext(), R.layout.footer_more_listview, null);\n mFooter.measure(0, 0);\n mFooterViewHeight = mFooter.getMeasuredHeight();\n\n mFooter.setPadding(0, -mFooterViewHeight, 0, 0);// 隐藏\n this.addFooterView(mFooter);\n this.setOnScrollListener(this);\n }\n public boolean isLoadingMore;\n @Override\n public void onScrollStateChanged(AbsListView view, int scrollState) {\n if (scrollState == SCROLL_STATE_IDLE\n || scrollState == SCROLL_STATE_FLING) {\n if (getLastVisiblePosition() == getCount() - 1 && !isLoadingMore) {\n mFooter.setPadding(0,0,0,0);\n setSelection(getCount() - 1);// 改变listview显示位置\n\n isLoadingMore = true;\n if (mListener != null) {\n mListener.onLoadMore();\n }\n }\n\n }\n }\n\n @Override\n public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {\n }\n\n OnRefreshListener mListener;\n public void setOnRefreshListener(OnRefreshListener listener) {\n mListener = listener;\n }\n\n public interface OnRefreshListener {\n public void onLoadMore();// 加载下一页数据\n }\n\n public void LoadingDone(){\n if (isLoadingMore) {// 正在加载更多...\n mFooter.setPadding(0, -mFooterViewHeight, 0, 0);// 隐藏脚布局\n isLoadingMore = false;\n }\n }\n}" ]
import android.animation.Animator; import android.animation.ObjectAnimator; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.github.siyamed.shapeimageview.CircularImageView; import com.joe.bibi.R; import com.joe.bibi.application.BBApplication; import com.joe.bibi.domain.BBUser; import com.joe.bibi.domain.Comment; import com.joe.bibi.domain.Debate; import com.joe.bibi.domain.Follow; import com.joe.bibi.utils.AnimUtils; import com.joe.bibi.utils.ConsUtils; import com.joe.bibi.utils.PrefUtils; import com.joe.bibi.utils.ToastUtils; import com.joe.bibi.view.PullUpListView; import org.xutils.x; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobUser; import cn.bmob.v3.listener.DeleteListener; import cn.bmob.v3.listener.FindListener; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener;
package com.joe.bibi.activity; public class DebateActivity extends AppCompatActivity { private static final int SHOW_CURRENT_VS = 0; private static final int POS_PLUS = 1; private static final int NEG_PLUS = 2; private boolean isFabOn; private FloatingActionButton fabComment; private FloatingActionButton fabFollow;
private Debate mDebate;
3
jeffprestes/brasilino
android/Brasilino/app/src/main/java/com/paypal/developer/brasilino/broadcast/PaymentOrderReceiver.java
[ "public class PermissionActivity extends ActionBarActivity {\n\n private WebView webContent;\n private ProgressBar progress;\n private Bundle receivedExtras;\n private Token token;\n\n @Override\n protected void onSaveInstanceState(@NonNull Bundle outState) {\n super.onSaveInstanceState(outState);\n if (receivedExtras != null)\n outState.putAll(receivedExtras);\n }\n\n @SuppressLint(\"SetJavaScriptEnabled\")\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_permission);\n\n NotificationManagerCompat.from(getApplicationContext()).cancel(Util.NOTIFICATION_ID);\n\n if (savedInstanceState != null)\n receivedExtras = savedInstanceState;\n\n final CandieSQLiteDataSource dataSource = CarrinhoApplication.getDatasource();\n\n webContent = ((WebView) findViewById(R.id.webContent));\n webContent.setVisibility(View.INVISIBLE);\n CandiesWebViewClient webViewClient = new CandiesWebViewClient(this);\n webViewClient.setOnProcessStepListener(new CandiesWebViewClient.OnProcessStepListener() {\n @Override\n public void onProcessStarted() {\n progress.setVisibility(View.GONE);\n webContent.setVisibility(View.VISIBLE);\n }\n\n @Override\n public void onServerLoading() {\n progress.setVisibility(View.VISIBLE);\n webContent.setVisibility(View.INVISIBLE);\n }\n\n @Override\n public void onProcessFinished() {\n dataSource.saveToken(token);\n /*Intent paymentIntent = new Intent(getApplicationContext(), PaymentService.class);\n if (receivedExtras != null)\n paymentIntent.putExtras(receivedExtras);\n getApplicationContext().startService(paymentIntent);\n finish();*/\n WebServerHelper.requestUser(\n token,\n new Response.Listener<User>() {\n @Override\n public void onResponse(User response) {\n Toast.makeText(PermissionActivity.this, \"Bem vindo \" + response.getFirstName() + \" \" + response.getLastName(), Toast.LENGTH_LONG).show();\n SharedPreferences.Editor editor = CarrinhoApplication.get().getSharedPreferences().edit();\n editor.putString(\"Nome\", response.getFirstName() + \" \" + response.getLastName());\n editor.commit();\n finish();\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n }\n });;\n }\n });\n webContent.setWebViewClient(webViewClient);\n\n //We are enabling Javascript and Cookies for a better experience on the PayPal web site\n webContent.getSettings().setJavaScriptEnabled(true);\n webContent.getSettings().setAppCacheEnabled(true);\n\n progress = ((ProgressBar) findViewById(R.id.progress));\n progress.setIndeterminate(true);\n progress.setVisibility(View.VISIBLE);\n\n if (dataSource.getToken() == null) {\n WebServerHelper.requestNewToken(\n new Response.Listener<Token>() {\n @Override\n public void onResponse(Token response) {\n showWebContentForToken(response);\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n TextView errorMessage = ((TextView) findViewById(R.id.errorMessage));\n errorMessage.setVisibility(View.VISIBLE);\n progress.setVisibility(View.GONE);\n }\n });\n } else\n showWebContentForToken(dataSource.getToken());\n }\n\n private void showWebContentForToken(Token token) {\n this.token = token;\n webContent.loadUrl(token.getUrl().toString());\n\n /* WebServerHelper.requestUser(\n token,\n new Response.Listener<User>() {\n @Override\n public void onResponse(User response) {\n Log.e(CarrinhoApplication.class.getSimpleName(), \"Bem vindo \" + response.getFirstName() + \" \" +\n response.getLastName());\n Toast.makeText(PermissionActivity.this, \"Bem vindo \" + response.getFirstName() + \" \" +\n response.getLastName(), Toast.LENGTH_LONG).show();\n\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n }\n });;*/\n }\n}", "public class CarrinhoApplication extends Application {\n private static final String UNBIND_FLAG = \"UNBIND_FLAG\";\n\n private CandieSQLiteDataSource dataSource;\n private static CarrinhoApplication app;\n\n private RequestQueue queue;\n\n @Override\n public void onCreate() {\n super.onCreate();\n app = this;\n dataSource = new CandieSQLiteDataSource(app);\n }\n\n public static CandieSQLiteDataSource getDatasource() {\n if(app == null)\n return null;\n else\n return app.dataSource;\n }\n\n public static CarrinhoApplication get() {\n return app;\n }\n\n /**\n * Add a simple Volley {@link com.android.volley.Request} to the application request queue\n * @param request A valid Volley {@link com.android.volley.Request}\n */\n public void addRequestToQueue(Request<?> request) {\n addRequestToQueue(request, CarrinhoApplication.class.getSimpleName());\n }\n\n /**\n * <p>Add a Volley {@link com.android.volley.Request} to the application request queue.</p>\n * <p>But, first, associate a {@link java.lang.String} tag to the request. So, it can be\n * stopped latter</p>\n * @param request A valid Volley {@link com.android.volley.Request}\n * @param tag {@link java.lang.String} that will be associated to the specific request\n */\n public void addRequestToQueue(Request<?> request, String tag) {\n request.setTag(tag);\n request.setRetryPolicy(new DefaultRetryPolicy(\n 10000,\n DefaultRetryPolicy.DEFAULT_MAX_RETRIES,\n DefaultRetryPolicy.DEFAULT_BACKOFF_MULT\n ));\n getQueue().add(request);\n }\n\n /**\n * Get the application {@link com.android.volley.RequestQueue}. It holds all the application\n * internet request\n * @return The application {@link com.android.volley.RequestQueue}\n */\n public RequestQueue getQueue() {\n if(queue == null) {\n queue = Volley.newRequestQueue(app, new OkHttpStack());\n }\n return queue;\n }\n\n public SharedPreferences getSharedPreferences() {\n return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n }\n\n public void setFromUnbind(boolean fromUnbind)\n {\n if(fromUnbind)\n getSharedPreferences().edit().putBoolean(UNBIND_FLAG, true).apply();\n else\n getSharedPreferences().edit().remove(UNBIND_FLAG).apply();\n }\n\n}", "public class CandieSQLiteDataSource\n{\n private SQLiteDatabase database;\n private SQLiteOpenHelper dbHelper;\n\n public CandieSQLiteDataSource(Context context) {\n dbHelper = new CandieSQLiteHelper(context);\n }\n\n private void open() throws SQLiteException {\n database = dbHelper.getWritableDatabase();\n }\n\n private SQLiteDatabase getWritableDatabase() throws SQLiteException {\n if(database == null)\n open();\n return database;\n }\n\n public void close() {\n database.close();\n dbHelper.close();\n database = null;\n }\n\n public Token getToken() {\n\n Cursor cursor = getWritableDatabase().query(\n Token.DomainNamespace.TABLE_NAME,\n Token.getColumns(),\n null,\n null,\n null,\n null,\n null\n );\n\n if(cursor == null)\n return null;\n\n if(cursor.moveToFirst()) {\n Token token = new Token(cursor);\n if(!cursor.isClosed())cursor.close();\n return token;\n }\n\n return null;\n }\n\n public boolean saveToken(Token token) {\n boolean successful = false;\n SQLiteDatabase db = getWritableDatabase();\n db.beginTransaction();\n try {\n long insertId = db.insert(\n Token.DomainNamespace.TABLE_NAME,\n null,\n token.toContentValues()\n );\n if(insertId >= 0) {\n successful = true;\n db.setTransactionSuccessful();\n }\n } catch (Exception ex) {\n successful = false;\n } finally {\n db.endTransaction();\n }\n\n return successful;\n }\n\n public boolean updateToken(Token token) {\n SQLiteDatabase db = getWritableDatabase();\n Cursor cursor = getWritableDatabase().query(\n Token.DomainNamespace.TABLE_NAME,\n Token.getColumns(),\n null,\n null,\n null,\n null,\n null\n );\n if(cursor != null && cursor.moveToFirst()) {\n int id = cursor.getInt(cursor.getColumnIndex(Token.DomainNamespace.ID));\n if(!cursor.isClosed())cursor.close();\n if(id >= 0) {\n int updated = db.update(\n Token.DomainNamespace.TABLE_NAME,\n token.toContentValues(),\n Token.DomainNamespace.ID + \"=?\",\n new String[]{String.valueOf(id)}\n );\n if(updated > 0)\n return true;\n }\n }\n return false;\n }\n\n}", "public class Token\n{\n @SerializedName(\"token\")\n private String token;\n @SerializedName(\"url\")\n private String url;\n\n public Token() {}\n\n public Token(Cursor cursor) {\n this.url = null;\n this.token = cursor.getString(cursor.getColumnIndex(DomainNamespace.TOKEN));\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 Uri getUrl() {\n if(url == null) return null;\n return Uri.parse(url);\n }\n\n public void setUrl(Uri url) {\n this.url = (url == null?null:url.toString());\n }\n\n public ContentValues toContentValues() {\n ContentValues values = new ContentValues();\n values.put(DomainNamespace.TOKEN, token);\n return values;\n }\n\n public static String[] getColumns() {\n return new String[]{DomainNamespace.ID, DomainNamespace.TOKEN};\n }\n\n public class DomainNamespace {\n public static final String TABLE_NAME = \"token\";\n public static final String ID = \"_id\";\n public static final String TOKEN = \"token\";\n }\n}", "public class PaymentService extends Service {\n\n private LocalBinder mBinder = new LocalBinder();\n private PaymentStepsListener paymentStepsListener;\n private Token token = null;\n\n\n public interface PaymentStepsListener {\n public void onPaymentStarted(Token token);\n public void onPaymentFinished(Token token, boolean successful, String message);\n }\n\n\n public PaymentService() {\n token = CarrinhoApplication.getDatasource().getToken();\n }\n\n private String getStringToken() {\n return token.getToken();\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n\n final Token token = CarrinhoApplication.getDatasource().getToken();\n\n if(token != null) {\n NotificationManagerCompat.from(getApplicationContext()).cancel(Util.NOTIFICATION_ID);\n WebServerHelper.performNewPayment(\n this.getStringToken(),\n intent.getBooleanExtra(\"five\", false)?Util.PRODUCT_DEFAULT_VALUE_FIVE:Util.PRODUCT_DEFAULT_VALUE_TEN,\n this.getResponsePaymentListener(),\n this.getErrorPaymentListener()\n );\n\n if(paymentStepsListener != null) {\n paymentStepsListener.onPaymentStarted(token);\n }\n\n return START_STICKY;\n } else {\n return START_NOT_STICKY;\n }\n }\n\n\n @Override\n public IBinder onBind(Intent intent) {\n return mBinder;\n }\n\n public void setPaymentStepsListener(PaymentStepsListener paymentStepsListener) {\n this.paymentStepsListener = paymentStepsListener;\n }\n\n\n public class LocalBinder extends Binder {\n public PaymentService getService() {\n return PaymentService.this;\n }\n }\n\n\n /**\n * Return specific Response Payment listener to payment webservice call\n */\n public Response.Listener<NewTransaction> getResponsePaymentListener() {\n\n return new Response.Listener<NewTransaction>() {\n\n public void onResponse (NewTransaction response) {\n if (response.isSuccessfull()) {\n\n finishService(\"Pegar dados do usuário...\", true);\n /*WebServerHelper.sendMachineOrder(\n token,\n new Response.Listener<NewTransaction>() {\n\n @Override\n public void onResponse(NewTransaction response) {\n if(response.isSuccessfull()) {\n Util.sendMessage(\n \"/candies/payment\",\n \"success\"\n );\n finishService(\"Pegar dados do usuário...\", true);\n } else {\n finishService(\"Erro no comando à maquina.\", false);\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.e(PaymentService.class.getSimpleName(), \"Erro no envio à máquina\", error);\n finishService(Log.getStackTraceString(error), false);\n }\n }\n );*/\n\n } else {\n finishService(response.getMessage(), false);\n }\n }\n\n };\n }\n\n private void finishService(String message, boolean successful) {\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n\n Util.sendMessage(\n \"/candies/payment\",\n (successful?\"success\":\"fail\")\n );\n\n if (paymentStepsListener != null)\n paymentStepsListener.onPaymentFinished(token, successful, message);\n stopSelf();\n }\n\n /**\n * Specific error listener for payment webservice call\n * @return Error Listener for payment webservice call\n */\n public Response.ErrorListener getErrorPaymentListener() {\n return new Response.ErrorListener() {\n public void onErrorResponse(VolleyError error) {\n Log.e(CarrinhoApplication.class.getSimpleName(), Log.getStackTraceString(error));\n Toast.makeText(getApplicationContext(), \"Erro no pagamento: \" + error.getLocalizedMessage() + \" | Tempo final: \" + (Calendar.getInstance().getTimeInMillis()), Toast.LENGTH_SHORT).show();\n if (paymentStepsListener != null)\n paymentStepsListener.onPaymentFinished(token, false, error.getMessage());\n stopSelf();\n }\n };\n }\n}", "public class IntentParameters {\n\n public static final String UUID = \"UUID\";\n public static final String MAJOR = \"Major\";\n public static final String MINOR = \"Minor\";\n\n}", "public class Util\n{\n public static final int NOTIFICATION_ID = 123456;\n public static final double PRODUCT_DEFAULT_VALUE_FIVE = 1.0f;\n public static final double PRODUCT_DEFAULT_VALUE_TEN = 2.0f;\n\n public static void dispatchNotification(Context context, String uuid, String major, String minor, int productImage)\n {\n Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), productImage);\n dispatchNotification(context, uuid, major, minor, bitmap);\n bitmap.recycle();\n }\n\n public static void dispatchNotification(Context context, String uuid, String major, String minor, Bitmap productImage)\n {\n Bundle infoBundle = new Bundle();\n infoBundle.putString(IntentParameters.UUID,uuid);\n infoBundle.putString(IntentParameters.MAJOR,major);\n infoBundle.putString(IntentParameters.MINOR,minor);\n\n Intent purchaseIntent = new Intent(context, PaymentOrderReceiver.class);\n purchaseIntent.putExtras(infoBundle);\n\n PendingIntent purchasePendingIntent = PendingIntent.getBroadcast(\n context,\n RequestCode.PURCHASE,\n purchaseIntent,\n PendingIntent.FLAG_CANCEL_CURRENT);\n\n NotificationCompat.Builder builder = new NotificationCompat.Builder(context)\n .setSmallIcon(R.drawable.ic_launcher)\n .setLocalOnly(true)\n .setAutoCancel(true)\n .setCategory(NotificationCompat.CATEGORY_PROMO)\n .setPriority(NotificationCompat.PRIORITY_HIGH)\n .setContentTitle(context.getString(R.string.notification_generic_title))\n .setContentText(context.getString(R.string.notification_generic_message))\n .addAction(R.drawable.ic_logo_paypal, context.getString(R.string.action_purchase), purchasePendingIntent);\n\n Notification notification = builder.build();\n notification.defaults |= Notification.DEFAULT_ALL;\n\n NotificationManagerCompat manager = NotificationManagerCompat.from(context);\n manager.notify(NOTIFICATION_ID,notification);\n }\n\n public static boolean isServiceRunning(Class<?> serviceClass, Context context) {\n ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n\n public static void sendMessage(String path, String message) {\n Log.e(\"THTPAYPALCARRINHO\", path + \" - \" + message);\n }\n\n public static void scheduleReceiver(Context context, Class receiver) {\n Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(System.currentTimeMillis());\n calendar.set(Calendar.MILLISECOND, 500);\n\n AlarmManager alarmManager = (AlarmManager)context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);\n Intent receiverIntent = new Intent(context.getApplicationContext(), receiver);\n PendingIntent receiverPendent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, receiverIntent, 0);\n alarmManager.set(\n AlarmManager.RTC_WAKEUP,\n calendar.getTimeInMillis(),\n receiverPendent\n );\n }\n\n //TODO: Refazer a logica de desabilitar a cobrança do paypal para Ricardo\n //Criar outra variavel em SharedPreferences\n public static String retiraTHT(String ipTemp) {\n\n String trechoFinal = ipTemp.substring(ipTemp.length()-3,ipTemp.length());\n\n if (\"tht\".equalsIgnoreCase(trechoFinal)) {\n ipTemp = ipTemp.substring(0,ipTemp.length()-3);\n }\n\n return ipTemp;\n }\n}" ]
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationManagerCompat; import com.paypal.developer.brasilino.PermissionActivity; import com.paypal.developer.brasilino.application.CarrinhoApplication; import com.paypal.developer.brasilino.database.CandieSQLiteDataSource; import com.paypal.developer.brasilino.domain.Token; import com.paypal.developer.brasilino.service.PaymentService; import com.paypal.developer.brasilino.util.IntentParameters; import com.paypal.developer.brasilino.util.Util;
package com.paypal.developer.brasilino.broadcast; /** * Created by ricardo on 31/01/2015. */ public class PaymentOrderReceiver extends BroadcastReceiver { public PaymentOrderReceiver() {} @Override public void onReceive(Context context, Intent intent) { NotificationManagerCompat.from(context).cancel(Util.NOTIFICATION_ID); if(intent != null && intent.hasExtra(IntentParameters.UUID)) { CandieSQLiteDataSource dataSource = CarrinhoApplication.getDatasource(); if(dataSource != null) {
Token token = dataSource.getToken();
3
synapticloop/routemaster
src/main/java/synapticloop/nanohttpd/example/servant/ModulesRouteServant.java
[ "public abstract class Routable {\n\t// the route that this routable is bound to\n\tprotected String routeContext = null;\n\t// the map of option key values\n\tprotected Map<String, String> options = new HashMap<String, String>();\n\n\t/**\n\t * Create a new routable class with the bound routing context\n\t *\n\t * @param routeContext the context to route to\n\t */\n\tpublic Routable(String routeContext) {\n\t\tthis.routeContext = routeContext;\n\t}\n\n\t/**\n\t * Serve the correctly routed file\n\t *\n\t * @param rootDir The root directory of the RouteMaster server\n\t * @param httpSession The session\n\t *\n\t * @return The response\n\t */\n\tpublic abstract Response serve(File rootDir, IHTTPSession httpSession);\n\t\n\t/**\n\t * Set an option for this routable into the options map.\n\t * \n\t * @param key The option key\n\t * @param value the value\n\t */\n\tpublic void setOption(String key, String value) {\n\t\toptions.put(key, value);\n\t}\n\n\t/**\n\t * Get an option from the map, or null if it does not exist\n\t * \n\t * @param key the key to search for\n\t * \n\t * @return the value of the option, or null if it doesn't exist\n\t */\n\tpublic String getOption(String key) {\n\t\treturn(options.get(key));\n\t}\n}", "public class RouteMaster {\n\tprivate static final String ROUTEMASTER_PROPERTIES = \"routemaster.properties\";\n\tprivate static final String ROUTEMASTER_JSON = \"routemaster.json\";\n\tprivate static final String ROUTEMASTER_EXAMPLE_PROPERTIES = \"routemaster.example.properties\";\n\tprivate static final String ROUTEMASTER_EXAMPLE_JSON = \"routemaster.example.json\";\n\n\tprivate static final String PROPERTY_PREFIX_REST = \"rest.\";\n\tprivate static final String PROPERTY_PREFIX_ROUTE = \"route.\";\n\tprivate static final String PROPERTY_PREFIX_HANDLER = \"handler.\";\n\n\tprivate static Router router = null;\n\n\tprivate static Set<String> indexFiles = new HashSet<String>();\n\tprivate static Map<Integer, String> errorPageCache = new ConcurrentHashMap<Integer, String>();\n\tprivate static Map<String, Routable> routerCache = new ConcurrentHashMap<String, Routable>();\n\tprivate static Map<String, Handler> handlerCache = new ConcurrentHashMap<String, Handler>();\n\tprivate static Set<String> modules = new HashSet<String>();\n\n\tprivate static boolean initialised = false;\n\tprivate static File rootDir;\n\n\tprivate RouteMaster() {}\n\n\t/**\n\t * Initialise the RouteMaster by attempting to look for the routemaster.properties\n\t * in the classpath and on the file system.\n\t * \n\t * @param rootDir the root directory from which content should be sourced\n\t */\n\tpublic static void initialise(File rootDir) {\n\t\tRouteMaster.rootDir = rootDir;\n\n\t\tProperties properties = null;\n\t\tboolean allOk = true;\n\n\t\ttry {\n\t\t\tproperties = FileHelper.confirmPropertiesFileDefault(ROUTEMASTER_PROPERTIES, ROUTEMASTER_EXAMPLE_PROPERTIES);\n\t\t} catch (IOException ioex) {\n\t\t\ttry {\n\t\t\t\tlogNoRoutemasterProperties();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tallOk = false;\n\t\t}\n\n\t\tif(null == properties) {\n\t\t\ttry {\n\t\t\t\tlogNoRoutemasterProperties();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tallOk = false;\n\t\t}\n\n\t\tif(allOk) {\n\t\t\t// at this point we want to load any modules that we find, and at them to the \n\t\t\t// properties file\n\t\t\tloadModules(properties);\n\n\t\t\tparseOptionsAndRoutes(properties);\n\t\t\tinitialised = true;\n\t\t} else {\n\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(\"/*\", \"/\", false);\n\t\t\trouter = new Router(\"/*\", stringTokenizer, UninitialisedServant.class.getCanonicalName());\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically load any modules that exist within the 'modules' directory\n\t * \n\t * @param properties the properties from the default routemaster.properties\n\t */\n\tprivate static void loadModules(Properties properties) {\n\t\t// look in the modules directory\n\t\tFile modulesDirectory = new File(rootDir.getAbsolutePath() + \"/modules/\");\n\t\tif(modulesDirectory.exists() && modulesDirectory.isDirectory() && modulesDirectory.canRead()) {\n\t\t\tString[] moduleList = modulesDirectory.list(new FilenameFilter() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\t\treturn(name.endsWith(\".jar\"));\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tint length = moduleList.length;\n\n\t\t\tif(length == 0) {\n\t\t\t\tlogInfo(\"No modules found, continuing...\");\n\t\t\t} else {\n\t\t\t\tlogInfo(\"Scanning '\" + length + \"' jar files for modules\");\n\t\t\t\tURLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();\n\t\t\t\tMethod method = null;\n\t\t\t\ttry {\n\t\t\t\t\tmethod = URLClassLoader.class.getDeclaredMethod(\"addURL\", URL.class);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogFatal(\"Could not load any modules, exception message was: \" + ex.getMessage());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tmethod.setAccessible(true);\n\t\t\t\tfor (String module : moduleList) {\n\t\t\t\t\tlogInfo(\"Found potential module in file '\" + module + \"'.\");\n\n\t\t\t\t\tFile file = new File(rootDir + \"/modules/\" + module);\n\n\t\t\t\t\t// try and find the <module>-<version>.jar.properties file which will\n\t\t\t\t\t// over-ride the routemaster.properties entry in the jar file\n\n\t\t\t\t\tboolean loadedOverrideProperties = false;\n\n\t\t\t\t\tString moduleName = getModuleName(module);\n\t\t\t\t\tFile overridePropertiesFile = new File(rootDir + \"/modules/\" + moduleName + \".properties\");\n\t\t\t\t\tif(overridePropertiesFile.exists() && overridePropertiesFile.canRead()) {\n\t\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Found an over-ride .properties file '\" + moduleName + \".properties'.\");\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tProperties mergeProperties = new Properties();\n\t\t\t\t\t\t\tmergeProperties.load(new FileReader(overridePropertiesFile));\n\t\t\t\t\t\t\tIterator<Object> iterator = mergeProperties.keySet().iterator();\n\t\t\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\t\t\tString key = (String) iterator.next();\n\t\t\t\t\t\t\t\tif(properties.containsKey(key)) {\n\t\t\t\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Routemaster already has a property with key '\" + key + \"', over-writing...\");\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tString value = mergeProperties.getProperty(key);\n\t\t\t\t\t\t\t\tproperties.setProperty(key, value);\n\n\t\t\t\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Adding property key '\" + key + \"', value '\" + value + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tloadedOverrideProperties = true;\n\t\t\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\t\t\tlogFatal(\"Could not load modules message was: \" + ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t\tJarFile jarFile = new JarFile(file);\n\t\t\t\t\t\t\tZipEntry zipEntry = jarFile.getEntry(moduleName + \".properties\");\n\t\t\t\t\t\t\tif(null != zipEntry) {\n\t\t\t\t\t\t\t\tURL url = file.toURI().toURL();\n\t\t\t\t\t\t\t\tmethod.invoke(classLoader, url);\n\n\t\t\t\t\t\t\t\tif(!loadedOverrideProperties) { \n\t\t\t\t\t\t\t\t\t// assuming that the above works - read the properties from the \n\t\t\t\t\t\t\t\t\t// jar file\n\t\t\t\t\t\t\t\t\treadProperties(module, properties, jarFile, zipEntry);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif(!modules.contains(module)) {\n\t\t\t\t\t\t\t\t\tmodules.add(module);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Could not find '/\" + moduleName + \".properties' in file '\" + module + \"'.\");\n\t\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\t\tjarFile.close();\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tlogFatal(\"Could not load modules message was: \" + ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void readProperties(String module, Properties properties, JarFile jarFile, ZipEntry zipEntry) throws IOException {\n\t\tInputStream input = jarFile.getInputStream(zipEntry);\n\t\tInputStreamReader isr = new InputStreamReader(input);\n\t\tBufferedReader reader = new BufferedReader(isr);\n\t\tString line;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tString trimmed = line.trim();\n\n\t\t\tif(trimmed.length() != 0) {\n\t\t\t\tif(trimmed.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString[] split = line.split(\"=\", 2);\n\t\t\t\tif(split.length == 2) {\n\t\t\t\t\tString key = split[0].trim();\n\t\t\t\t\tString value = split[1].trim();\n\t\t\t\t\tif(properties.containsKey(key)) {\n\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Routemaster already has a property with key '\" + key + \"', over-writing...\");\n\t\t\t\t\t}\n\n\t\t\t\t\tproperties.setProperty(key, value);\n\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Adding property key '\" + key + \"', value '\" + value + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treader.close();\n\t}\n\n\tprivate static String getModuleName(String module) {\n\t\tPattern r = Pattern.compile(\"(.*)-\\\\d+\\\\.\\\\d+.*\\\\.jar\");\n\t\tMatcher m = r.matcher(module);\n\t\tif(m.matches()) {\n\t\t\treturn(m.group(1));\n\t\t}\n\n\t\tint lastIndexOf = module.lastIndexOf(\".\");\n\t\treturn(module.substring(0, lastIndexOf));\n\t}\n\n\tprivate static void parseOptionsAndRoutes(Properties properties) {\n\t\t// now parse the properties\n\t\tparseOptions(properties);\n\t\tEnumeration<Object> keys = properties.keys();\n\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tString routerClass = (String)properties.get(key);\n\t\t\tif(key.startsWith(PROPERTY_PREFIX_ROUTE)) {\n\t\t\t\t// time to bind a route\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_ROUTE.length());\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(subKey, \"/\", false);\n\t\t\t\tif(null == router) {\n\t\t\t\t\trouter = new Router(subKey, stringTokenizer, routerClass);\n\t\t\t\t} else {\n\t\t\t\t\trouter.addRoute(subKey, stringTokenizer, routerClass);\n\t\t\t\t}\n\t\t\t} else if(key.startsWith(PROPERTY_PREFIX_REST)) {\n\t\t\t\t// time to bind a rest route\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_REST.length());\n\t\t\t\t// now we need to get the parameters\n\t\t\t\tString[] splits = subKey.split(\"/\");\n\t\t\t\tStringBuilder stringBuilder = new StringBuilder();\n\n\t\t\t\tList<String> params = new ArrayList<String>();\n\t\t\t\tif(subKey.startsWith(\"/\")) { stringBuilder.append(\"/\"); }\n\n\t\t\t\tfor (int i = 0; i < splits.length; i++) {\n\t\t\t\t\tString split = splits[i];\n\t\t\t\t\tif(split.length() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(split.startsWith(\"%\") && split.endsWith(\"%\")) {\n\t\t\t\t\t\t// have a parameter\n\t\t\t\t\t\tparams.add(split.substring(1, split.length() -1));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstringBuilder.append(split);\n\t\t\t\t\t\t// keep adding a slash for those that are missing - but not\n\t\t\t\t\t\t// if it the last\n\t\t\t\t\t\tif(i != splits.length -1) { stringBuilder.append(\"/\"); }\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// now clean up the route\n\t\t\t\tString temp = stringBuilder.toString();\n\t\t\t\tif(!temp.endsWith(\"/\")) { stringBuilder.append(\"/\"); }\n\t\t\t\t// need to make sure that the rest router always picks up wildcards\n\t\t\t\tif(!subKey.endsWith(\"*\")) { stringBuilder.append(\"*\"); }\n\n\t\t\t\tsubKey = stringBuilder.toString();\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(subKey, \"/\", false);\n\t\t\t\tif(null == router) {\n\t\t\t\t\trouter = new Router(subKey, stringTokenizer, routerClass, params);\n\t\t\t\t} else {\n\t\t\t\t\trouter.addRestRoute(subKey, stringTokenizer, routerClass, params);\n\t\t\t\t}\n\n\t\t\t} else if(key.startsWith(PROPERTY_PREFIX_HANDLER)) {\n\t\t\t\t// we are going to add in a plugin\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_HANDLER.length());\n\t\t\t\tString pluginProperty = properties.getProperty(key);\n\n\t\t\t\ttry {\n\t\t\t\t\tObject pluginClass = Class.forName(pluginProperty).newInstance();\n\t\t\t\t\tif(pluginClass instanceof Handler) {\n\t\t\t\t\t\thandlerCache.put(subKey, (Handler)pluginClass);\n\t\t\t\t\t\tlogInfo(\"Handler '\" + pluginClass + \"', registered for '*.\" + subKey + \"'.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogFatal(\"Plugin class '\" + pluginProperty + \"' is not of instance Plugin.\");\n\t\t\t\t\t}\n\t\t\t\t} catch (ClassNotFoundException cnfex) {\n\t\t\t\t\tlogFatal(\"Could not find the class for '\" + pluginProperty + \"'.\", cnfex);\n\t\t\t\t} catch (InstantiationException iex) {\n\t\t\t\t\tlogFatal(\"Could not instantiate the class for '\" + pluginProperty + \"'.\", iex);\n\t\t\t\t} catch (IllegalAccessException iaex) {\n\t\t\t\t\tlogFatal(\"Illegal acces for class '\" + pluginProperty + \"'.\", iaex);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tlogWarn(\"Unknown property prefix for key '\" + key + \"'.\");\n\t\t\t}\n\t\t}\n\n\t\tif(null != router) {\n\t\t\tlogTable(router.getRouters(), \"registered routes\", \"route\", \"routable class\");\n\t\t}\n\n\t\tlogTable(new ArrayList<String>(modules), \"loaded modules\");\n\n\t\tif(indexFiles.isEmpty()) {\n\t\t\t// default welcomeFiles\n\t\t\tindexFiles.add(\"index.html\");\n\t\t\tindexFiles.add(\"index.htm\");\n\t\t}\n\n\t\tlogTable(new ArrayList<String>(indexFiles), \"index files\");\n\n\t\tlogTable(errorPageCache, \"error pages\", \"status\", \"page\");\n\n\t\tlogTable(handlerCache, \"Handlers\", \"extension\", \"handler class\");\n\n\t\tMimeTypeMapper.logMimeTypes();\n\n\t\tlogInfo(RouteMaster.class.getSimpleName() + \" initialised.\");\n\t}\n\n\tprivate static void logNoRoutemasterProperties() throws IOException {\n//\t\tlogFatal(\"Could not load the '\" + ROUTEMASTER_JSON + \"' file, ignoring...\");\n//\t\tlogFatal(\"(Consequently this is going to be a pretty boring experience!\");\n//\t\tlogFatal(\"but we did write out an example file for you - '\" + ROUTEMASTER_EXAMPLE_JSON + \"')\");\n//\t\tlogFatal(\"NOTE: the '\" + ROUTEMASTER_EXAMPLE_JSON + \"' takes precedence)\");\n//\t\tInputStream inputStream = RouteMaster.class.getResourceAsStream(\"/\" + ROUTEMASTER_EXAMPLE_JSON);\n//\n//\t\tFileHelper.writeFile(new File(ROUTEMASTER_EXAMPLE_JSON), inputStream, true);\n//\t\tinputStream.close();\n\n\t\tlogFatal(\"Could not load the '\" + ROUTEMASTER_PROPERTIES + \"' file, ignoring...\");\n\t\tlogFatal(\"(Consequently this is going to be a pretty boring experience!\");\n\t\tlogFatal(\"but we did write out an example file for you - '\" + ROUTEMASTER_EXAMPLE_PROPERTIES + \"')\");\n\n\t\tInputStream inputStream = RouteMaster.class.getResourceAsStream(\"/\" + ROUTEMASTER_EXAMPLE_PROPERTIES);\n\t\tFileHelper.writeFile(new File(ROUTEMASTER_EXAMPLE_PROPERTIES), inputStream, true);\n\t\tinputStream.close();\n\n\t}\n\n\t/**\n\t * Parse the options file\n\t *\n\t * @param properties The properties object\n\t * @param key the option key we are looking at\n\t */\n\tprivate static void parseOption(Properties properties, String key) {\n\t\tif(\"option.indexfiles\".equals(key)) {\n\t\t\tString property = properties.getProperty(key);\n\t\t\tString[] splits = property.split(\",\");\n\t\t\tfor (int i = 0; i < splits.length; i++) {\n\t\t\t\tString split = splits[i].trim();\n\t\t\t\tindexFiles.add(split);\n\t\t\t}\n\t\t} else if(key.startsWith(\"option.error.\")) {\n\t\t\tString subKey = key.substring(\"option.error.\".length());\n\t\t\ttry {\n\t\t\t\tint parseInt = Integer.parseInt(subKey);\n\t\t\t\terrorPageCache.put(parseInt, properties.getProperty(key));\n\t\t\t} catch(NumberFormatException nfex) {\n\t\t\t\tlogFatal(\"Could not parse error key '\" + subKey + \"'.\", nfex);\n\t\t\t}\n\t\t} else if(\"option.log\".equals(key)) {\n\t\t\t//\t\t\tlogRequests = properties.getProperty(\"option.log\").equalsIgnoreCase(\"true\");\n\t\t}\n\t}\n\n\tprivate static void parseOptions(Properties properties) {\n\t\tEnumeration<Object> keys = properties.keys();\n\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tif(key.startsWith(\"option.\")) {\n\t\t\t\tparseOption(properties, key);\n\t\t\t\tproperties.remove(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Serve the correctly routed file\n\t *\n\t * @param rootDir The root directory of the RouteMaster server\n\t * @param httpSession The session\n\t *\n\t * @return The response\n\t */\n\tpublic static Response route(File rootDir, IHTTPSession httpSession) {\n\t\tif(!initialised) {\n\t\t\tHttpUtils.notFoundResponse();\n\t\t}\n\n\t\tResponse routeInternalResponse = routeInternal(rootDir, httpSession);\n\t\tif(null != routeInternalResponse) {\n\t\t\treturn(routeInternalResponse);\n\t\t}\n\n\t\treturn(get500Response(rootDir, httpSession));\n\t}\n\n\tprivate static Response routeInternal(File rootDir, IHTTPSession httpSession) {\n\t\tif(null != router) {\n\t\t\t// try and find the route\n\t\t\tString uri = httpSession.getUri();\n\n\t\t\t// do we have a cached version of this?\n\t\t\tif(routerCache.containsKey(uri)) {\n\t\t\t\tResponse serve = routerCache.get(uri).serve(rootDir, httpSession);\n\t\t\t\tif(serve == null) {\n\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t} else {\n\t\t\t\t\treturn(serve);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(uri, \"/\", false);\n\t\t\t\tRoutable routable = router.route(httpSession, stringTokenizer);\n\t\t\t\tif(null != routable) {\n\t\t\t\t\trouterCache.put(uri, routable);\n\t\t\t\t\tResponse serve = routable.serve(rootDir, httpSession);\n\t\t\t\t\tif(null != serve) {\n\t\t\t\t\t\treturn(serve);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// have a null route-able return 404 perhaps\n\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t}\n\t}\n\n\tprivate static Response getErrorResponse(File rootDir, IHTTPSession httpSession, Status status, String message) {\n\t\tint requestStatus = status.getRequestStatus();\n\t\tString uri = errorPageCache.get(requestStatus);\n\t\tif(errorPageCache.containsKey(requestStatus)) {\n\t\t\tModifiableSession modifiedSession = new ModifiableSession(httpSession);\n\t\t\tmodifiedSession.setUri(uri);\n\t\t\t// if not valid - we have already tried this - and we are going to get a\n\t\t\t// stack overflow, so just drop through\n\t\t\tif(modifiedSession.isValidRequest()) {\n\t\t\t\tResponse response = route(rootDir, modifiedSession);\n\t\t\t\tresponse.setStatus(status);\n\t\t\t\tif(null != response) {\n\t\t\t\t\treturn(response);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn(HttpUtils.notFoundResponse(AsciiArt.ROUTEMASTER + \n\t\t\t\t\" \" + \n\t\t\t\tmessage + \n\t\t\t\t\";\\n\\n additionally, an over-ride \" + \n\t\t\t\tstatus.toString() + \n\t\t\t\t\" error page was not defined\\n\\n in the configuration file, key 'option.error.404'.\"));\n\t}\n\n\tpublic static Response get404Response(File rootDir, IHTTPSession httpSession) { return(getErrorResponse(rootDir, httpSession, Response.Status.NOT_FOUND, \"not found\")); }\n\tpublic static Response get500Response(File rootDir, IHTTPSession httpSession) { return(getErrorResponse(rootDir, httpSession, Response.Status.INTERNAL_ERROR, \"internal server error\")); }\n\n\t/**\n\t * Get the root Router\n\t *\n\t * @return The Router assigned to the root of the site\n\t */\n\tpublic static Router getRouter() { return(router); }\n\n\t/**\n\t * Get the cache of all of the Routables which contains a Map of the Routables\n\t * per path - which saves on going through the Router and determining the\n\t * Routable on every access\n\t *\n\t * @return The Routable cache\n\t */\n\tpublic static Map<String, Routable> getRouterCache() { return (routerCache); }\n\n\t/**\n\t * Get the index/welcome files that are registered.\n\t *\n\t * @return The index files\n\t */\n\tpublic static Set<String> getIndexFiles() { return indexFiles; }\n\n\t/**\n\t * Get the handler cache\n\t * \n\t * @return the handler cache\n\t */\n\tpublic static Map<String, Handler> getHandlerCache() { return (handlerCache); }\n\t\n\t/**\n\t * Get the set of modules that have been registered with the routemaster\n\t * \n\t * @return the set of modules that have been registered\n\t */\n\tpublic static Set<String> getModules() { return(modules); }\n}", "public class HttpUtils {\n\n\tprivate static final Logger LOGGER = Logger.getLogger(HttpUtils.class.getName());\n\n\tpublic static String cleanUri(String uri) {\n\t\tif(null == uri) {\n\t\t\treturn(null);\n\t\t}\n\n\t\treturn(uri.replaceAll(\"/\\\\.\\\\./\", \"/\").replaceAll(\"//\", \"/\"));\n\t}\n\n\tprivate static Response defaultTextResponse(IStatus status) { return(newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, status.getDescription())); }\n\tprivate static Response defaultTextResponse(IStatus status, String content) { return(newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, content)); }\n\n\tpublic static Response okResponse() { return(defaultTextResponse(Response.Status.OK)); }\n\tpublic static Response okResponse(String content) { return(defaultTextResponse(Response.Status.OK, content)); }\n\tpublic static Response okResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.OK, mimeType, content)); }\n\tpublic static Response okResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.OK, mimeType, content, totalBytes)); }\n\n\tpublic static Response notFoundResponse() { return(defaultTextResponse(Response.Status.NOT_FOUND)); }\n\tpublic static Response notFoundResponse(String content) { return(defaultTextResponse(Response.Status.NOT_FOUND, content)); }\n\tpublic static Response notFoundResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.NOT_FOUND, mimeType, content)); }\n\tpublic static Response notFoundResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.NOT_FOUND, mimeType, content, totalBytes)); }\n\n\tpublic static Response rangeNotSatisfiableResponse() { return(defaultTextResponse(Response.Status.RANGE_NOT_SATISFIABLE)); }\n\tpublic static Response rangeNotSatisfiableResponse(String content) { return(defaultTextResponse(Response.Status.RANGE_NOT_SATISFIABLE, content)); }\n\tpublic static Response rangeNotSatisfiableResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, mimeType, content)); }\n\tpublic static Response rangeNotSatisfiableResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, mimeType, content, totalBytes)); }\n\n\tpublic static Response methodNotAllowedResponse() { return(defaultTextResponse(Response.Status.METHOD_NOT_ALLOWED)); }\n\tpublic static Response methodNotAllowedResponse(String content) { return(defaultTextResponse(Response.Status.METHOD_NOT_ALLOWED, content)); }\n\tpublic static Response methodNotAllowedResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, mimeType, content)); }\n\tpublic static Response methodNotAllowedResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, mimeType, content, totalBytes)); }\n\n\tpublic static Response internalServerErrorResponse() { return(defaultTextResponse(Response.Status.INTERNAL_ERROR)); }\n\tpublic static Response internalServerErrorResponse(String content) { return(defaultTextResponse(Response.Status.INTERNAL_ERROR, content)); }\n\tpublic static Response internalServerErrorResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mimeType, content)); }\n\tpublic static Response internalServerErrorResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mimeType, content, totalBytes)); }\n\n\tpublic static Response forbiddenResponse() { return(defaultTextResponse(Response.Status.FORBIDDEN)); }\n\tpublic static Response forbiddenResponse(String content) { return(defaultTextResponse(Response.Status.FORBIDDEN, content)); }\n\tpublic static Response forbiddenResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.FORBIDDEN, mimeType, content)); }\n\tpublic static Response forbiddenResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.FORBIDDEN, mimeType, content, totalBytes)); }\n\n\tpublic static Response badRequestResponse() { return(defaultTextResponse(Response.Status.BAD_REQUEST)); }\n\tpublic static Response badRequestResponse(String content) { return(defaultTextResponse(Response.Status.BAD_REQUEST, content)); }\n\tpublic static Response badRequestResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.BAD_REQUEST, mimeType, content)); }\n\tpublic static Response badRequestResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.BAD_REQUEST, mimeType, content, totalBytes)); }\n\n\tpublic static Response notModifiedResponse() { return(defaultTextResponse(Response.Status.NOT_MODIFIED)); }\n\tpublic static Response notModifiedResponse(String content) { return(defaultTextResponse(Response.Status.NOT_MODIFIED, content)); }\n\tpublic static Response notModifiedResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.NOT_MODIFIED, mimeType, content)); }\n\tpublic static Response notModifiedResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.NOT_MODIFIED, mimeType, content, totalBytes)); }\n\n\tpublic static Response partialContentResponse() { return(defaultTextResponse(Response.Status.PARTIAL_CONTENT)); }\n\tpublic static Response partialContentResponse(String content) { return(defaultTextResponse(Response.Status.PARTIAL_CONTENT, content)); }\n\tpublic static Response partialContentResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mimeType, content)); }\n\tpublic static Response partialContentResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mimeType, content, totalBytes)); }\n\n\tpublic static Response redirectResponse(String uri) { return(redirectResponse(uri, \"<html><body>Redirected: <a href=\\\"\" + uri + \"\\\">\" + uri + \"</a></body></html>\")); }\n\tpublic static Response redirectResponse(String uri, String message) {\n\t\tResponse res = newFixedLengthResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, message);\n\t\tres.addHeader(\"Location\", uri);\n\t\treturn(res);\n\t}\n\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\treturn new Response(status, mimeType, data, totalBytes);\n\t}\n\n\t/**\n\t * Create a text response with known length.\n\t * \n\t * @param status the HTTP status\n\t * @param mimeType the mime type of the response\n\t * @param response the response message \n\t * \n\t * @return The fixed length response object\n\t */\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, String response) {\n\t\tif (response == null) {\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);\n\t\t} else {\n\t\t\tbyte[] bytes;\n\t\t\ttry {\n\t\t\t\tbytes = response.getBytes(\"UTF-8\");\n\t\t\t} catch (UnsupportedEncodingException ueex) {\n\t\t\t\tLOGGER.log(Level.SEVERE, \"Encoding problem, responding nothing\", ueex);\n\t\t\t\tbytes = new byte[0];\n\t\t\t}\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(bytes), bytes.length);\n\t\t}\n\t}\n\n\tpublic static String getMimeType(String uri) {\n\t\tint lastIndexOf = uri.lastIndexOf(\".\");\n\t\tString extension = uri.substring(lastIndexOf + 1);\n\n\t\tString mimeType = NanoHTTPD.MIME_HTML;\n\n\t\tif(MimeTypeMapper.getMimeTypes().containsKey(extension)) {\n\t\t\tmimeType = MimeTypeMapper.getMimeTypes().get(extension);\n\t\t}\n\t\treturn(mimeType);\n\t}\n}", "public interface IHTTPSession {\n\n\tvoid execute() throws IOException;\n\n\tCookieHandler getCookies();\n\n\tMap<String, String> getHeaders();\n\n\tInputStream getInputStream();\n\n\tMethod getMethod();\n\n\t/**\n\t * This method will only return the first value for a given parameter.\n\t * You will want to use getParameters if you expect multiple values for\n\t * a given key.\n\t * \n\t * @deprecated use {@link #getParameters()} instead.\n\t */\n\t@Deprecated\n\tMap<String, String> getParms();\n\n\tMap<String, List<String>> getParameters();\n\n\tString getQueryParameterString();\n\n\t/**\n\t * @return the path part of the URL.\n\t */\n\tString getUri();\n\n\t/**\n\t * Adds the files in the request body to the files map.\n\t * \n\t * @param files\n\t * map to modify\n\t */\n\tvoid parseBody(Map<String, String> files) throws IOException, ResponseException;\n\n\t/**\n\t * Get the remote ip address of the requester.\n\t * \n\t * @return the IP address.\n\t */\n\tString getRemoteIpAddress();\n\n\t/**\n\t * Get the remote hostname of the requester.\n\t * \n\t * @return the hostname.\n\t */\n\tString getRemoteHostName();\n}", "public static class Response implements Closeable {\n\n\tpublic interface IStatus {\n\n\t\tString getDescription();\n\n\t\tint getRequestStatus();\n\t}\n\n\t/**\n\t * Some HTTP response status codes\n\t */\n\tpublic enum Status implements IStatus {\n\t\tSWITCH_PROTOCOL(101, \"Switching Protocols\"),\n\n\t\tOK(200, \"OK\"),\n\t\tCREATED(201, \"Created\"),\n\t\tACCEPTED(202, \"Accepted\"),\n\t\tNO_CONTENT(204, \"No Content\"),\n\t\tPARTIAL_CONTENT(206, \"Partial Content\"),\n\t\tMULTI_STATUS(207, \"Multi-Status\"),\n\n\t\tREDIRECT(301, \"Moved Permanently\"),\n\t\t/**\n\t\t * Many user agents mishandle 302 in ways that violate the RFC1945\n\t\t * spec (i.e., redirect a POST to a GET). 303 and 307 were added in\n\t\t * RFC2616 to address this. You should prefer 303 and 307 unless the\n\t\t * calling user agent does not support 303 and 307 functionality\n\t\t */\n\t\t@Deprecated\n\t\tFOUND(302, \"Found\"),\n\t\tREDIRECT_SEE_OTHER(303, \"See Other\"),\n\t\tNOT_MODIFIED(304, \"Not Modified\"),\n\t\tTEMPORARY_REDIRECT(307, \"Temporary Redirect\"),\n\n\t\tBAD_REQUEST(400, \"Bad Request\"),\n\t\tUNAUTHORIZED(401, \"Unauthorized\"),\n\t\tFORBIDDEN(403, \"Forbidden\"),\n\t\tNOT_FOUND(404, \"Not Found\"),\n\t\tMETHOD_NOT_ALLOWED(405, \"Method Not Allowed\"),\n\t\tNOT_ACCEPTABLE(406, \"Not Acceptable\"),\n\t\tREQUEST_TIMEOUT(408, \"Request Timeout\"),\n\t\tCONFLICT(409, \"Conflict\"),\n\t\tGONE(410, \"Gone\"),\n\t\tLENGTH_REQUIRED(411, \"Length Required\"),\n\t\tPRECONDITION_FAILED(412, \"Precondition Failed\"),\n\t\tPAYLOAD_TOO_LARGE(413, \"Payload Too Large\"),\n\t\tUNSUPPORTED_MEDIA_TYPE(415, \"Unsupported Media Type\"),\n\t\tRANGE_NOT_SATISFIABLE(416, \"Requested Range Not Satisfiable\"),\n\t\tEXPECTATION_FAILED(417, \"Expectation Failed\"),\n\t\tTOO_MANY_REQUESTS(429, \"Too Many Requests\"),\n\n\t\tINTERNAL_ERROR(500, \"Internal Server Error\"),\n\t\tNOT_IMPLEMENTED(501, \"Not Implemented\"),\n\t\tSERVICE_UNAVAILABLE(503, \"Service Unavailable\"),\n\t\tUNSUPPORTED_HTTP_VERSION(505, \"HTTP Version Not Supported\");\n\n\t\tprivate final int requestStatus;\n\n\t\tprivate final String description;\n\n\t\tStatus(int requestStatus, String description) {\n\t\t\tthis.requestStatus = requestStatus;\n\t\t\tthis.description = description;\n\t\t}\n\n\t\tpublic static Status lookup(int requestStatus) {\n\t\t\tfor (Status status : Status.values()) {\n\t\t\t\tif (status.getRequestStatus() == requestStatus) {\n\t\t\t\t\treturn status;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getDescription() {\n\t\t\treturn \"\" + this.requestStatus + \" \" + this.description;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getRequestStatus() {\n\t\t\treturn this.requestStatus;\n\t\t}\n\n\t}\n\n\t/**\n\t * Output stream that will automatically send every write to the wrapped\n\t * OutputStream according to chunked transfer:\n\t * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n\t */\n\tprivate static class ChunkedOutputStream extends FilterOutputStream {\n\n\t\tpublic ChunkedOutputStream(OutputStream out) {\n\t\t\tsuper(out);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(int b) throws IOException {\n\t\t\tbyte[] data = {\n\t\t\t\t\t(byte) b\n\t\t\t};\n\t\t\twrite(data, 0, 1);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(byte[] b) throws IOException {\n\t\t\twrite(b, 0, b.length);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(byte[] b, int off, int len) throws IOException {\n\t\t\tif (len == 0)\n\t\t\t\treturn;\n\t\t\tout.write(String.format(\"%x\\r\\n\", len).getBytes());\n\t\t\tout.write(b, off, len);\n\t\t\tout.write(\"\\r\\n\".getBytes());\n\t\t}\n\n\t\tpublic void finish() throws IOException {\n\t\t\tout.write(\"0\\r\\n\\r\\n\".getBytes());\n\t\t}\n\n\t}\n\n\t/**\n\t * HTTP status code after processing, e.g. \"200 OK\", Status.OK\n\t */\n\tprivate IStatus status;\n\n\t/**\n\t * MIME type of content, e.g. \"text/html\"\n\t */\n\tprivate String mimeType;\n\n\t/**\n\t * Data of the response, may be null.\n\t */\n\tprivate InputStream data;\n\n\tprivate long contentLength;\n\n\t/**\n\t * Headers for the HTTP response. Use addHeader() to add lines. the\n\t * lowercase map is automatically kept up to date.\n\t */\n\t@SuppressWarnings(\"serial\")\n\tprivate final Map<String, String> header = new HashMap<String, String>() {\n\n\t\tpublic String put(String key, String value) {\n\t\t\tlowerCaseHeader.put(key == null ? key : key.toLowerCase(), value);\n\t\t\treturn super.put(key, value);\n\t\t};\n\t};\n\n\t/**\n\t * copy of the header map with all the keys lowercase for faster\n\t * searching.\n\t */\n\tprivate final Map<String, String> lowerCaseHeader = new HashMap<String, String>();\n\n\t/**\n\t * The request method that spawned this response.\n\t */\n\tprivate Method requestMethod;\n\n\t/**\n\t * Use chunkedTransfer\n\t */\n\tprivate boolean chunkedTransfer;\n\n\tprivate boolean encodeAsGzip;\n\n\tprivate boolean keepAlive;\n\n\t/**\n\t * Creates a fixed length response if totalBytes>=0, otherwise chunked.\n\t */\n\tprotected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\tthis.status = status;\n\t\tthis.mimeType = mimeType;\n\t\tif (data == null) {\n\t\t\tthis.data = new ByteArrayInputStream(new byte[0]);\n\t\t\tthis.contentLength = 0L;\n\t\t} else {\n\t\t\tthis.data = data;\n\t\t\tthis.contentLength = totalBytes;\n\t\t}\n\t\tthis.chunkedTransfer = this.contentLength < 0;\n\t\tkeepAlive = true;\n\t}\n\n\t@Override\n\tpublic void close() throws IOException {\n\t\tif (this.data != null) {\n\t\t\tthis.data.close();\n\t\t}\n\t}\n\n\t/**\n\t * Adds given line to the header.\n\t */\n\tpublic void addHeader(String name, String value) {\n\t\tthis.header.put(name, value);\n\t}\n\n\t/**\n\t * Indicate to close the connection after the Response has been sent.\n\t * \n\t * @param close\n\t * {@code true} to hint connection closing, {@code false} to\n\t * let connection be closed by client.\n\t */\n\tpublic void closeConnection(boolean close) {\n\t\tif (close)\n\t\t\tthis.header.put(\"connection\", \"close\");\n\t\telse\n\t\t\tthis.header.remove(\"connection\");\n\t}\n\n\t/**\n\t * @return {@code true} if connection is to be closed after this\n\t * Response has been sent.\n\t */\n\tpublic boolean isCloseConnection() {\n\t\treturn \"close\".equals(getHeader(\"connection\"));\n\t}\n\n\tpublic InputStream getData() {\n\t\treturn this.data;\n\t}\n\n\tpublic String getHeader(String name) {\n\t\treturn this.lowerCaseHeader.get(name.toLowerCase());\n\t}\n\n\tpublic String getMimeType() {\n\t\treturn this.mimeType;\n\t}\n\n\tpublic Method getRequestMethod() {\n\t\treturn this.requestMethod;\n\t}\n\n\tpublic IStatus getStatus() {\n\t\treturn this.status;\n\t}\n\n\tpublic void setGzipEncoding(boolean encodeAsGzip) {\n\t\tthis.encodeAsGzip = encodeAsGzip;\n\t}\n\n\tpublic void setKeepAlive(boolean useKeepAlive) {\n\t\tthis.keepAlive = useKeepAlive;\n\t}\n\n\t/**\n\t * Sends given response to the socket.\n\t */\n\tprotected void send(OutputStream outputStream) {\n\t\tSimpleDateFormat gmtFrmt = new SimpleDateFormat(\"E, d MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n\t\tgmtFrmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n\t\ttry {\n\t\t\tif (this.status == null) {\n\t\t\t\tthrow new Error(\"sendResponse(): Status can't be null.\");\n\t\t\t}\n\t\t\tPrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);\n\t\t\tpw.append(\"HTTP/1.1 \").append(this.status.getDescription()).append(\" \\r\\n\");\n\t\t\tif (this.mimeType != null) {\n\t\t\t\tprintHeader(pw, \"Content-Type\", this.mimeType);\n\t\t\t}\n\t\t\tif (getHeader(\"date\") == null) {\n\t\t\t\tprintHeader(pw, \"Date\", gmtFrmt.format(new Date()));\n\t\t\t}\n\t\t\tfor (Entry<String, String> entry : this.header.entrySet()) {\n\t\t\t\tprintHeader(pw, entry.getKey(), entry.getValue());\n\t\t\t}\n\t\t\tif (getHeader(\"connection\") == null) {\n\t\t\t\tprintHeader(pw, \"Connection\", (this.keepAlive ? \"keep-alive\" : \"close\"));\n\t\t\t}\n\t\t\tif (getHeader(\"content-length\") != null) {\n\t\t\t\tencodeAsGzip = false;\n\t\t\t}\n\t\t\tif (encodeAsGzip) {\n\t\t\t\tprintHeader(pw, \"Content-Encoding\", \"gzip\");\n\t\t\t\tsetChunkedTransfer(true);\n\t\t\t}\n\t\t\tlong pending = this.data != null ? this.contentLength : 0;\n\t\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\t\tprintHeader(pw, \"Transfer-Encoding\", \"chunked\");\n\t\t\t} else if (!encodeAsGzip) {\n\t\t\t\tpending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);\n\t\t\t}\n\t\t\tpw.append(\"\\r\\n\");\n\t\t\tpw.flush();\n\t\t\tsendBodyWithCorrectTransferAndEncoding(outputStream, pending);\n\t\t\toutputStream.flush();\n\t\t\tsafeClose(this.data);\n\t\t} catch (IOException ioe) {\n\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Could not send response to the client\", ioe);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"static-method\")\n\tprotected void printHeader(PrintWriter pw, String key, String value) {\n\t\tpw.append(key).append(\": \").append(value).append(\"\\r\\n\");\n\t}\n\n\tprotected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) {\n\t\tString contentLengthString = getHeader(\"content-length\");\n\t\tlong size = defaultSize;\n\t\tif (contentLengthString != null) {\n\t\t\ttry {\n\t\t\t\tsize = Long.parseLong(contentLengthString);\n\t\t\t} catch (NumberFormatException ex) {\n\t\t\t\tLOG.severe(\"content-length was no number \" + contentLengthString);\n\t\t\t}\n\t\t}\n\t\tpw.print(\"Content-Length: \" + size + \"\\r\\n\");\n\t\treturn size;\n\t}\n\n\tprivate void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\tChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);\n\t\t\tsendBodyWithCorrectEncoding(chunkedOutputStream, -1);\n\t\t\tchunkedOutputStream.finish();\n\t\t} else {\n\t\t\tsendBodyWithCorrectEncoding(outputStream, pending);\n\t\t}\n\t}\n\n\tprivate void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\tif (encodeAsGzip) {\n\t\t\tGZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);\n\t\t\tsendBody(gzipOutputStream, -1);\n\t\t\tgzipOutputStream.finish();\n\t\t} else {\n\t\t\tsendBody(outputStream, pending);\n\t\t}\n\t}\n\n\t/**\n\t * Sends the body to the specified OutputStream. The pending parameter\n\t * limits the maximum amounts of bytes sent unless it is -1, in which\n\t * case everything is sent.\n\t * \n\t * @param outputStream\n\t * the OutputStream to send data to\n\t * @param pending\n\t * -1 to send everything, otherwise sets a max limit to the\n\t * number of bytes sent\n\t * @throws IOException\n\t * if something goes wrong while sending the data.\n\t */\n\tprivate void sendBody(OutputStream outputStream, long pending) throws IOException {\n\t\tlong BUFFER_SIZE = 16 * 1024;\n\t\tbyte[] buff = new byte[(int) BUFFER_SIZE];\n\t\tboolean sendEverything = pending == -1;\n\t\twhile (pending > 0 || sendEverything) {\n\t\t\tlong bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);\n\t\t\tint read = this.data.read(buff, 0, (int) bytesToRead);\n\t\t\tif (read <= 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutputStream.write(buff, 0, read);\n\t\t\tif (!sendEverything) {\n\t\t\t\tpending -= read;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setChunkedTransfer(boolean chunkedTransfer) {\n\t\tthis.chunkedTransfer = chunkedTransfer;\n\t}\n\n\tpublic void setData(InputStream data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic void setMimeType(String mimeType) {\n\t\tthis.mimeType = mimeType;\n\t}\n\n\tpublic void setRequestMethod(Method requestMethod) {\n\t\tthis.requestMethod = requestMethod;\n\t}\n\n\tpublic void setStatus(IStatus status) {\n\t\tthis.status = status;\n\t}\n}" ]
import java.io.File; import java.util.Iterator; import synapticloop.nanohttpd.router.Routable; import synapticloop.nanohttpd.router.RouteMaster; import synapticloop.nanohttpd.utils.HttpUtils; import fi.iki.elonen.NanoHTTPD.IHTTPSession; import fi.iki.elonen.NanoHTTPD.Response;
package synapticloop.nanohttpd.example.servant; /* * Copyright (c) 2013-2020 synapticloop. * * All rights reserved. * * This source code and any derived binaries are covered by the terms and * conditions of the Licence agreement ("the Licence"). You may not use this * source code or any derived binaries except in compliance with the Licence. * A copy of the Licence is available in the file named LICENCE shipped with * this source code or binaries. * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * Licence for the specific language governing permissions and limitations * under the Licence. */ public class ModulesRouteServant extends Routable { public ModulesRouteServant(String routeContext) { super(routeContext); } @Override
public Response serve(File rootDir, IHTTPSession httpSession) {
4
razerdp/FriendCircle
module_main/src/main/java/com/razerdp/github/module/main/ui/TimeLineFragment.java
[ "public abstract class BaseAppFragment extends BaseLibFragment {\n}", "public class RandomUtil {\n\n private static final String CHAR_LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n private static final String CHAR_NUMBER = \"0123456789\";\n private static final String CHAR_ALL = CHAR_NUMBER + CHAR_LETTERS;\n\n private static final Random RANDOM = new Random();\n\n /**\n * 产生长度为length的随机字符串(包括字母和数字)\n *\n * @param length\n * @return\n */\n public static String randomString(int length) {\n RANDOM.setSeed(System.currentTimeMillis());\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n sb.append(CHAR_ALL.charAt(RANDOM.nextInt(CHAR_ALL.length())));\n }\n return sb.toString();\n }\n\n public static String randomNonNumberString(int length) {\n StringBuilder sb = new StringBuilder();\n Random random = new Random();\n for (int i = 0; i < length; i++) {\n sb.append(CHAR_LETTERS.charAt(random.nextInt(CHAR_LETTERS.length())));\n }\n return sb.toString();\n }\n\n public static String randomLowerNonNumberString(int length) {\n return randomNonNumberString(length).toLowerCase();\n }\n\n public static String randomUpperNonNumberString(int length) {\n return randomNonNumberString(length).toUpperCase();\n }\n\n public static int randomInt(int min, int max) {\n RANDOM.setSeed(System.currentTimeMillis());\n return RANDOM.nextInt(max - min + 1) + min;\n }\n\n public static float randomFloat() {\n RANDOM.setSeed(System.currentTimeMillis());\n return RANDOM.nextFloat();\n }\n\n public static boolean randomBoolean() {\n return new Random().nextBoolean();\n }\n\n public static String randomIntString(int min, int max) {\n return String.valueOf(randomInt(min, max));\n }\n\n public static int randomColor() {\n return randomColor(false);\n }\n\n public static int randomColor(boolean withAlpha) {\n RANDOM.setSeed(System.currentTimeMillis());\n return withAlpha ?\n Color.rgb(RANDOM.nextInt(256), RANDOM.nextInt(256), RANDOM.nextInt(256))\n :\n Color.argb(RANDOM.nextInt(256), RANDOM.nextInt(256), RANDOM.nextInt(256), RANDOM.nextInt(256));\n }\n}", "public class UIHelper {\n\n public static int getColor(@ColorRes int colorResId) {\n try {\n return ContextCompat.getColor(AppContext.getAppContext(), colorResId);\n } catch (Exception e) {\n return Color.TRANSPARENT;\n }\n }\n\n\n public static void toast(@StringRes int textResId) {\n toast(StringUtil.getString(textResId));\n }\n\n public static void toast(String text) {\n toast(text, Toast.LENGTH_SHORT);\n }\n\n public static void toast(@StringRes int textResId, int duration) {\n toast(StringUtil.getString(textResId), duration);\n }\n\n public static void toast(String text, int duration) {\n Toast.makeText(AppContext.getAppContext(), text, duration).show();\n }\n\n public static int getNavigationBarHeight() {\n Resources resources = AppContext.getResources();\n int resourceId = resources.getIdentifier(\"navigation_bar_height\",\n \"dimen\", \"android\");\n if (resourceId > 0) {\n //获取NavigationBar的高度\n return resources.getDimensionPixelSize(resourceId);\n }\n return 0;\n }\n\n /**\n * 根据手机的分辨率从 dp 的单位 转成为 px(像素)\n */\n public static int dip2px(float dpValue) {\n final float scale = Resources.getSystem().getDisplayMetrics().density;\n return (int) (dpValue * scale + 0.5f);\n }\n\n /**\n * 根据手机的分辨率从 px(像素) 的单位 转成为 dp\n */\n public static int px2dip(float pxValue) {\n final float scale = Resources.getSystem().getDisplayMetrics().density;\n return (int) (pxValue / scale + 0.5f);\n }\n\n public static int sp2px(float spValue) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,\n spValue, Resources.getSystem().getDisplayMetrics());\n }\n\n public static int getScreenWidth() {\n return Resources.getSystem().getDisplayMetrics().widthPixels;\n }\n\n public static int getScreenHeight() {\n return Resources.getSystem().getDisplayMetrics().heightPixels;\n }\n}", "public abstract class BaseMultiRecyclerViewHolder<T extends MultiType> extends BaseRecyclerViewHolder<T> {\n public BaseMultiRecyclerViewHolder(@NonNull View itemView) {\n super(itemView);\n }\n\n public abstract int layoutId();\n}", "public class MultiRecyclerViewAdapter<T extends MultiType> extends BaseRecyclerViewAdapter<T> {\n\n private static HashMap<String, Integer> mViewHolderIdCache = new HashMap<>();\n private SparseArray<ViewHolderInfo> mHolderInfos = new SparseArray<>();\n private static final Class<?>[] INSTANCE_TYPE = {View.class};\n\n private WeakReference<Object> outher;\n\n public MultiRecyclerViewAdapter(Context context) {\n super(context);\n }\n\n public MultiRecyclerViewAdapter(Context context, List<T> datas) {\n super(context, datas);\n }\n\n public MultiRecyclerViewAdapter appendHolder(Class<? extends BaseMultiRecyclerViewHolder> holderClass) {\n return appendHolder(holderClass, holderClass.hashCode());\n }\n\n public MultiRecyclerViewAdapter appendHolder(Class<? extends BaseMultiRecyclerViewHolder> holderClass, int... viewType) {\n for (int i : viewType) {\n if (mHolderInfos.get(i) == null) {\n mHolderInfos.put(i, new ViewHolderInfo(holderClass, i));\n }\n }\n return this;\n }\n\n public MultiRecyclerViewAdapter outher(Object object) {\n this.outher = new WeakReference<>(object);\n return this;\n }\n\n @Override\n public int onGetViewType(T data, int position) {\n return data.getItemType();\n }\n\n @Override\n public int holderLayout(int viewType) {\n ViewHolderInfo info = mHolderInfos.get(viewType);\n return info == null ? 0 : info.getLayoutId();\n }\n\n @NonNull\n @Override\n public BaseRecyclerViewHolder createViewHolder(@NonNull ViewGroup parent, @NonNull View itemView, int viewType) {\n KLog.i(TAG, \"创建multitype viewholder:\", viewType);\n if (mHolderInfos.size() < 0) {\n KLog.e(TAG, \"holder没有注册,请调用#appendHolder添加holder信息\");\n return createEmptyHolder();\n }\n ViewHolderInfo info = mHolderInfos.get(viewType);\n if (info == null) {\n KLog.e(TAG, \"无法获取该viewType的holder信息\", viewType);\n return createEmptyHolder();\n }\n final int id = info.getLayoutId();\n\n if (id == 0) {\n KLog.e(TAG, \"id为0\", info.getHolderClass());\n return createEmptyHolder();\n }\n\n if (itemView == null) {\n itemView = ViewUtil.inflate(id, parent, false);\n }\n\n try {\n return Reflect.on(info.getHolderClass()).create(INSTANCE_TYPE, itemView).get();\n } catch (ReflectException e) {\n //考虑到非静态内部类的情况,创建viewholder的时候需要传入外部类的对象\n if (outher != null && outher.get() != null) {\n //如果是创建在内部类里面的viewholder,则需要绑定outher\n Class<?>[] types = {outher.get().getClass(), View.class};\n return Reflect.on(info.getHolderClass()).create(types, outher.get(), itemView).get();\n }\n //其余情况皆是Context的内部类\n Class<?>[] types = {getContext().getClass(), View.class};\n return Reflect.on(info.getHolderClass()).create(types, getContext(), itemView).get();\n }\n }\n\n\n private static class ViewHolderInfo {\n final Class<? extends BaseMultiRecyclerViewHolder> mHolderClass;\n final int viewType;\n\n int layoutId;\n\n public ViewHolderInfo(Class<? extends BaseMultiRecyclerViewHolder> holderClass, int viewType) {\n mHolderClass = holderClass;\n this.viewType = viewType;\n }\n\n public int getLayoutId() {\n if (layoutId == 0) {\n searchLayout();\n }\n return layoutId;\n }\n\n public Class<? extends BaseMultiRecyclerViewHolder> getHolderClass() {\n return mHolderClass;\n }\n\n public int getViewType() {\n return viewType;\n }\n\n static String generateKey(Class clazz, int viewType) {\n return clazz.getName() + \"$Type:\" + viewType;\n }\n\n void searchLayout() {\n if (layoutId != 0) return;\n if (mHolderClass != null) {\n final String key = generateKey(mHolderClass, viewType);\n if (mViewHolderIdCache.containsKey(key)) {\n layoutId = mViewHolderIdCache.get(key);\n if (layoutId != 0) {\n KLog.i(\"ViewHolderInfo\", \"id from cache : \" + layoutId);\n return;\n }\n }\n //利用unsafe绕过构造器创建对象,该对象仅用于获取layoutid\n BaseMultiRecyclerViewHolder holder = UnsafeUtil.unsafeInstance(mHolderClass);\n if (holder == null) return;\n layoutId = holder.layoutId();\n if (layoutId != 0) {\n mViewHolderIdCache.put(key, layoutId);\n }\n holder = null;\n }\n }\n }\n}", "public class SimpleMultiType implements MultiType {\n\n int type;\n\n public SimpleMultiType(int type) {\n this.type = type;\n }\n\n @Override\n public int getItemType() {\n return type;\n }\n}", "public interface OnItemClickListener<T> {\n\n void onItemClick(View v, int position, T data);\n}", "public interface OnItemLongClickListener<T> {\n\n void onItemLongClick(View v, int position, T data);\n}" ]
import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.razerdp.github.common.base.BaseAppFragment; import com.razerdp.github.lib.utils.RandomUtil; import com.razerdp.github.lib.utils.UIHelper; import com.razerdp.github.module.main.R; import com.razerdp.github.module.main.R2; import com.razerdp.github.uilib.base.adapter.BaseMultiRecyclerViewHolder; import com.razerdp.github.uilib.base.adapter.MultiRecyclerViewAdapter; import com.razerdp.github.uilib.base.adapter.SimpleMultiType; import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener; import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView;
package com.razerdp.github.module.main.ui; /** * Created by 大灯泡 on 2019/8/3. * <p> * 朋友圈时间线fragment */ public class TimeLineFragment extends BaseAppFragment { @BindView(R2.id.rv_content) RecyclerView mRvContent; @Override public int layoutId() { return R.layout.fragment_time_line; } @Override protected void onInitView(View rootView) { List<SimpleMultiType> multiTypes = new ArrayList<>(); int[] types = {1, 2, 3};
for (int i = 0; i < RandomUtil.randomInt(100, 500); i++) {
1
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/parser/Reader.java
[ "public class BigIntegerSyntax extends Syntax<BigInteger> {\n\tpublic BigIntegerSyntax(BigInteger value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}", "public class BooleanSyntax extends Syntax<Boolean> {\n\tpublic BooleanSyntax(boolean value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}", "public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> {\n public ListSyntax(MumblerList<? extends Syntax<?>> value,\n SourceSection sourceSection) {\n super(value, sourceSection);\n }\n\n @Override\n public Object strip() {\n List<Object> list = new ArrayList<Object>();\n for (Syntax<? extends Object> syntax : getValue()) {\n list.add(syntax.strip());\n }\n return MumblerList.list(list);\n }\n\n @Override\n public String getName() {\n if (super.getName() != null) {\n return super.getName();\n }\n if (this.getValue().size() == 0) {\n return \"()\";\n }\n return this.getValue().car().getValue().toString() + \"-\" + this.hashCode();\n }\n}", "public class LongSyntax extends Syntax<Long> {\n\tpublic LongSyntax(long value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}", "public class StringSyntax extends Syntax<String> {\n\tpublic StringSyntax(String value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}", "public class SymbolSyntax extends Syntax<MumblerSymbol> {\n\tpublic SymbolSyntax(MumblerSymbol value, SourceSection source) {\n\t\tsuper(value, source);\n\t}\n}", "public class MumblerList<T extends Object> implements Iterable<T> {\n public static final MumblerList<?> EMPTY = new MumblerList<>();\n\n private final T car;\n private final MumblerList<T> cdr;\n private final int length;\n\n private MumblerList() {\n this.car = null;\n this.cdr = null;\n this.length = 0;\n }\n\n private MumblerList(T car, MumblerList<T> cdr) {\n this.car = car;\n this.cdr = cdr;\n this.length = cdr.length + 1;\n }\n\n @SafeVarargs\n public static <T> MumblerList<T> list(T... objs) {\n return list(asList(objs));\n }\n\n public static <T> MumblerList<T> list(List<T> objs) {\n @SuppressWarnings(\"unchecked\")\n MumblerList<T> l = (MumblerList<T>) EMPTY;\n for (int i=objs.size()-1; i>=0; i--) {\n l = l.cons(objs.get(i));\n }\n return l;\n }\n\n public MumblerList<T> cons(T node) {\n return new MumblerList<T>(node, this);\n }\n\n public T car() {\n if (this != EMPTY) {\n return this.car;\n }\n throw new MumblerException(\"Cannot car the empty list\");\n }\n\n public MumblerList<T> cdr() {\n if (this != EMPTY) {\n return this.cdr;\n }\n throw new MumblerException(\"Cannot cdr the empty list\");\n }\n\n public long size() {\n return this.length;\n }\n\n @Override\n public Iterator<T> iterator() {\n return new Iterator<T>() {\n private MumblerList<T> l = MumblerList.this;\n\n @Override\n public boolean hasNext() {\n return this.l != EMPTY;\n }\n\n @Override\n public T next() {\n if (this.l == EMPTY) {\n throw new MumblerException(\"At end of list\");\n }\n T car = this.l.car;\n this.l = this.l.cdr;\n return car;\n }\n\n @Override\n public void remove() {\n throw new MumblerException(\"Iterator is immutable\");\n }\n };\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof MumblerList)) {\n return false;\n }\n if (this == EMPTY && other == EMPTY) {\n return true;\n }\n\n MumblerList<?> that = (MumblerList<?>) other;\n if (this.cdr == EMPTY && that.cdr != EMPTY) {\n return false;\n }\n return this.car.equals(that.car) && this.cdr.equals(that.cdr);\n }\n\n @Override\n public String toString() {\n if (this == EMPTY) {\n return \"()\";\n }\n\n StringBuilder b = new StringBuilder(\"(\" + this.car);\n MumblerList<T> rest = this.cdr;\n while (rest != null && rest != EMPTY) {\n b.append(\" \");\n b.append(rest.car);\n rest = rest.cdr;\n }\n b.append(\")\");\n return b.toString();\n }\n}", "public class MumblerSymbol {\n public final String name;\n\n public MumblerSymbol(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return this.name;\n }\n}" ]
import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import mumbler.truffle.syntax.BigIntegerSyntax; import mumbler.truffle.syntax.BooleanSyntax; import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.LongSyntax; import mumbler.truffle.syntax.StringSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList; import mumbler.truffle.type.MumblerSymbol; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection;
package mumbler.truffle.parser; public class Reader extends MumblerBaseVisitor<Syntax<?>> { public static ListSyntax read(Source source) throws IOException { return (ListSyntax) new Reader(source) .visit(createParseTree(source.getInputStream())); } public static Syntax<?> readForm(Source source) throws IOException { return ((ListSyntax) new Reader(source).visit( createParseTree(source.getInputStream()))) .getValue() .car(); } private static ParseTree createParseTree(InputStream istream) throws IOException { ANTLRInputStream input = new ANTLRInputStream(istream); MumblerLexer lexer = new MumblerLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); MumblerParser parser = new MumblerParser(tokens); return parser.file(); } private final Source source; private Reader(Source source) { this.source = source; } @Override public ListSyntax visitFile(MumblerParser.FileContext ctx) { List<Syntax<?>> forms = new ArrayList<>(); for (MumblerParser.FormContext form : ctx.form()) { forms.add(this.visit(form)); } return new ListSyntax(MumblerList.list(forms), createSourceSection(ctx)); } @Override public ListSyntax visitList(MumblerParser.ListContext ctx) { List<Syntax<?>> forms = new ArrayList<>(); for (MumblerParser.FormContext form : ctx.form()) { forms.add(this.visit(form)); } return new ListSyntax(MumblerList.list(forms), createSourceSection(ctx)); } @Override public Syntax<?> visitNumber(MumblerParser.NumberContext ctx) { try { return new LongSyntax(Long.valueOf(ctx.getText(), 10), createSourceSection(ctx)); } catch (NumberFormatException e) { return new BigIntegerSyntax(new BigInteger(ctx.getText()), createSourceSection(ctx)); } } private SourceSection createSourceSection(ParserRuleContext ctx) { return source.createSection( ctx.start.getLine(), ctx.start.getCharPositionInLine() + 1, ctx.stop.getStopIndex() - ctx.start.getStartIndex()); } @Override public BooleanSyntax visitBool(MumblerParser.BoolContext ctx) { return new BooleanSyntax("#t".equals(ctx.getText()), createSourceSection(ctx)); } @Override public SymbolSyntax visitSymbol(MumblerParser.SymbolContext ctx) { return new SymbolSyntax(new MumblerSymbol(ctx.getText()), createSourceSection(ctx)); } @Override public ListSyntax visitQuote(MumblerParser.QuoteContext ctx) { return new ListSyntax(MumblerList.list( new SymbolSyntax(new MumblerSymbol("quote"), createSourceSection(ctx)), this.visit(ctx.form())), createSourceSection(ctx)); } @Override
public StringSyntax visitString(MumblerParser.StringContext ctx) {
4
la-team/lightadmin-jhipster
src/test/java/org/lightadmin/jhipster/web/rest/AccountResourceTest.java
[ "@ComponentScan\n@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})\npublic class Application {\n\n private final Logger log = LoggerFactory.getLogger(Application.class);\n\n @Inject\n private Environment env;\n\n /**\n * Initializes lightadmin-jhipster.\n * <p/>\n * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile\n * <p/>\n */\n @PostConstruct\n public void initApplication() throws IOException {\n if (env.getActiveProfiles().length == 0) {\n log.warn(\"No Spring profile configured, running with default configuration\");\n } else {\n log.info(\"Running with Spring profile(s) : {}\", Arrays.toString(env.getActiveProfiles()));\n }\n }\n\n /**\n * Main method, used to run the application.\n *\n * To run the application with hot reload enabled, add the following arguments to your JVM:\n * \"-javaagent:spring_loaded/springloaded-jhipster.jar -noverify -Dspringloaded=plugins=io.github.jhipster.loaded.instrument.JHipsterLoadtimeInstrumentationPlugin\"\n */\n public static void main(String[] args) {\n SpringApplication app = new SpringApplication(Application.class);\n app.setShowBanner(false);\n\n SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);\n\n // Check if the selected profile has been set as argument.\n // if not the development profile will be added\n addDefaultProfile(app, source);\n\n app.run(args);\n }\n\n /**\n * Set a default profile if it has not been set\n */\n private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {\n if (!source.containsProperty(\"spring.profiles.active\")) {\n app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);\n }\n }\n}", "@Entity\n@Table(name = \"T_AUTHORITY\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\npublic class Authority implements Serializable {\n\n @NotNull\n @Size(min = 0, max = 50)\n @Id\n private String name;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n Authority authority = (Authority) o;\n\n if (name != null ? !name.equals(authority.name) : authority.name != null) {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return name != null ? name.hashCode() : 0;\n }\n\n @Override\n public String toString() {\n return \"Authority{\" +\n \"name='\" + name + '\\'' +\n \"}\";\n }\n}", "@Entity\n@Table(name = \"T_USER\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\npublic class User extends AbstractAuditingEntity implements Serializable {\n\n @NotNull\n @Size(min = 0, max = 50)\n @Id\n private String login;\n\n @JsonIgnore\n @Size(min = 0, max = 100)\n private String password;\n\n @Size(min = 0, max = 50)\n @Column(name = \"first_name\")\n private String firstName;\n\n @Size(min = 0, max = 50)\n @Column(name = \"last_name\")\n private String lastName;\n\n @Email\n @Size(min = 0, max = 100)\n private String email;\n\n @NotNull\n private Boolean activated = false;\n\n @Size(min = 2, max = 5)\n @Column(name = \"lang_key\")\n private String langKey;\n\n @Size(min = 0, max = 20)\n @Column(name = \"activation_key\")\n private String activationKey;\n\n @JsonIgnore\n @ManyToMany\n @JoinTable(\n name = \"T_USER_AUTHORITY\",\n joinColumns = {@JoinColumn(name = \"login\", referencedColumnName = \"login\")},\n inverseJoinColumns = {@JoinColumn(name = \"name\", referencedColumnName = \"name\")})\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private Set<Authority> authorities = new HashSet<>();\n\n @JsonIgnore\n @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = \"user\")\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private Set<PersistentToken> persistentTokens = new HashSet<>();\n\n public String getLogin() {\n return login;\n }\n\n public void setLogin(String login) {\n this.login = login;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public Boolean getActivated() {\n return activated;\n }\n\n public void setActivated(Boolean activated) {\n this.activated = activated;\n }\n\n public String getActivationKey() {\n return activationKey;\n }\n\n public void setActivationKey(String activationKey) {\n this.activationKey = activationKey;\n }\n\n public String getLangKey() {\n return langKey;\n }\n\n public void setLangKey(String langKey) {\n this.langKey = langKey;\n }\n\n public Set<Authority> getAuthorities() {\n return authorities;\n }\n\n public void setAuthorities(Set<Authority> authorities) {\n this.authorities = authorities;\n }\n \n public Set<PersistentToken> getPersistentTokens() {\n return persistentTokens;\n }\n\n public void setPersistentTokens(Set<PersistentToken> persistentTokens) {\n this.persistentTokens = persistentTokens;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n User user = (User) o;\n\n if (!login.equals(user.login)) {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return login.hashCode();\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"login='\" + login + '\\'' +\n \", password='\" + password + '\\'' +\n \", firstName='\" + firstName + '\\'' +\n \", lastName='\" + lastName + '\\'' +\n \", email='\" + email + '\\'' +\n \", activated='\" + activated + '\\'' +\n \", langKey='\" + langKey + '\\'' +\n \", activationKey='\" + activationKey + '\\'' +\n \"}\";\n }\n}", "public interface UserRepository extends JpaRepository<User, String> {\n \n @Query(\"select u from User u where u.activationKey = ?1\")\n User getUserByActivationKey(String activationKey);\n \n @Query(\"select u from User u where u.activated = false and u.createdDate > ?1\")\n List<User> findNotActivatedUsersByCreationDateBefore(DateTime dateTime);\n\n}", "public final class AuthoritiesConstants {\n\n private AuthoritiesConstants() {\n }\n\n public static final String ADMIN = \"ROLE_ADMIN\";\n\n public static final String USER = \"ROLE_USER\";\n\n public static final String ANONYMOUS = \"ROLE_ANONYMOUS\";\n}", "@Service\n@Transactional\npublic class UserService {\n\n private final Logger log = LoggerFactory.getLogger(UserService.class);\n\n @Inject\n private PasswordEncoder passwordEncoder;\n\n @Inject\n private UserRepository userRepository;\n\n @Inject\n private PersistentTokenRepository persistentTokenRepository;\n\n @Inject\n private AuthorityRepository authorityRepository;\n\n public User activateRegistration(String key) {\n log.debug(\"Activating user for activation key {}\", key);\n User user = userRepository.getUserByActivationKey(key);\n\n // activate given user for the registration key.\n if (user != null) {\n user.setActivated(true);\n user.setActivationKey(null);\n userRepository.save(user);\n log.debug(\"Activated user: {}\", user);\n }\n return user;\n }\n\n public User createUserInformation(String login, String password, String firstName, String lastName, String email,\n String langKey) {\n User newUser = new User();\n Authority authority = authorityRepository.findOne(\"ROLE_USER\");\n Set<Authority> authorities = new HashSet<Authority>();\n String encryptedPassword = passwordEncoder.encode(password);\n newUser.setLogin(login);\n // new user gets initially a generated password\n newUser.setPassword(encryptedPassword);\n newUser.setFirstName(firstName);\n newUser.setLastName(lastName);\n newUser.setEmail(email);\n newUser.setLangKey(langKey);\n // new user is not active\n newUser.setActivated(false);\n // new user gets registration key\n newUser.setActivationKey(RandomUtil.generateActivationKey());\n authorities.add(authority);\n newUser.setAuthorities(authorities);\n userRepository.save(newUser);\n log.debug(\"Created Information for User: {}\", newUser);\n return newUser;\n }\n\n public void updateUserInformation(String firstName, String lastName, String email) {\n User currentUser = userRepository.findOne(SecurityUtils.getCurrentLogin());\n currentUser.setFirstName(firstName);\n currentUser.setLastName(lastName);\n currentUser.setEmail(email);\n userRepository.save(currentUser);\n log.debug(\"Changed Information for User: {}\", currentUser);\n }\n\n public void changePassword(String password) {\n User currentUser = userRepository.findOne(SecurityUtils.getCurrentLogin());\n String encryptedPassword = passwordEncoder.encode(password);\n currentUser.setPassword(encryptedPassword);\n userRepository.save(currentUser);\n log.debug(\"Changed password for User: {}\", currentUser);\n }\n\n @Transactional(readOnly = true)\n public User getUserWithAuthorities() {\n User currentUser = userRepository.findOne(SecurityUtils.getCurrentLogin());\n currentUser.getAuthorities().size(); // eagerly load the association\n return currentUser;\n }\n\n /**\n * Persistent Token are used for providing automatic authentication, they should be automatically deleted after\n * 30 days.\n * <p/>\n * <p>\n * This is scheduled to get fired everyday, at midnight.\n * </p>\n */\n @Scheduled(cron = \"0 0 0 * * ?\")\n public void removeOldPersistentTokens() {\n LocalDate now = new LocalDate();\n List<PersistentToken> tokens = persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1));\n for (PersistentToken token : tokens) {\n log.debug(\"Deleting token {}\", token.getSeries());\n User user = token.getUser();\n user.getPersistentTokens().remove(token);\n persistentTokenRepository.delete(token);\n }\n }\n\n /**\n * Not activated users should be automatically deleted after 3 days.\n * <p/>\n * <p>\n * This is scheduled to get fired everyday, at 01:00 (am).\n * </p>\n */\n @Scheduled(cron = \"0 0 1 * * ?\")\n public void removeNotActivatedUsers() {\n DateTime now = new DateTime();\n List<User> users = userRepository.findNotActivatedUsersByCreationDateBefore(now.minusDays(3));\n for (User user : users) {\n log.debug(\"Deleting not activated user {}\", user.getLogin());\n userRepository.delete(user);\n }\n }\n}" ]
import org.lightadmin.jhipster.Application; import org.lightadmin.jhipster.domain.Authority; import org.lightadmin.jhipster.domain.User; import org.lightadmin.jhipster.repository.UserRepository; import org.lightadmin.jhipster.security.AuthoritiesConstants; import org.lightadmin.jhipster.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.inject.Inject; import java.util.HashSet; import java.util.Set; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
package org.lightadmin.jhipster.web.rest; /** * Test class for the AccountResource REST controller. * * @see UserService */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @ActiveProfiles("dev") public class AccountResourceTest { @Inject private UserRepository userRepository; @Mock
private UserService userService;
5
zhengjunbase/codehelper.generator
src/main/java/com/ccnode/codegenerator/genCode/GenTestService.java
[ "public class GenCodeResponse extends BaseResponse {\n\n Map<String,String> userConfigMap = Maps.newHashMap();\n\n GenCodeConfig codeConfig;\n\n DirectoryConfig directoryConfig;\n\n List<OnePojoInfo> pojoInfos = Lists.newArrayList();\n\n GenCodeRequest request;\n\n String pathSplitter;\n\n List<ChangeInfo> newFiles = Lists.newArrayList();\n\n List<ChangeInfo> updateFiles = Lists.newArrayList();\n\n Throwable throwable;\n\n ServerMsg serverMsg;\n\n public String getConfig(String key, String defaultValue) {\n if(StringUtils.isBlank(key) || userConfigMap == null){\n return defaultValue;\n }\n String value = userConfigMap.get(key);\n if(StringUtils.isBlank(value)){\n return defaultValue;\n }else{\n return value;\n }\n }\n\n public GenCodeResponse() {\n }\n\n public DirectoryConfig getDirectoryConfig() {\n return directoryConfig;\n }\n\n public void setDirectoryConfig(DirectoryConfig directoryConfig) {\n this.directoryConfig = directoryConfig;\n }\n\n public Map<String, String> getUserConfigMap() {\n return userConfigMap;\n }\n\n public void setUserConfigMap(Map<String, String> userConfigMap) {\n this.userConfigMap = userConfigMap;\n }\n\n public List<OnePojoInfo> getPojoInfos() {\n return pojoInfos;\n }\n\n public void setPojoInfos(List<OnePojoInfo> pojoInfos) {\n this.pojoInfos = pojoInfos;\n }\n\n public GenCodeRequest getRequest() {\n return request;\n }\n\n public void setRequest(GenCodeRequest request) {\n this.request = request;\n }\n\n public GenCodeConfig getCodeConfig() {\n return codeConfig;\n }\n\n public void setCodeConfig(GenCodeConfig codeConfig) {\n this.codeConfig = codeConfig;\n }\n\n public String getPathSplitter() {\n return pathSplitter;\n }\n\n public void setPathSplitter(String pathSplitter) {\n this.pathSplitter = pathSplitter;\n }\n\n public List<ChangeInfo> getNewFiles() {\n return newFiles;\n }\n\n public void setNewFiles(List<ChangeInfo> newFiles) {\n this.newFiles = newFiles;\n }\n\n public List<ChangeInfo> getUpdateFiles() {\n return updateFiles;\n }\n\n public void setUpdateFiles(List<ChangeInfo> updateFiles) {\n this.updateFiles = updateFiles;\n }\n\n public Throwable getThrowable() {\n return throwable;\n }\n\n public void setThrowable(Throwable throwable) {\n this.throwable = throwable;\n this.setMsg(throwable.getMessage());\n }\n\n public ServerMsg getServerMsg() {\n return serverMsg;\n }\n\n public void setServerMsg(ServerMsg serverMsg) {\n this.serverMsg = serverMsg;\n }\n}", "public class LoggerWrapper implements Logger {\n\n public static List<String> logList = Lists.newArrayList(\n \"\", \"---------------------- start -------------------------\");\n\n public static List<String> errorList = Lists.newArrayList(\n \"\", \"---------------------- start -------------------------\"\n );\n\n public LoggerWrapper() {\n\n }\n\n public static void saveAllLogs(String projectPath) {\n try{\n String firstMatch = MapHelper.getFirstMatch(UserConfigService.userConfigMap, \"printLog\", \"printlog\", \"debug\");\n if(!StringUtils.endsWithIgnoreCase(firstMatch,\"true\") || StringUtils.isBlank(projectPath)){\n return;\n }\n logList.add(\"---------------------- end -------------------------\");\n if(!projectPath.endsWith(GenCodeResponseHelper.getPathSplitter())){\n projectPath = projectPath + GenCodeResponseHelper.getPathSplitter();\n }\n String path = projectPath + \"codehelper.generator.log\";\n File logFile = new File(path);\n List<String> allLines = Lists.newArrayList();\n if(logFile.exists()){\n List<String> oldLines = IOUtils.readLines(path);\n if(oldLines !=null && !oldLines.isEmpty()){\n allLines.addAll(oldLines);\n }\n }\n allLines.addAll(logList);\n IOUtils.writeLines(new File(path),allLines);\n }catch(Throwable ignored){\n\n }\n\n }\n\n public static Logger getLogger(Class clazz){\n return new LoggerWrapper();\n }\n\n @Override\n public String getName() {\n return \"LOGGER\";\n }\n\n @Override\n public void trace(String msg) {\n }\n\n private String format(String format, Object... objects) {\n StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];\n List<String> splits = Splitter.on(\".\").splitToList(stackTraceElement.getClassName());\n String className = splits.get(splits.size() - 1);\n String methodName = stackTraceElement.getMethodName();\n String logLevel = Thread.currentThread().getStackTrace()[2].getMethodName().toUpperCase();\n format = format.replace(\"{}\", \"%s\");\n format = format.replace(\"{ }\", \"%s\");\n for (Object object : objects) {\n if (format.contains(\"%s\")) {\n format = StringUtils.replaceOnce(format, \"%s\", \" \" + LogHelper.toString(object) + \" \");\n } else {\n format += format + \" \" + LogHelper.toString(object);\n }\n }\n // TODO: 7/26/16 add dateUtil\n String logContent = DateUtil.formatLong(new Date()) + \" [\" + className + \".\" + methodName + \"] \" + \"[\" + logLevel + \"] \" + format;\n logList.add(logContent);\n if(\"error\".equalsIgnoreCase(logLevel)){\n errorList.add(logContent);\n }\n return format;\n }\n\n @Override\n public void trace(String msg, Throwable t) {\n\n }\n\n @Override\n public void info(String msg) {\n\n format(msg);\n\n }\n\n @Override\n public void info(String format, Object arg) {\n\n format(format, arg);\n\n }\n\n @Override\n public void info(String format, Object arg1, Object arg2) {\n\n format(format, arg1, arg2);\n\n }\n\n @Override\n public void info(String format, Object... arguments) {\n\n format(format, arguments);\n\n }\n\n @Override\n public void info(String msg, Throwable t) {\n\n format(msg, t);\n\n }\n\n @Override\n public void info(Marker marker, String msg) {\n\n }\n\n @Override\n public void info(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void info(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void info(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void info(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public void error(String msg) {\n\n format(msg);\n\n }\n\n @Override\n public void error(String format, Object arg) {\n\n format(format, arg);\n\n }\n\n @Override\n public void error(String format, Object arg1, Object arg2) {\n format(format, arg1, arg2);\n }\n\n @Override\n public void error(String format, Object... arguments) {\n format(format, arguments);\n }\n\n @Override\n public void error(String msg, Throwable t) {\n format(msg, t);\n }\n\n @Override\n public void error(Marker marker, String msg) {\n\n }\n\n @Override\n public void error(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void error(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void error(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void error(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public void trace(String format, Object arg) {\n\n }\n\n @Override\n public void trace(String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void trace(String format, Object... arguments) {\n\n }\n\n @Override\n public boolean isTraceEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public void trace(Marker marker, String msg) {\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object... argArray) {\n\n }\n\n @Override\n public void trace(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isDebugEnabled() {\n return false;\n }\n\n @Override\n public void debug(String msg) {\n\n }\n\n @Override\n public void debug(String format, Object arg) {\n\n }\n\n @Override\n public void debug(String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void debug(String format, Object... arguments) {\n\n }\n\n @Override\n public void debug(String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isDebugEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public void debug(Marker marker, String msg) {\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void debug(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isInfoEnabled() {\n return false;\n }\n\n @Override\n public boolean isWarnEnabled() {\n return false;\n }\n\n @Override\n public void warn(String msg) {\n\n }\n\n @Override\n public void warn(String format, Object arg) {\n\n }\n\n @Override\n public void warn(String format, Object... arguments) {\n\n }\n\n @Override\n public void warn(String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void warn(String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isWarnEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public void warn(Marker marker, String msg) {\n\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void warn(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void warn(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isInfoEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public boolean isErrorEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public boolean isTraceEnabled() {\n return false;\n }\n\n @Override\n public boolean isErrorEnabled() {\n return false;\n }\n}", "public class GenCodeResponse extends BaseResponse {\n\n Map<String,String> userConfigMap = Maps.newHashMap();\n\n GenCodeConfig codeConfig;\n\n DirectoryConfig directoryConfig;\n\n List<OnePojoInfo> pojoInfos = Lists.newArrayList();\n\n GenCodeRequest request;\n\n String pathSplitter;\n\n List<ChangeInfo> newFiles = Lists.newArrayList();\n\n List<ChangeInfo> updateFiles = Lists.newArrayList();\n\n Throwable throwable;\n\n ServerMsg serverMsg;\n\n public String getConfig(String key, String defaultValue) {\n if(StringUtils.isBlank(key) || userConfigMap == null){\n return defaultValue;\n }\n String value = userConfigMap.get(key);\n if(StringUtils.isBlank(value)){\n return defaultValue;\n }else{\n return value;\n }\n }\n\n public GenCodeResponse() {\n }\n\n public DirectoryConfig getDirectoryConfig() {\n return directoryConfig;\n }\n\n public void setDirectoryConfig(DirectoryConfig directoryConfig) {\n this.directoryConfig = directoryConfig;\n }\n\n public Map<String, String> getUserConfigMap() {\n return userConfigMap;\n }\n\n public void setUserConfigMap(Map<String, String> userConfigMap) {\n this.userConfigMap = userConfigMap;\n }\n\n public List<OnePojoInfo> getPojoInfos() {\n return pojoInfos;\n }\n\n public void setPojoInfos(List<OnePojoInfo> pojoInfos) {\n this.pojoInfos = pojoInfos;\n }\n\n public GenCodeRequest getRequest() {\n return request;\n }\n\n public void setRequest(GenCodeRequest request) {\n this.request = request;\n }\n\n public GenCodeConfig getCodeConfig() {\n return codeConfig;\n }\n\n public void setCodeConfig(GenCodeConfig codeConfig) {\n this.codeConfig = codeConfig;\n }\n\n public String getPathSplitter() {\n return pathSplitter;\n }\n\n public void setPathSplitter(String pathSplitter) {\n this.pathSplitter = pathSplitter;\n }\n\n public List<ChangeInfo> getNewFiles() {\n return newFiles;\n }\n\n public void setNewFiles(List<ChangeInfo> newFiles) {\n this.newFiles = newFiles;\n }\n\n public List<ChangeInfo> getUpdateFiles() {\n return updateFiles;\n }\n\n public void setUpdateFiles(List<ChangeInfo> updateFiles) {\n this.updateFiles = updateFiles;\n }\n\n public Throwable getThrowable() {\n return throwable;\n }\n\n public void setThrowable(Throwable throwable) {\n this.throwable = throwable;\n this.setMsg(throwable.getMessage());\n }\n\n public ServerMsg getServerMsg() {\n return serverMsg;\n }\n\n public void setServerMsg(ServerMsg serverMsg) {\n this.serverMsg = serverMsg;\n }\n}", "public class OnePojoInfo {\n\n List<GeneratedFile> files;\n List<PojoFieldInfo> pojoFieldInfos;\n GenCodeConfig genCodeConfig;\n DirectoryConfig directoryConfig;\n PsiClassImpl psiClass;\n Class pojoClass;\n String pojoName;\n String pojoPackage;\n String daoPackage;\n String servicePackage;\n String pojoDirPath;\n String fullPojoPath;\n String fullDaoPath;\n String fullServicePath;\n String fullSqlPath;\n String fullMapperPath;\n String pojoClassSimpleName;\n String suffix;\n String idType;\n\n public String getPojoName() {\n return pojoName;\n }\n\n public void setPojoName(String pojoName) {\n this.pojoName = pojoName;\n }\n\n public DirectoryConfig getDirectoryConfig() {\n return directoryConfig;\n }\n\n public void setDirectoryConfig(DirectoryConfig directoryConfig) {\n this.directoryConfig = directoryConfig;\n }\n\n public List<GeneratedFile> getFiles() {\n return files;\n }\n\n public void setFiles(List<GeneratedFile> files) {\n this.files = files;\n }\n\n public List<PojoFieldInfo> getPojoFieldInfos() {\n return pojoFieldInfos;\n }\n\n public void setPojoFieldInfos(List<PojoFieldInfo> pojoFieldInfos) {\n this.pojoFieldInfos = pojoFieldInfos;\n }\n\n public GenCodeConfig getGenCodeConfig() {\n return genCodeConfig;\n }\n\n public void setGenCodeConfig(GenCodeConfig genCodeConfig) {\n this.genCodeConfig = genCodeConfig;\n }\n\n public Class getPojoClass() {\n return pojoClass;\n }\n\n public void setPojoClass(@Nullable Class pojoClass) {\n this.pojoClass = pojoClass;\n }\n\n public String getFullPojoPath() {\n return fullPojoPath;\n }\n\n public void setFullPojoPath(String fullPojoPath) {\n this.fullPojoPath = fullPojoPath;\n }\n\n public String getPojoPackage() {\n return pojoPackage;\n }\n\n public void setPojoPackage(String pojoPackage) {\n this.pojoPackage = pojoPackage;\n }\n\n public String getDaoPackage() {\n return daoPackage;\n }\n\n public void setDaoPackage(String daoPackage) {\n this.daoPackage = daoPackage;\n }\n\n public String getServicePackage() {\n return servicePackage;\n }\n\n public void setServicePackage(String servicePackage) {\n this.servicePackage = servicePackage;\n }\n\n public String getPojoClassSimpleName() {\n return pojoClassSimpleName;\n }\n\n public void setPojoClassSimpleName(String pojoClassSimpleName) {\n this.pojoClassSimpleName = pojoClassSimpleName;\n }\n\n public PsiClassImpl getPsiClass() {\n return psiClass;\n }\n\n public void setPsiClass(PsiClassImpl psiClass) {\n this.psiClass = psiClass;\n }\n\n public String getFullDaoPath() {\n return fullDaoPath;\n }\n\n public void setFullDaoPath(String fullDaoPath) {\n this.fullDaoPath = fullDaoPath;\n }\n\n public String getFullServicePath() {\n return fullServicePath;\n }\n\n public void setFullServicePath(String fullServicePath) {\n this.fullServicePath = fullServicePath;\n }\n\n public String getFullSqlPath() {\n return fullSqlPath;\n }\n\n public void setFullSqlPath(String fullSqlPath) {\n this.fullSqlPath = fullSqlPath;\n }\n\n public String getFullMapperPath() {\n return fullMapperPath;\n }\n\n public void setFullMapperPath(String fullMapperPath) {\n this.fullMapperPath = fullMapperPath;\n }\n\n public String getPojoDirPath() {\n return pojoDirPath;\n }\n\n public void setPojoDirPath(String pojoDirPath) {\n this.pojoDirPath = pojoDirPath;\n }\n\n public String getSuffix() {\n return suffix;\n }\n\n public void setSuffix(String suffix) {\n this.suffix = suffix;\n }\n\n public String getIdType() {\n return idType;\n }\n\n public void setIdType(String idType) {\n this.idType = idType;\n }\n}", "public class LoggerWrapper implements Logger {\n\n public static List<String> logList = Lists.newArrayList(\n \"\", \"---------------------- start -------------------------\");\n\n public static List<String> errorList = Lists.newArrayList(\n \"\", \"---------------------- start -------------------------\"\n );\n\n public LoggerWrapper() {\n\n }\n\n public static void saveAllLogs(String projectPath) {\n try{\n String firstMatch = MapHelper.getFirstMatch(UserConfigService.userConfigMap, \"printLog\", \"printlog\", \"debug\");\n if(!StringUtils.endsWithIgnoreCase(firstMatch,\"true\") || StringUtils.isBlank(projectPath)){\n return;\n }\n logList.add(\"---------------------- end -------------------------\");\n if(!projectPath.endsWith(GenCodeResponseHelper.getPathSplitter())){\n projectPath = projectPath + GenCodeResponseHelper.getPathSplitter();\n }\n String path = projectPath + \"codehelper.generator.log\";\n File logFile = new File(path);\n List<String> allLines = Lists.newArrayList();\n if(logFile.exists()){\n List<String> oldLines = IOUtils.readLines(path);\n if(oldLines !=null && !oldLines.isEmpty()){\n allLines.addAll(oldLines);\n }\n }\n allLines.addAll(logList);\n IOUtils.writeLines(new File(path),allLines);\n }catch(Throwable ignored){\n\n }\n\n }\n\n public static Logger getLogger(Class clazz){\n return new LoggerWrapper();\n }\n\n @Override\n public String getName() {\n return \"LOGGER\";\n }\n\n @Override\n public void trace(String msg) {\n }\n\n private String format(String format, Object... objects) {\n StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];\n List<String> splits = Splitter.on(\".\").splitToList(stackTraceElement.getClassName());\n String className = splits.get(splits.size() - 1);\n String methodName = stackTraceElement.getMethodName();\n String logLevel = Thread.currentThread().getStackTrace()[2].getMethodName().toUpperCase();\n format = format.replace(\"{}\", \"%s\");\n format = format.replace(\"{ }\", \"%s\");\n for (Object object : objects) {\n if (format.contains(\"%s\")) {\n format = StringUtils.replaceOnce(format, \"%s\", \" \" + LogHelper.toString(object) + \" \");\n } else {\n format += format + \" \" + LogHelper.toString(object);\n }\n }\n // TODO: 7/26/16 add dateUtil\n String logContent = DateUtil.formatLong(new Date()) + \" [\" + className + \".\" + methodName + \"] \" + \"[\" + logLevel + \"] \" + format;\n logList.add(logContent);\n if(\"error\".equalsIgnoreCase(logLevel)){\n errorList.add(logContent);\n }\n return format;\n }\n\n @Override\n public void trace(String msg, Throwable t) {\n\n }\n\n @Override\n public void info(String msg) {\n\n format(msg);\n\n }\n\n @Override\n public void info(String format, Object arg) {\n\n format(format, arg);\n\n }\n\n @Override\n public void info(String format, Object arg1, Object arg2) {\n\n format(format, arg1, arg2);\n\n }\n\n @Override\n public void info(String format, Object... arguments) {\n\n format(format, arguments);\n\n }\n\n @Override\n public void info(String msg, Throwable t) {\n\n format(msg, t);\n\n }\n\n @Override\n public void info(Marker marker, String msg) {\n\n }\n\n @Override\n public void info(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void info(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void info(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void info(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public void error(String msg) {\n\n format(msg);\n\n }\n\n @Override\n public void error(String format, Object arg) {\n\n format(format, arg);\n\n }\n\n @Override\n public void error(String format, Object arg1, Object arg2) {\n format(format, arg1, arg2);\n }\n\n @Override\n public void error(String format, Object... arguments) {\n format(format, arguments);\n }\n\n @Override\n public void error(String msg, Throwable t) {\n format(msg, t);\n }\n\n @Override\n public void error(Marker marker, String msg) {\n\n }\n\n @Override\n public void error(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void error(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void error(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void error(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public void trace(String format, Object arg) {\n\n }\n\n @Override\n public void trace(String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void trace(String format, Object... arguments) {\n\n }\n\n @Override\n public boolean isTraceEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public void trace(Marker marker, String msg) {\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object... argArray) {\n\n }\n\n @Override\n public void trace(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isDebugEnabled() {\n return false;\n }\n\n @Override\n public void debug(String msg) {\n\n }\n\n @Override\n public void debug(String format, Object arg) {\n\n }\n\n @Override\n public void debug(String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void debug(String format, Object... arguments) {\n\n }\n\n @Override\n public void debug(String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isDebugEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public void debug(Marker marker, String msg) {\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void debug(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isInfoEnabled() {\n return false;\n }\n\n @Override\n public boolean isWarnEnabled() {\n return false;\n }\n\n @Override\n public void warn(String msg) {\n\n }\n\n @Override\n public void warn(String format, Object arg) {\n\n }\n\n @Override\n public void warn(String format, Object... arguments) {\n\n }\n\n @Override\n public void warn(String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void warn(String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isWarnEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public void warn(Marker marker, String msg) {\n\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg) {\n\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg1, Object arg2) {\n\n }\n\n @Override\n public void warn(Marker marker, String format, Object... arguments) {\n\n }\n\n @Override\n public void warn(Marker marker, String msg, Throwable t) {\n\n }\n\n @Override\n public boolean isInfoEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public boolean isErrorEnabled(Marker marker) {\n return false;\n }\n\n @Override\n public boolean isTraceEnabled() {\n return false;\n }\n\n @Override\n public boolean isErrorEnabled() {\n return false;\n }\n}" ]
import com.ccnode.codegenerator.pojo.GenCodeResponse; import com.ccnode.codegenerator.util.LoggerWrapper; import com.ccnode.codegenerator.pojo.GenCodeResponse; import com.ccnode.codegenerator.pojo.OnePojoInfo; import com.ccnode.codegenerator.util.LoggerWrapper; import org.slf4j.Logger;
package com.ccnode.codegenerator.genCode; /** * What always stop you is what you always believe. * <p> * Created by zhengjun.du on 2016/08/21 15:54 */ public class GenTestService { private final static Logger LOGGER = LoggerWrapper.getLogger(GenTestService.class);
public static void genTest(GenCodeResponse response) {
2
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/handler/RestDeployStatusHandler.java
[ "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class DeployRequest {\n private final UUID id = UUID.randomUUID();\n private final List<DeployApplicationRequest> modules;\n private final List<DeployConfigRequest> configs;\n private final List<DeployArtifactRequest> artifacts;\n private final boolean elb;\n private final boolean autoScaling;\n private final String autoScalingGroup;\n private boolean decrementDesiredCapacity = true;\n private boolean restart;\n private DeployState state;\n private long timestamp;\n private final boolean testScope;\n\n private String failedReason;\n\n\n @JsonCreator\n public DeployRequest(@JsonProperty(\"modules\") List<DeployApplicationRequest> modules,\n @JsonProperty(\"artifacts\") List<DeployArtifactRequest> artifacts,\n @JsonProperty(\"configs\") List<DeployConfigRequest> configs,\n @JsonProperty(\"with_elb\") boolean elb,\n @JsonProperty(\"with_as\") boolean autoScaling,\n @JsonProperty(\"as_group_id\") String autoScalingGroup,\n @JsonProperty(\"restart\") boolean restart,\n @JsonProperty(\"test_scope\") boolean testScope) {\n this.modules = modules != null ? modules : Collections.emptyList();\n this.artifacts = artifacts != null ? artifacts : Collections.emptyList();\n this.configs = configs != null ? configs : Collections.emptyList();\n this.testScope = testScope;\n this.elb = elb;\n this.autoScaling = autoScaling;\n this.autoScalingGroup = autoScalingGroup;\n this.restart = restart;\n }\n\n public List<DeployArtifactRequest> getArtifacts() {\n return artifacts;\n }\n\n public List<DeployApplicationRequest> getModules() {\n return modules;\n }\n\n public List<DeployConfigRequest> getConfigs() {\n return configs;\n }\n\n public UUID getId() {\n return id;\n }\n\n public String getAutoScalingGroup() {\n return autoScalingGroup;\n }\n\n public boolean withElb() {\n return elb;\n }\n\n public boolean withAutoScaling() {\n return elb && autoScaling;\n }\n\n public boolean withRestart() {\n return restart;\n }\n\n public DeployState getState() {\n return this.state;\n }\n\n public void setState(DeployState state) {\n this.state = state;\n }\n\n public boolean isDecrementDesiredCapacity() {\n return decrementDesiredCapacity;\n }\n\n public boolean isScopeTest() {\n return this.testScope;\n }\n\n @JsonProperty(\"as_decrement_desired_capacity\")\n public void setDecrementDesiredCapacity(boolean decrementDesiredCapacity) {\n this.decrementDesiredCapacity = decrementDesiredCapacity;\n }\n\n public void setRestart(boolean restart) {\n this.restart = restart;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public void setFailedReason(String reason) {\n this.failedReason = reason;\n }\n\n public String getFailedReason() {\n return this.failedReason;\n }\n}", "public enum DeployState {\n WAITING_FOR_AS_DEREGISTER,\n WAITING_FOR_ELB_DEREGISTER,\n DEPLOYING_CONFIGS,\n STOPPING_CONTAINER,\n DEPLOYING_ARTIFACTS,\n DEPLOYING_APPLICATIONS,\n UNKNOWN,\n FAILED,\n SUCCESS,\n CONTINUE,\n WAITING_FOR_AS_REGISTER,\n WAITING_FOR_ELB_REGISTER\n}", "public class AwsService {\n private static final Logger LOG = LoggerFactory.getLogger(AwsService.class);\n private final Vertx vertx;\n private final DeployConfig config;\n private final Map<String, DeployRequest> runningRequests = new HashMap<>();\n\n public AwsService(Vertx vertx, DeployConfig config) {\n this.vertx = vertx;\n this.config = config;\n }\n\n public void registerRequest(DeployRequest deployRequest) {\n if (runningRequests.containsKey(deployRequest.getId().toString())) {\n LOG.error(LogConstants.REQUEST_ALREADY_REGISTERED, LogConstants.AWS_ELB_REQUEST, deployRequest.getId());\n throw new IllegalStateException(\"Request already registered.\");\n }\n runningRequests.put(deployRequest.getId().toString(), deployRequest);\n }\n\n public Observable<DeployRequest> autoScalingDeRegisterInstance(DeployRequest deployRequest) {\n if (!runningRequests.containsKey(deployRequest.getId().toString())) {\n LOG.error(LogConstants.REQUEST_NOT_REGISTERED, LogConstants.AWS_ELB_REQUEST, deployRequest.getId());\n this.failBuild(deployRequest.getId().toString(), LogConstants.REQUEST_NOT_REGISTERED, null);\n throw new IllegalStateException();\n }\n updateAndGetRequest(DeployState.WAITING_FOR_AS_DEREGISTER, deployRequest.getId().toString());\n AwsAsDeRegisterInstance deRegisterFromAsGroup = new AwsAsDeRegisterInstance(vertx, config, config.getAwsMaxRegistrationDuration());\n return deRegisterFromAsGroup.executeAsync(deployRequest);\n }\n\n public Observable<DeployRequest> autoScalingRegisterInstance(DeployRequest deployRequest) {\n if (!runningRequests.containsKey(deployRequest.getId().toString())) {\n LOG.error(LogConstants.REQUEST_NOT_REGISTERED, LogConstants.AWS_ELB_REQUEST, deployRequest.getId());\n this.failBuild(deployRequest.getId().toString(), LogConstants.REQUEST_NOT_REGISTERED, null);\n throw new IllegalStateException();\n }\n updateAndGetRequest(DeployState.WAITING_FOR_AS_REGISTER, deployRequest.getId().toString());\n AwsAsRegisterInstance register = new AwsAsRegisterInstance(vertx, config, config.getAwsMaxRegistrationDuration());\n return register.executeAsync(deployRequest);\n }\n\n public Observable<DeployRequest> loadBalancerRegisterInstance(DeployRequest deployRequest) {\n if (!runningRequests.containsKey(deployRequest.getId().toString())) {\n LOG.error(LogConstants.REQUEST_NOT_REGISTERED, LogConstants.AWS_ELB_REQUEST, deployRequest.getId().toString());\n this.failBuild(deployRequest.getId().toString(), LogConstants.REQUEST_NOT_REGISTERED, null);\n throw new IllegalStateException();\n }\n updateAndGetRequest(DeployState.WAITING_FOR_ELB_REGISTER, deployRequest.getId().toString());\n AwsElbRegisterInstance register = new AwsElbRegisterInstance(vertx, deployRequest.getId().toString(), config,\n s -> runningRequests.containsKey(s) && (!DeployState.FAILED.equals(runningRequests.get(s).getState()) || !DeployState.SUCCESS.equals(runningRequests.get(s).getState())));\n return register.executeAsync(deployRequest);\n }\n\n public Observable<DeployRequest> loadBalancerDeRegisterInstance(DeployRequest deployRequest) {\n if (!runningRequests.containsKey(deployRequest.getId().toString())) {\n LOG.error(LogConstants.REQUEST_NOT_REGISTERED, LogConstants.AWS_ELB_REQUEST, deployRequest.getId().toString());\n this.failBuild(deployRequest.getId().toString(), LogConstants.REQUEST_NOT_REGISTERED, null);\n throw new IllegalStateException();\n }\n updateAndGetRequest(DeployState.WAITING_FOR_ELB_DEREGISTER, deployRequest.getId().toString());\n AwsElbDeRegisterInstance register = new AwsElbDeRegisterInstance(vertx, config);\n return register.executeAsync(deployRequest);\n }\n\n\n public DeployRequest updateAndGetRequest(DeployState state, String buildId) {\n if (runningRequests.containsKey(buildId) && !DeployState.FAILED.equals(runningRequests.get(buildId).getState())) {\n LOG.info(\"[{} - {}]: Updating state to {}\", LogConstants.AWS_ELB_REQUEST, buildId, state);\n runningRequests.get(buildId).setState(state);\n return runningRequests.get(buildId);\n }\n return null;\n }\n\n public void failBuild(String buildId, String reason, Throwable t) {\n LOG.error(\"[{} - {}]: Failing build.\", LogConstants.AWS_ELB_REQUEST, buildId);\n if (runningRequests.containsKey(buildId)) {\n runningRequests.get(buildId).setState(DeployState.FAILED);\n runningRequests.get(buildId).setFailedReason(reason);\n }\n }\n\n public DeployRequest getDeployRequest(String deployId) {\n if (!runningRequests.containsKey(deployId)) {\n return null;\n }\n DeployRequest deployRequest = runningRequests.get(deployId);\n\n if (DeployState.SUCCESS.equals(deployRequest.getState()) || DeployState.FAILED.equals(deployRequest.getState())) {\n runningRequests.remove(deployId);\n }\n return deployRequest;\n }\n\n public void failAllRunningRequests() {\n runningRequests.forEach((id, r) -> r.setState(DeployState.FAILED));\n }\n\n}", "public class DeployApplicationService implements DeployService<DeployApplicationRequest, DeployApplicationRequest> {\n private static final Logger LOG = LoggerFactory.getLogger(DeployApplicationService.class);\n private final DeployConfig config;\n private final Vertx vertx;\n private final List<String> deployedApplicationsSuccess = new ArrayList<>();\n private final Map<String, Object> deployedApplicationsFailed = new HashMap<>();\n\n public DeployApplicationService(DeployConfig config, Vertx vertx) {\n this.config = config;\n this.vertx = vertx;\n }\n\n @Override\n public Observable<DeployApplicationRequest> deployAsync(DeployApplicationRequest deployApplicationRequest) {\n return resolveSnapShotVersion(deployApplicationRequest)\n .flatMap(this::checkModuleState)\n .flatMap(this::stopApplication)\n .flatMap(this::startApplication)\n .flatMap(this::registerApplication);\n }\n\n private Observable<DeployApplicationRequest> checkModuleState(DeployApplicationRequest deployApplicationRequest) {\n new ProcessUtils(config).checkModuleRunning(deployApplicationRequest);\n LOG.info(\"[{} - {}]: Module '{}' running : {}, sameVersion : {}.\", LogConstants.DEPLOY_REQUEST, deployApplicationRequest.getId(), deployApplicationRequest.getModuleId(), deployApplicationRequest.isInstalled(), deployApplicationRequest.isInstalled());\n return just(deployApplicationRequest);\n }\n\n private Observable<DeployApplicationRequest> stopApplication(DeployApplicationRequest deployApplicationRequest) {\n if (deployApplicationRequest.isRunning() && !deployApplicationRequest.isInstalled()) {\n StopApplication stopApplicationCommand = new StopApplication(vertx, config);\n return stopApplicationCommand.executeAsync(deployApplicationRequest);\n } else {\n return just(deployApplicationRequest);\n }\n }\n\n private Observable<DeployApplicationRequest> startApplication(DeployApplicationRequest deployApplicationRequest) {\n if (!deployApplicationRequest.isRunning()) {\n RunApplication runModCommand = new RunApplication(vertx, config);\n return runModCommand.executeAsync(deployApplicationRequest);\n } else {\n return just(deployApplicationRequest);\n }\n }\n\n\n private Observable<DeployApplicationRequest> registerApplication(DeployApplicationRequest\n deployApplicationRequest) {\n io.vertx.rxjava.core.Vertx rxVertx = new io.vertx.rxjava.core.Vertx(vertx);\n return rxVertx.fileSystem()\n .rxExists(config.getRunDir() + deployApplicationRequest.getModuleId())\n .toObservable()\n .flatMap(exists -> {\n if (!exists) {\n return rxVertx.fileSystem().rxCreateFile(config.getRunDir() + deployApplicationRequest.getModuleId())\n .toObservable()\n .flatMap(x -> just(deployApplicationRequest));\n } else {\n return just(deployApplicationRequest);\n }\n });\n }\n\n @Override\n public DeployConfig getConfig() {\n return config;\n }\n\n @Override\n public Vertx getVertx() {\n return vertx;\n }\n\n @Override\n public String getLogType() {\n return LogConstants.DEPLOY_REQUEST;\n }\n\n Observable<Boolean> stopContainer() {\n LOG.info(\"[{}]: Stopping all running modules\", LogConstants.INVOKE_CONTAINER);\n return Observable.from(new ProcessUtils(config).listInstalledAndRunningModules().entrySet())\n .concatMap(entry -> {\n StopApplication stopApplication = new StopApplication(vertx, config);\n String[] mavenIds = entry.getKey().split(\":\", 2);\n DeployApplicationRequest request = new DeployApplicationRequest(mavenIds[0], mavenIds[1], entry.getValue(), null, \"jar\");\n request.setRunning(false);\n request.setInstalled(false);\n return stopApplication.executeAsync(request);\n })\n .toList()\n .flatMap(x -> Observable.just(true));\n }\n\n Observable<DeployRequest> cleanup(DeployRequest deployRequest) {\n deployedApplicationsSuccess.clear();\n deployedApplicationsFailed.clear();\n return cleanup()\n .flatMap(x -> just(deployRequest));\n }\n\n public Observable<Boolean> cleanup() {\n List<String> runningApplications = new ProcessUtils(config).listModules();\n FileSystem fs = new io.vertx.rxjava.core.Vertx(vertx).fileSystem();\n\n\n return fs.rxReadDir(config.getRunDir())\n .toObservable()\n .flatMapIterable(x -> x)\n .flatMap(s -> just(Pattern.compile(\"/\").splitAsStream(s).reduce((a, b) -> b).orElse(\"\")))\n .filter(s -> !s.isEmpty() && !runningApplications.contains(s))\n .flatMap(file -> fs.rxDelete(config.getRunDir() + file).toObservable())\n .toList()\n .flatMap(x -> just(Boolean.TRUE).doOnError(t -> LOG.error(\"error\")))\n .onErrorReturn(x -> {\n LOG.error(\"Error during cleanup of run files {}\", x.getMessage());\n return Boolean.FALSE;\n });\n }\n\n public void addApplicationDeployResult(boolean succeeded, String message, String deploymentId) {\n if (succeeded && !deployedApplicationsSuccess.contains(deploymentId)) {\n deployedApplicationsSuccess.add(deploymentId);\n }\n if (!succeeded && !deployedApplicationsFailed.containsKey(deploymentId)) {\n deployedApplicationsFailed.put(deploymentId, message != null ? message : \"No reason provided by application.\");\n }\n\n }\n\n public List<String> getDeployedApplicationsSuccess() {\n return deployedApplicationsSuccess;\n }\n\n public Map<String, Object> getDeployedApplicationsFailed() {\n return deployedApplicationsFailed;\n }\n}", "public enum ApplicationDeployState {\n OK,\n ERROR;\n\n public static ApplicationDeployState map(String state) {\n if (state == null || state.isEmpty()) {\n return OK;\n }\n try {\n return ApplicationDeployState.valueOf(state.toUpperCase());\n } catch (IllegalArgumentException e) {\n return OK;\n }\n }\n}", "public final class HttpUtils {\n\n private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);\n\n private HttpUtils() {\n // hide\n }\n\n public static JsonArray toArray(List<String> list) {\n return new JsonArray(list);\n }\n\n public static JsonObject toArray(Map<String, Object> map) {\n return new JsonObject(map);\n }\n\n public static <T> T readPostData(Buffer buffer, Class<T> clazz, String logType) {\n if (buffer == null || buffer.length() == 0) {\n LOG.error(\"[{}]: No postdata in request.\", logType);\n return null;\n }\n\n LOG.debug(\"[{}]: received POST data -> {} .\", logType, buffer.getBytes());\n\n try {\n return new ObjectMapper().readerFor(clazz).readValue(buffer.getBytes());\n } catch (IOException e) {\n LOG.error(\"[{}]: Error while reading POST data -> {}.\", logType, e.getMessage(), e);\n return null;\n }\n }\n\n public static boolean hasCorrectAuthHeader(RoutingContext context, String authToken, String logType) {\n if (StringUtils.isNullOrEmpty(context.request().getHeader(\"authToken\")) || !authToken.equals(context.request().getHeader(\"authToken\"))) {\n LOG.error(\"{}: Invalid authToken in request.\", logType);\n return false;\n }\n return true;\n }\n\n private static void respond(HttpServerResponse response, HttpResponseStatus code, JsonObject status) {\n response.setStatusCode(code.code());\n if (status != null) {\n response.end(status.encode());\n } else {\n response.end();\n }\n }\n\n public static void respondOk(HttpServerRequest request, JsonObject status) {\n respond(request.response(), HttpResponseStatus.OK, status);\n }\n\n public static void respondOk(HttpServerRequest request) {\n respondOk(request, null);\n }\n\n public static void respondFailed(HttpServerRequest request, JsonObject status) {\n respond(request.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR, status);\n }\n\n public static void respondFailed(HttpServerRequest request) {\n respondFailed(request, null);\n }\n\n public static void respondBadRequest(HttpServerRequest request) {\n respond(request.response(), HttpResponseStatus.BAD_REQUEST, null);\n }\n\n public static void respondContinue(HttpServerRequest request, DeployState state) {\n request.response().setStatusCode(HttpResponseStatus.ACCEPTED.code());\n request.response().setStatusMessage(\"Deploy in state : \" + state.name());\n request.response().end();\n }\n\n\n}" ]
import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import nl.jpoint.vertx.deploy.agent.request.DeployRequest; import nl.jpoint.vertx.deploy.agent.request.DeployState; import nl.jpoint.vertx.deploy.agent.service.AwsService; import nl.jpoint.vertx.deploy.agent.service.DeployApplicationService; import nl.jpoint.vertx.deploy.agent.util.ApplicationDeployState; import nl.jpoint.vertx.deploy.agent.util.HttpUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package nl.jpoint.vertx.deploy.agent.handler; public class RestDeployStatusHandler implements Handler<RoutingContext> { private static final Logger LOG = LoggerFactory.getLogger(RestDeployStatusHandler.class); private final AwsService deployAwsService; private final DeployApplicationService deployApplicationService; public RestDeployStatusHandler(AwsService deployAwsService, DeployApplicationService deployApplicationService) { this.deployAwsService = deployAwsService; this.deployApplicationService = deployApplicationService; } @Override public void handle(final RoutingContext context) { DeployRequest deployRequest = deployAwsService.getDeployRequest(context.request().params().get("id")); DeployState state = deployRequest != null ? deployRequest.getState() : DeployState.UNKNOWN; if (!deployApplicationService.getDeployedApplicationsFailed().isEmpty()) { LOG.error("Some services failed to start, failing build"); state = DeployState.FAILED; deployAwsService.failAllRunningRequests(); } DeployState deployState = state != null ? state : DeployState.CONTINUE; LOG.trace("[{}]: Current state : {}", deployRequest != null ? deployRequest.getId() : DeployState.UNKNOWN, deployState.name()); switch (deployState) { case SUCCESS:
HttpUtils.respondOk(context.request(), createStatusObject(null));
5
spring-projects/eclipse-integration-tcserver
com.vmware.vfabric.ide.eclipse.tcserver.ui/src/com/vmware/vfabric/ide/eclipse/tcserver/internal/ui/TcServer21WizardFragment.java
[ "public interface ITcRuntime {\n\t\n\tIPath runtimeLocation();\n\t\n\tIPath instanceCreationScript();\n\t\n\tIPath getTomcatLocation();\n\t\n\tIPath getTomcatServersContainer();\n\t\n\tIPath instanceDirectory(String instanceName);\n\t\n\tIPath defaultInstancesDirectory();\n\n}", "public interface ITcServerConstants {\n\n\tpublic static String ID_CONFIG_TC_SERVER_2_1 = \"com.springsource.sts.ide.configurator.server.TcServer21\";\n\n\tpublic static String ID_CONFIG_TC_SERVER_2_0 = \"com.springsource.sts.ide.configurator.server.TcServer20\";\n\n\tpublic static String ID_CONFIG_TC_SERVER_6 = \"com.springsource.sts.ide.configurator.server.TcServer6\";\n\n\tpublic static final String PLUGIN_ID = \"com.vwmare.vfabric.ide.eclipse.tcserver.core\";\n\n}", "public class TcServer extends TomcatServer {\n\n\tpublic static final String DEFAULT_DEPLOYER_HOST = \"localhost\";\n\n\tpublic static final String DEFAULT_DEPLOYER_SERVICE = \"Catalina\";\n\n\t/**\n\t * Default filename patters that should to avoid a webapp reload when\n\t * publishing.\n\t */\n\tpublic static final String DEFAULT_STATIC_FILENAMES = \"*.html,*.xhtml,*.css,*.jspx,*.js,*.jsp,*.gif,*.jpg,*.png,*.swf,*-flow.xml,*.properties,*.xml,!tiles.xml,!web.xml\";\n\n\t/** Boolean property that determines if the ASF layout should be used. */\n\tpublic static final String KEY_ASF_LAYOUT = \"com.springsource.tcserver.asf\";\n\n\t/**\n\t * String property for the server instance for combined or separate layout.\n\t */\n\tpublic static final String KEY_SERVER_NAME = \"com.springsource.tcserver.name\";\n\n\tpublic static final String PROPERTY_ADD_EXTRA_VMARGS = \"addExtraVmArgs\";\n\n\tpublic static final String PROPERTY_AGENT_OPTIONS = \"com.springsource.tcserver.agent.options\";\n\n\tpublic static final String PROPERTY_AGENT_REDEPLOY = \"com.springsource.tcserver.agent.deploy\";\n\n\tpublic static final String PROPERTY_DEPLOYER_HOST = \"modifyDeployerHost\";\n\n\tpublic static final String PROPERTY_DEPLOYER_SERVICE = \"modifyDeployerService\";\n\n\t/**\n\t * Property key for a boolean that indicates managing of webapp reloading is\n\t * enabled.\n\t */\n\tpublic static final String PROPERTY_ENHANCED_REDEPLOY = \"com.springsource.tcserver.jmx.deploy\";\n\n\tpublic static final String PROPERTY_JMX_PASSWORD = \"modifyJmxPassowrd\";\n\n\tpublic static final String PROPERTY_JMX_PORT = \"modifyJmxPort\";\n\n\tpublic static final String PROPERTY_JMX_USER = \"modifyJmxUser\";\n\n\tpublic static final String PROPERTY_REMOVE_EXTRA_VMARGS = \"removeExtraVmArgs\";\n\n\t/**\n\t * Property key for list of patterns to avoid a webapp reload when\n\t * publishing.\n\t */\n\tpublic static final String PROPERTY_STATIC_FILENAMES = \"com.springsource.tcserver.filenames.static\";\n\n\tprivate static TcServerCallback callback;\n\n\tprivate static final String DEFAULT_JMX_PORT = \"6969\";\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<String> getAddExtraVmArgs() {\n\t\treturn getAttribute(PROPERTY_ADD_EXTRA_VMARGS, Collections.EMPTY_LIST);\n\t}\n\n\tpublic String getAgentOptions() {\n\t\treturn getAttribute(PROPERTY_AGENT_OPTIONS, \"\");\n\t}\n\n\tpublic String getDeployerHost() {\n\t\treturn getAttribute(PROPERTY_DEPLOYER_HOST, DEFAULT_DEPLOYER_HOST);\n\t}\n\n\tpublic String getDeployerProperty(String key) {\n\t\tif (PROPERTY_JMX_PORT.equals(key)) {\n\t\t\treturn getJmxPort();\n\t\t}\n\t\tif (PROPERTY_DEPLOYER_HOST.equals(key)) {\n\t\t\treturn getDeployerHost();\n\t\t}\n\t\tif (PROPERTY_DEPLOYER_SERVICE.equals(key)) {\n\t\t\treturn getDeployerService();\n\t\t}\n\t\treturn getAttribute(key, (String) null);\n\t}\n\n\tpublic String getDeployerService() {\n\t\treturn getAttribute(PROPERTY_DEPLOYER_SERVICE, DEFAULT_DEPLOYER_SERVICE);\n\t}\n\n\t/**\n\t * The runtime may specifies the top-level tc Server directory and not the\n\t * catalina home. This methods returns the actual catalina home this server\n\t * is configured to use.\n\t */\n\tpublic IPath getInstanceBase(IRuntime runtime) {\n\t\tITcRuntime tcRuntime = TcServerUtil.getTcRuntime(runtime);\n\t\tIPath path = tcRuntime.runtimeLocation();\n\t\tif (isAsfLayout()) {\n\t\t\treturn getTomcatRuntime().getTomcatLocation();\n\t\t}\n\t\telse {\n\t\t\tString instanceDir = getInstanceDirectory();\n\t\t\tif (instanceDir != null) {\n\t\t\t\tpath = Path.fromOSString(instanceDir);\n\t\t\t}\n\t\t\tString serverName = getAttribute(KEY_SERVER_NAME, (String) null);\n\t\t\tif (serverName != null && !path.toOSString().endsWith(serverName)) {\n\t\t\t\tpath = tcRuntime.instanceDirectory(serverName);\n\t\t\t}\n\t\t\treturn path;\n\t\t}\n\t}\n\n\tpublic String getJmxPassword() {\n\t\treturn getAttribute(PROPERTY_JMX_PASSWORD, \"\");\n\t}\n\n\tpublic String getJmxPort() {\n\t\treturn getAttribute(PROPERTY_JMX_PORT, DEFAULT_JMX_PORT);\n\t}\n\n\tpublic String getJmxUser() {\n\t\treturn getAttribute(PROPERTY_JMX_USER, \"\");\n\t}\n\n\tpublic Layout getLayout() {\n\t\tif (isAsfLayout()) {\n\t\t\treturn Layout.ASF;\n\t\t}\n\t\telse {\n\t\t\tIPath path = getInstanceBase(getServer().getRuntime());\n\t\t\tif (path.append(\"lib\").append(\"catalina.jar\").toFile().exists()) {\n\t\t\t\treturn Layout.COMBINED;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn Layout.SEPARATE;\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<String> getRemoveExtraVmArgs() {\n\t\treturn getAttribute(PROPERTY_REMOVE_EXTRA_VMARGS, Collections.EMPTY_LIST);\n\t}\n\n\tpublic String getServerName() {\n\t\treturn getAttribute(TcServer.KEY_SERVER_NAME, (String) null);\n\t}\n\n\tpublic String getStaticFilenamePatterns() {\n\t\treturn getAttribute(PROPERTY_STATIC_FILENAMES, DEFAULT_STATIC_FILENAMES);\n\t}\n\n\t@Override\n\tpublic TcServerConfiguration getTomcatConfiguration() throws CoreException {\n\t\tif (configuration == null) {\n\t\t\tIFolder folder = getFolder();\n\t\t\tconfiguration = new TcServerConfiguration(this, folder, getTomcatRuntime().supportsServlet30());\n\t\t\ttry {\n\t\t\t\t((TcServerConfiguration) configuration).load(folder, null);\n\t\t\t}\n\t\t\tcatch (CoreException ce) {\n\t\t\t\t// ignore\n\t\t\t\tconfiguration = null;\n\t\t\t\tthrow ce;\n\t\t\t}\n\t\t}\n\t\treturn (TcServerConfiguration) configuration;\n\t}\n\n\t@Override\n\tpublic TcServerRuntime getTomcatRuntime() {\n\t\treturn (TcServerRuntime) super.getTomcatRuntime();\n\t}\n\n\t@Override\n\tpublic void importRuntimeConfiguration(IRuntime runtime, IProgressMonitor monitor) throws CoreException {\n\t\ttry {\n\t\t\timportRuntimeConfigurationChecked(runtime, monitor);\n\t\t}\n\t\tcatch (CoreException ce) {\n\t\t\t// ignore, need additional configuration for server instance\n\t\t\t// Webtools invokes importRuntimeConfiguration() before any\n\t\t\t// configuration has taken place therefore this method need to fail\n\t\t\t// silently and the configuration needs to be imported again later\n\t\t\t// on\n\t\t\tconfiguration = null;\n\t\t}\n\t}\n\n\tpublic void importRuntimeConfigurationChecked(IRuntime runtime, IProgressMonitor monitor) throws CoreException {\n\t\tif (runtime == null) {\n\t\t\tconfiguration = null;\n\t\t\treturn;\n\t\t}\n\t\tIPath path = getInstanceBase(runtime);\n\t\tpath = path.append(\"conf\");\n\t\tIFolder folder = getServer().getServerConfiguration();\n\t\tconfiguration = new TcServerConfiguration(this, folder);\n\t\tconfiguration.importFromPath(path, isTestEnvironment(), monitor);\n\t}\n\n\tpublic boolean isAgentRedeployEnabled() {\n\t\treturn getAttribute(PROPERTY_AGENT_REDEPLOY, false);\n\t}\n\n\tpublic boolean isAsfLayout() {\n\t\treturn getAttribute(TcServer.KEY_ASF_LAYOUT, true);\n\t}\n\n\tpublic boolean isEnhancedRedeployEnabled() {\n\t\treturn getAttribute(PROPERTY_ENHANCED_REDEPLOY, false);\n\t}\n\n\tpublic void setAddExtraVmArgs(List<String> value) {\n\t\tsetAttribute(PROPERTY_ADD_EXTRA_VMARGS, value);\n\t}\n\n\tpublic void setAgentOptions(String agentOptions) {\n\t\tsetAttribute(PROPERTY_AGENT_OPTIONS, agentOptions);\n\t}\n\n\tpublic void setAgentRedeployEnabled(boolean enable) {\n\t\tsetAttribute(PROPERTY_AGENT_REDEPLOY, enable);\n\t}\n\n\t@Override\n\tpublic void setDefaults(IProgressMonitor monitor) {\n\t\tsuper.setDefaults(monitor);\n\n\t\tTcServerUtil.setTcServerDefaultName(getServerWorkingCopy());\n\n\t\t// test mode is now supported\n\t\t// setAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, (String) null);\n\t\t// setAttribute(ITomcatServer.PROPERTY_TEST_ENVIRONMENT, false);\n\t\t// ASF layout is only supported by tc Server 2.0 and earlier\n\t\tif (isVersion25(getServer().getRuntime()) || isVersion30(getServer().getRuntime())\n\t\t\t\t|| isVersion40(getServer().getRuntime())) {\n\t\t\tsetAttribute(TcServer.KEY_ASF_LAYOUT, false);\n\t\t\tsetAttribute(ITomcatServer.PROPERTY_SAVE_SEPARATE_CONTEXT_FILES, true);\n\t\t}\n\t\telse {\n\t\t\tsetAttribute(TcServer.KEY_ASF_LAYOUT, true);\n\n\t\t}\n\t\tsetTestEnvironment(false);\n\t\tgetCallback().setDefaults(this, monitor);\n\t}\n\n\tpublic void setDeployerHost(String value) {\n\t\tsetAttribute(PROPERTY_DEPLOYER_HOST, value);\n\t}\n\n\tpublic void setDeployerProperty(String key, String value) {\n\t\tsetAttribute(key, value);\n\t}\n\n\tpublic void setDeployerService(String value) {\n\t\tsetAttribute(PROPERTY_DEPLOYER_SERVICE, value);\n\t}\n\n\tpublic void setEnhancedRedeployEnabled(boolean enable) {\n\t\tsetAttribute(PROPERTY_ENHANCED_REDEPLOY, enable);\n\t}\n\n\tpublic void setJmxPassword(String value) {\n\t\tsetAttribute(PROPERTY_JMX_PASSWORD, value);\n\t}\n\n\tpublic void setJmxPort(String value) {\n\t\tsetAttribute(PROPERTY_JMX_PORT, value);\n\t}\n\n\tpublic void setJmxUser(String value) {\n\t\tsetAttribute(PROPERTY_JMX_USER, value);\n\t}\n\n\tpublic void setRemoveExtraVmArgs(List<String> value) {\n\t\tsetAttribute(PROPERTY_REMOVE_EXTRA_VMARGS, value);\n\t}\n\n\tpublic void setStaticFilenamePatterns(String filenamePatterns) {\n\t\tsetAttribute(PROPERTY_STATIC_FILENAMES, filenamePatterns);\n\t}\n\n\tprotected IFolder getFolder() throws CoreException {\n\t\tIFolder folder = getServer().getServerConfiguration();\n\t\tif (folder == null || !folder.exists()) {\n\t\t\tString path = null;\n\t\t\tif (folder != null) {\n\t\t\t\tpath = folder.getFullPath().toOSString();\n\t\t\t}\n\t\t\tthrow new CoreException(new Status(IStatus.ERROR, TomcatPlugin.PLUGIN_ID, 0, NLS.bind(\n\t\t\t\t\tMessages.errorNoConfiguration, path), null));\n\t\t}\n\t\treturn folder;\n\t}\n\n\t@Override\n\tprotected void initialize() {\n\t\tsuper.initialize();\n\t}\n\n\tpublic static synchronized TcServerCallback getCallback() {\n\t\tif (callback == null) {\n\t\t\tcallback = ExtensionPointReader.readExtension();\n\t\t\tif (callback == null) {\n\t\t\t\t// create null callback\n\t\t\t\tcallback = new TcServerCallback() {\n\t\t\t\t\t// ignore\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn callback;\n\t}\n\n\tpublic static boolean isVersion25(IRuntime runtime) {\n\t\treturn runtime.getRuntimeType().getId().endsWith(\"70\");\n\t}\n\n\tpublic static boolean isVersion30(IRuntime runtime) {\n\t\treturn runtime.getRuntimeType().getId().endsWith(\"80\");\n\t}\n\n\tpublic static boolean isVersion40(IRuntime runtime) {\n\t\treturn runtime.getRuntimeType().getId().endsWith(\"90\");\n\t}\n\t\n\tpublic static String substitute(String value, Properties properties) {\n\t\tString[] segments = value.split(\"\\\\$\\\\{\");\n\t\tStringBuffer sb = new StringBuffer(value.length());\n\t\tsb.append(segments[0]);\n\t\tfor (int i = 1; i < segments.length; i++) {\n\t\t\tString segment = segments[i];\n\t\t\tString substitution = null;\n\t\t\tint brace = segment.indexOf('}');\n\t\t\tif (brace > 0) {\n\t\t\t\tString keyword = segment.substring(0, brace);\n\t\t\t\tsubstitution = properties.getProperty(keyword);\n\t\t\t}\n\n\t\t\tif (substitution != null) {\n\t\t\t\tsb.append(substitution);\n\t\t\t\tsb.append(segment.substring(brace + 1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsb.append(\"${\");\n\t\t\t\tsb.append(segment);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic enum Layout {\n\t\t/**\n\t\t * Uses runtime directory. Does not have an instance directory.\n\t\t * Supported by v2.0 and earlier only.\n\t\t */\n\t\tASF,\n\t\t/** Uses instance directory. Supported by v2.5 and later only. */\n\t\tCOMBINED,\n\t\t/** Uses runtime and instance directory. Supported by all versions. */\n\t\tSEPARATE;\n\n\t\tpublic String toString() {\n\t\t\tswitch (this) {\n\t\t\tcase ASF:\n\t\t\t\treturn \"ASF Layout\";\n\t\t\tcase COMBINED:\n\t\t\t\treturn \"Combined Layout\";\n\t\t\tcase SEPARATE:\n\t\t\t\treturn \"Separate Layout\";\n\t\t\t}\n\t\t\tthrow new IllegalStateException();\n\t\t};\n\t}\n\n\tprivate static class ExtensionPointReader {\n\n\t\tprivate static final String ELEMENT_CALLBACK = \"callback\";\n\n\t\tprivate static final String ELEMENT_CLASS = \"class\";\n\n\t\tprivate static final String EXTENSION_ID_CALLBACK = \"com.springsource.sts.server.tc.core.callback\";\n\n\t\tpublic static TcServerCallback readExtension() {\n\t\t\tIExtensionRegistry registry = Platform.getExtensionRegistry();\n\t\t\tIExtensionPoint extensionPoint = registry.getExtensionPoint(EXTENSION_ID_CALLBACK);\n\t\t\tIExtension[] extensions = extensionPoint.getExtensions();\n\t\t\tfor (IExtension extension : extensions) {\n\t\t\t\tIConfigurationElement[] elements = extension.getConfigurationElements();\n\t\t\t\tfor (IConfigurationElement element : elements) {\n\t\t\t\t\tif (element.getName().compareTo(ELEMENT_CALLBACK) == 0) {\n\t\t\t\t\t\treturn readCallbackExtension(element);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate static TcServerCallback readCallbackExtension(IConfigurationElement configurationElement) {\n\t\t\ttry {\n\t\t\t\tObject object = configurationElement.createExecutableExtension(ELEMENT_CLASS);\n\t\t\t\tif (!(object instanceof TcServerCallback)) {\n\t\t\t\t\tTomcatPlugin.log(new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID, \"Could not load \"\n\t\t\t\t\t\t\t+ object.getClass().getCanonicalName() + \" must implement \"\n\t\t\t\t\t\t\t+ TcServerCallback.class.getCanonicalName()));\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn (TcServerCallback) object;\n\t\t\t}\n\t\t\tcatch (CoreException e) {\n\t\t\t\tTomcatPlugin.log(new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID,\n\t\t\t\t\t\t\"Could not load callback extension\", e));\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic URL getModuleRootURL(IModule module) {\n\t\tURL url = super.getModuleRootURL(module);\n\t\tif (url != null) {\n\t\t\treturn url;\n\t\t}\n\n\t\t// if standard method fails, return URL for SSL connection\n\t\ttry {\n\t\t\tif (module == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tTcServerConfiguration config = getTomcatConfiguration();\n\t\t\tif (config == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tServerPort sslPort = config.getMainSslPort();\n\t\t\tif (sslPort == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tint port = sslPort.getPort();\n\t\t\tString urlString = \"https://\" + getServer().getHost();\n\t\t\tport = ServerUtil.getMonitoredPort(getServer(), port, \"web\");\n\t\t\tif (port != 443) {\n\t\t\t\turlString += \":\" + port;\n\t\t\t}\n\t\t\turlString += config.getWebModuleURL(module);\n\t\t\tif (!urlString.endsWith(\"/\")) {\n\t\t\t\turlString += \"/\";\n\t\t\t}\n\t\t\treturn new URL(urlString);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tTrace.trace(Trace.SEVERE, \"Could not get root URL\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n}", "public class TcServerCorePlugin extends AbstractUIPlugin {\n\n\tpublic static final String PLUGIN_ID = \"com.vmware.vfabric.ide.eclipse.tcserver.core\";\n\n\tprivate static TcServerCorePlugin plugin;\n\n\tprivate static TcServerConfigurationResourceListener configurationListener;\n\n\tpublic static TcServerCorePlugin getDefault() {\n\t\treturn plugin;\n\t}\n\n\t@Override\n\tpublic void start(BundleContext context) throws Exception {\n\t\tsuper.start(context);\n\t\tplugin = this;\n\t\tconfigurationListener = new TcServerConfigurationResourceListener();\n\t\tResourcesPlugin.getWorkspace().addResourceChangeListener(configurationListener,\n\t\t\t\tIResourceChangeEvent.POST_CHANGE);\n\n\t}\n\n\t@Override\n\tpublic void stop(BundleContext context) throws Exception {\n\t\tResourcesPlugin.getWorkspace().removeResourceChangeListener(configurationListener);\n\t\tplugin = null;\n\t\tsuper.stop(context);\n\t}\n\t\n\tpublic static void log(IStatus status) {\n\t\tTcServerCorePlugin plugin = getDefault();\n\t\tif (plugin!=null) {\n\t\t\tILog log = plugin.getLog();\n\t\t\tif (log!=null) {\n\t\t\t\tlog.log(status);\n\t\t\t}\n\t\t}\n\t}\n\n}", "public class TcServerUtil {\n\n\t@Deprecated\n\tpublic static boolean isSpringSource(IRuntimeWorkingCopy wc) {\n\t\treturn wc != null && wc.getRuntimeType() != null && wc.getRuntimeType().getId().startsWith(\"com.springsource\");\n\t}\n\n\t@Deprecated\n\tpublic static boolean isVMWare(IRuntimeWorkingCopy wc) {\n\t\treturn wc != null && wc.getRuntimeType() != null && wc.getRuntimeType().getId().startsWith(\"com.vmware\");\n\t}\n\n\tpublic static String getServerVersion(IRuntime runtime) {\n\t\tITcRuntime tcRuntime = getTcRuntime(runtime);\n\t\tString directory = tcRuntime.getTomcatLocation().lastSegment();\n\t\treturn getServerVersion(directory);\n\t}\n\n\tpublic static String getServerVersion(String tomcatFolerName) {\n\t\treturn (tomcatFolerName != null && tomcatFolerName.startsWith(\"tomcat-\")) ? tomcatFolerName.substring(7)\n\t\t\t\t: tomcatFolerName;\n\t}\n\n\tpublic static void importRuntimeConfiguration(IServerWorkingCopy wc, IProgressMonitor monitor) throws CoreException {\n\t\t// invoke tc Server API directly since\n\t\t// TcServer.importRuntimeConfiguration() swallows exceptions\n\t\t((TcServer) ((ServerWorkingCopy) wc).getWorkingCopyDelegate(monitor)).importRuntimeConfigurationChecked(\n\t\t\t\twc.getRuntime(), monitor);\n\t}\n\n\tpublic static IStatus validateInstance(File instanceDirectory, boolean tcServer21orLater) {\n\t\tif (tcServer21orLater) {\n\t\t\tif (!new File(instanceDirectory, \".tc-runtime-instance\").exists()) {\n\t\t\t\treturn new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID,\n\t\t\t\t\t\t\"The specified server is not valid. The .tc-runtime-instance file is missing.\");\n\t\t\t}\n\t\t}\n\n\t\tFile confDir = new File(instanceDirectory, \"conf\");\n\t\tif (!confDir.exists()) {\n\t\t\treturn new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID,\n\t\t\t\t\t\"The specified server is not valid. The conf directory is missing.\");\n\t\t}\n\t\tFile confFile = new File(confDir, \"server.xml\");\n\t\tif (!confFile.exists()) {\n\t\t\treturn new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID,\n\t\t\t\t\t\"The specified server is not valid. The server.xml file in the conf directory is missing.\");\n\t\t}\n\t\tif (!confFile.canRead()) {\n\t\t\treturn new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID,\n\t\t\t\t\t\"The specified server is not valid. The server.xml file in the conf directory is not readable.\");\n\t\t}\n\t\treturn Status.OK_STATUS;\n\t}\n\n\tpublic static void executeInstanceCreation(IRuntime runtime, String instanceName, String[] arguments)\n\t\t\tthrows CoreException {\n\t\tITcRuntime tcRuntime = getTcRuntime(runtime);\n\t\tServerInstanceCommand command = new ServerInstanceCommand(tcRuntime);\n\n\t\t// execute\n\t\tint returnCode;\n\t\ttry {\n\t\t\treturnCode = command.execute(arguments);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow handleResult(tcRuntime.runtimeLocation(), command, arguments, new Status(IStatus.ERROR,\n\t\t\t\t\tITcServerConstants.PLUGIN_ID, \"The instance creation command resulted in an exception\", e));\n\t\t}\n\n\t\tif (returnCode != 0) {\n\t\t\tthrow handleResult(tcRuntime.runtimeLocation(), command, arguments, new Status(IStatus.ERROR,\n\t\t\t\t\tITcServerConstants.PLUGIN_ID, \"The instance creation command failed and returned code \"\n\t\t\t\t\t\t\t+ returnCode));\n\t\t}\n\n\t\t// verify result\n\t\tIPath instanceDirectory = getInstanceDirectory(arguments, instanceName);\n\t\tif (instanceDirectory == null) {\n\t\t\tinstanceDirectory = tcRuntime.instanceDirectory(instanceName);\n\t\t}\n\t\tIStatus status = validateInstance(instanceDirectory.toFile(), true);\n\t\tif (!status.isOK()) {\n\t\t\tthrow handleResult(tcRuntime.runtimeLocation(), command, arguments, status);\n\t\t}\n\t}\n\t\n\tprivate static IPath getInstanceDirectory(String[] arguments, String instanceName) {\n\t\tfor (int i = 0; i < arguments.length; i++) {\n\t\t\tif (arguments[i].equals(\"-i\") && arguments[i + 1] != null) {\n\t\t\t\treturn new Path(new File(arguments[i + 1], instanceName).toString());\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate static CoreException handleResult(IPath installLocation, ServerInstanceCommand command, String[] arguments,\n\t\t\tIStatus result) {\n\t\tStringBuilder cmdStr = new StringBuilder(command.toString());\n\t\tfor (String arg : arguments) {\n\t\t\tcmdStr.append(' ');\n\t\t\tcmdStr.append(arg);\n\t\t}\n\t\tMultiStatus status = new MultiStatus(\n\t\t\t\tITcServerConstants.PLUGIN_ID,\n\t\t\t\t0,\n\t\t\t\tNLS.bind(\n\t\t\t\t\t\t\"Error creating server instance with command:\\n \\\"{0}\\\". Check access permission for the directory {1} and its files and subdirectories.\",\n\t\t\t\t\t\tnew Object[] { cmdStr, installLocation }), null);\n\t\tif (result != null) {\n\t\t\tstatus.add(result);\n\t\t}\n\t\tIStatus output = new Status(IStatus.ERROR, ITcServerConstants.PLUGIN_ID,\n\t\t\t\t\"Output of the instance creation command:\\n\" + command.getOutput());\n\t\tstatus.add(output);\n\n\t\tTcServerCorePlugin.log(status);\n\n\t\treturn new CoreException(status);\n\t}\n\n\tpublic static String getInstanceTomcatVersion(File instanceFolder) {\n\t\tFile tomcatVersionFile = new File(new File(instanceFolder, \"conf\"), \"tomcat.version\");\n\t\tScanner scanner = null;\n\t\ttry {\n\t\t\tif (tomcatVersionFile.exists()) {\n\t\t\t\tscanner = new Scanner(tomcatVersionFile);\n\t\t\t\treturn scanner.useDelimiter(\"\\\\Z\").next().trim();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tcatch (FileNotFoundException e) {\n\t\t\treturn null;\n\t\t}\n\t\tfinally {\n\t\t\tif (scanner != null) {\n\t\t\t\tscanner.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static File getInstanceDirectory(ServerWorkingCopy wc) {\n\t\tif (wc != null) {\n\t\t\tString instanceDir = wc.getAttribute(TomcatServer.PROPERTY_INSTANCE_DIR, (String) null);\n\t\t\tif (instanceDir != null) {\n\t\t\t\tFile file = new File(instanceDir);\n\t\t\t\tif (file.exists()) {\n\t\t\t\t\treturn file;\n\t\t\t\t}\n\t\t\t}\n\t\t\tString serverName = wc.getAttribute(TcServer.KEY_SERVER_NAME, (String) null);\n\t\t\tif (serverName != null) {\n\t\t\t\tITcRuntime tcRuntime = getTcRuntime(wc.getRuntime());\n\t\t\t\tIPath path = tcRuntime == null ? wc.getRuntime().getLocation() : tcRuntime.instanceDirectory(serverName);\n\t\t\t\tFile directory = path.toFile();\n\t\t\t\tif (directory.exists()) {\n\t\t\t\t\treturn directory;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static void setTcServerDefaultName(IServerWorkingCopy wc) {\n\t\tServerUtil.setServerDefaultName(wc);\n\t\tString defaultName = wc.getName();\n\t\tString prefix = wc.getAttribute(TcServer.KEY_SERVER_NAME, (String) null);\n\t\tif (prefix != null && !prefix.isEmpty()) {\n\t\t\tString name = prefix + \" - \" + defaultName;\n\t\t\tint idx = name.lastIndexOf('(');\n\t\t\tif (idx != -1) {\n\t\t\t\tname = name.substring(0, idx).trim();\n\t\t\t}\n\t\t\tint i = 2;\n\t\t\tdefaultName = name;\n\t\t\twhile (ServerPlugin.isNameInUse(wc.getOriginal(), defaultName)) {\n\t\t\t\tdefaultName = name + \" (\" + i + \")\";\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\twc.setName(defaultName);\n\t}\n\n\tpublic static boolean isTcServerDefaultName(IServerWorkingCopy wc) {\n\t\tServerWorkingCopy defaultServer = new ServerWorkingCopy(null, null, wc.getRuntime(), wc.getServerType());\n\t\tdefaultServer.setAttribute(TcServer.KEY_SERVER_NAME, wc.getAttribute(TcServer.KEY_SERVER_NAME, (String) null));\n\t\tdefaultServer.setDefaults(new NullProgressMonitor());\n\t\treturn wc.getName().equals(defaultServer.getName());\n\t}\n\n\tstatic boolean isWindows() {\n\t\treturn File.separatorChar == '\\\\';\n\t}\n\t\n\tpublic static ITcRuntime getTcRuntime(IRuntime runtime) {\n\t\treturn (ITcRuntime) runtime.loadAdapter(ITcRuntime.class, new NullProgressMonitor());\n\t}\n\n\tpublic static String getCatalinaVersion(IPath tomcatLocation, String serverTypeID) {\n\t\tString version = TomcatVersionHelper.getCatalinaVersion(tomcatLocation, serverTypeID);\n\t\tif ((version == null || version.isEmpty()) && (tomcatLocation != null && !tomcatLocation.isEmpty())) {\n\t\t\tversion = getServerVersion(tomcatLocation.lastSegment());\n\t\t}\n\t\treturn version;\n\t}\n}" ]
import java.io.File; import java.text.MessageFormat; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jst.server.tomcat.core.internal.ITomcatServer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.wst.server.core.IServerWorkingCopy; import org.eclipse.wst.server.core.TaskModel; import org.eclipse.wst.server.core.internal.ServerWorkingCopy; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import org.eclipse.wst.server.ui.wizard.WizardFragment; import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.ITcRuntime; import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.ITcServerConstants; import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServer; import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServerCorePlugin; import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServerUtil;
GridDataFactory.fillDefaults().span(3, 1).applyTo(existingInstanceButton); serverNameLabel = new Label(composite, SWT.NONE); serverNameLabel.setText("Instance:"); GridData data = new GridData(); serverNameLabel.setLayoutData(data); serverNameCombo = new Combo(composite, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); serverNameCombo.setLayoutData(data); serverNameCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (existingInstanceButton.getSelection()) { updateInstanceNameFromWidget(); } } }); serverBrowseButton = new Button(composite, SWT.PUSH); serverBrowseButton.setText("Browse..."); serverBrowseButton.setLayoutData(new GridData()); serverBrowseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { handleLocationBrowseButtonPressed(); validate(); } }); serverNameCombo.setEnabled(false); serverNameLabel.setEnabled(false); serverBrowseButton.setEnabled(false); Label separator = new Label(composite, SWT.NONE); GridDataFactory.fillDefaults().span(3, 1).applyTo(separator); descriptionLabel = new Label(composite, SWT.WRAP); descriptionLabel.setBackground(composite.getBackground()); GridDataFactory.fillDefaults().span(3, 1).grab(true, false).applyTo(descriptionLabel); return composite; } private void updateInstanceNameFromWidget() { IPath serverPath = new Path(serverNameCombo.getText()); if (!serverPath.isEmpty() && serverPath.isAbsolute()) { wc.setAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, serverNameCombo.getText()); wc.setAttribute(TcServer.KEY_SERVER_NAME, (String) null); } else { wc.setAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, (String) null); wc.setAttribute(TcServer.KEY_SERVER_NAME, serverNameCombo.getText()); } validate(); } private void handleLocationBrowseButtonPressed() { File path = wc.getRuntime().getLocation().toFile(); DirectoryDialog dialog = new DirectoryDialog(serverBrowseButton.getShell()); dialog.setMessage("Select location"); if (path.exists()) { dialog.setFilterPath(path.toString()); } String selectedDirectory = dialog.open(); if (selectedDirectory != null) { serverNameCombo.add(selectedDirectory, 0); serverNameCombo.select(0); } } @Override protected void createChildFragments(List<WizardFragment> list) { if (newInstanceButton != null && newInstanceButton.getSelection()) { if (instanceCreationPage == null) { instanceCreationPage = new TcServer21InstanceCreationFragment(); } list.add(instanceCreationPage); } } @Override public void enter() { this.wc = (IServerWorkingCopy) getTaskModel().getObject(TaskModel.TASK_SERVER); initialize(); updateChildFragments(); validate(); } @Override public void exit() { if (isDefaultServerName) { TcServerUtil.setTcServerDefaultName(wc); } try { // load the configuration from the directory based on the selections // made on the wizard page ((ServerWorkingCopy) wc).importRuntimeConfiguration(wc.getRuntime(), null); } catch (CoreException e) { TcServerCorePlugin.log( new Status(IStatus.ERROR, TcServerUiPlugin.PLUGIN_ID, "Failed to load runtime configuration", e)); // Trace.trace(Trace.SEVERE, "Failed to load runtime configuration", // e); } } @Override public boolean hasComposite() { return true; } private IStatus doValidate() { if (newInstanceButton != null && newInstanceButton.getSelection()) { return Status.OK_STATUS; } ServerWorkingCopy workingCopy = (ServerWorkingCopy) wc; if (workingCopy.getAttribute(TcServer.KEY_SERVER_NAME, (String) null) == null && workingCopy.getAttribute(ITomcatServer.PROPERTY_INSTANCE_DIR, (String) null) == null) {
return new Status(IStatus.INFO, ITcServerConstants.PLUGIN_ID, SELECT_INSTANCE_MESSAGE);
1
fcrepo4-labs/fcrepo-api-x
fcrepo-api-x-jena/src/main/java/org/fcrepo/apix/jena/impl/LookupOntologyRegistry.java
[ "public static Model parse(final WebResource r, final String base) {\n\n if (r instanceof JenaResource && ((JenaResource) r).model() != null) {\n return ((JenaResource) r).model();\n }\n\n final Model model =\n ModelFactory.createDefaultModel();\n\n final Lang lang = rdfLanguage(r.contentType());\n\n try (WebResource toParse = r;\n InputStream representation = toParse.representation()) {\n RDFDataMgr.read(model, representation, base, lang);\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n\n return model;\n}", "public static final Lang rdfLanguage(final String contentType) {\n final int separator = contentType.indexOf(';');\n\n if (separator < 0) {\n return RDFLanguages.contentTypeToLang(contentType);\n } else {\n return RDFLanguages.contentTypeToLang(contentType.substring(0, separator));\n }\n}", "public interface Initializer {\n\n /**\n * Run an initialization task.\n * <p>\n * May run initialization task indefinitely or repeatedly until it succeeds, or is cancelled.\n * </p>\n *\n * @param task The task to run\n * @return initialization state\n */\n Initialization initialize(final Runnable task);\n\n /**\n * Represents initialization state.\n * <p>\n * Provides barriers that may be used to verify orr wait for initialization;\n * </p>\n *\n * @author apb@jhu.edu\n */\n public interface Initialization {\n\n /** No initialization. */\n static final Initialization NONE = new Initialization() {\n\n @Override\n public void await() {\n // Do nothing\n }\n\n @Override\n public void verify() {\n // Do nothing\n }\n\n @Override\n public void cancel() {\n // Do nothing\n }\n\n @Override\n public void await(final long time, final TimeUnit unit) throws TimeoutException {\n // Do nothing\n }\n\n };\n\n /**\n * Await for initialization to succeed, blocking as necessary.\n * <p>\n * This may be used as an initialization barrier, preventing other threads from progressing until\n * initialization is finished. Called from within the initialization routine, this will not block.\n * </p>\n *\n * @throws RuntimeException if initialization fails.\n */\n void await();\n\n /**\n * Await for the initialization to succeed, blocking, for the specified time limit *\n * <p>\n * This may be used as an initialization barrier, preventing other threads from progressing until\n * initialization is finished. Called from within the initialization routine, this will not block.\n * </p>\n *\n * @param time Time to wait.\n * @param unit time units.\n * @throws TimeoutException Thrown when time limit exceeded\n */\n public void await(final long time, final TimeUnit unit) throws TimeoutException;\n\n /**\n * Throw an exception if not initialized.\n * <p>\n * If called within the initialization routine, this will not throw an exception.\n * </p>\n *\n * @throws RuntimeException id not initialized.\n */\n void verify();\n\n /**\n * Cancel an initialization, if it's still running.\n */\n void cancel();\n }\n}", "public interface Initialization {\n\n /** No initialization. */\n static final Initialization NONE = new Initialization() {\n\n @Override\n public void await() {\n // Do nothing\n }\n\n @Override\n public void verify() {\n // Do nothing\n }\n\n @Override\n public void cancel() {\n // Do nothing\n }\n\n @Override\n public void await(final long time, final TimeUnit unit) throws TimeoutException {\n // Do nothing\n }\n\n };\n\n /**\n * Await for initialization to succeed, blocking as necessary.\n * <p>\n * This may be used as an initialization barrier, preventing other threads from progressing until\n * initialization is finished. Called from within the initialization routine, this will not block.\n * </p>\n *\n * @throws RuntimeException if initialization fails.\n */\n void await();\n\n /**\n * Await for the initialization to succeed, blocking, for the specified time limit *\n * <p>\n * This may be used as an initialization barrier, preventing other threads from progressing until\n * initialization is finished. Called from within the initialization routine, this will not block.\n * </p>\n *\n * @param time Time to wait.\n * @param unit time units.\n * @throws TimeoutException Thrown when time limit exceeded\n */\n public void await(final long time, final TimeUnit unit) throws TimeoutException;\n\n /**\n * Throw an exception if not initialized.\n * <p>\n * If called within the initialization routine, this will not throw an exception.\n * </p>\n *\n * @throws RuntimeException id not initialized.\n */\n void verify();\n\n /**\n * Cancel an initialization, if it's still running.\n */\n void cancel();\n}", "public interface OntologyRegistry extends Registry {\n\n /**\n * Get an ontology by Ontology IRI or location\n *\n * @param id URI representing an Ontology IRI or location.\n * @return A resource containing a serialized ontology.\n */\n @Override\n public WebResource get(URI id);\n\n /**\n * Persist an ontology in the registry.\n * <p>\n * If the ontology contains a <code>&lt;ontologyIRI&gt; a owl:Ontology</code>, the ontology registry shall index\n * <code>ontologyIRI</code> such that {@link #get(URI)} with argument <code>ontologyIRI</code>.\n * </p>\n *\n * @param ontology Serialized ontology.\n * @return URI containing the location of the persisted ontology.\n */\n @Override\n public URI put(WebResource ontology);\n\n /**\n * Persist an ontology with a specified ontology IRI.\n * <p>\n * If the underlying ontology does not have an OWL ontology IRI declared within it, such statements will be added.\n * </p>\n *\n * @param ontology Serialized ontology.\n * @param ontologyIRI Desired ontology IRI\n * @return URI containing the location of the persisted ontology.\n */\n public URI put(WebResource ontology, URI ontologyIRI);\n\n /**\n * Determine if the registry contains the given location or ontology IRI. {@inheritDoc}\n *\n * @param id Ontology location or Ontology IRI.\n */\n @Override\n public boolean contains(URI id);\n\n}", "public interface Updateable {\n\n /**\n * Update internal state, in whatever manner is appropriate.\n */\n void update();\n\n /**\n * Update internal state in response to changes to the given resource.\n * <p>\n * Given the identity of a resource that mat have changed, an implementation may decide if and how to update\n * itself.\n * </p>\n *\n * @param inResponseTo URI of some web resource.\n */\n void update(URI inResponseTo);\n\n}" ]
import static org.fcrepo.apix.jena.Util.parse; import static org.fcrepo.apix.jena.Util.rdfLanguage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.URI; import java.util.AbstractMap.SimpleEntry; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BinaryOperator; import java.util.stream.Collectors; import org.fcrepo.apix.model.WebResource; import org.fcrepo.apix.model.components.Initializer; import org.fcrepo.apix.model.components.Initializer.Initialization; import org.fcrepo.apix.model.components.OntologyRegistry; import org.fcrepo.apix.model.components.Registry; import org.fcrepo.apix.model.components.Updateable; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Licensed to DuraSpace under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * DuraSpace 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.fcrepo.apix.jena.impl; /** * Allows lookup by ontologyURI as well as location. * <p> * For any ontology in underlying registry, will allow retriving that ontology by its location URI, or ontologyIRI * (which may be different). To do so, it maintains an in-memory map of ontology URIs to location. It is an error to * have the same ontology IRI in more than one entry in the registry. * </p> * <p> * This indexes all ontologies upon initialization (if {@link #isIndexIRIs()} is {@code true}), and maintains the * index in response to {@link #put(WebResource)} or {@link #put(WebResource, URI)}. * </p> * <p> * For ontology registries backed by an LDP container in the repository, this class may be used by an asynchronous * message consumer to update the ontology registry in response to ontologies added/removed manually by clients via * LDP interactions with the repository. * </p> * * @author apb@jhu.edu */ public class LookupOntologyRegistry implements OntologyRegistry, Updateable { static final String RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; static final String OWL_ONTOLOGY = "http://www.w3.org/2002/07/owl#Ontology"; private final Map<URI, URI> ontologyIRIsToLocation = new ConcurrentHashMap<>(); private Registry registry; private boolean indexIRIs = true; private Initializer initializer;
private Initialization init = Initialization.NONE;
3
mp911de/spinach
src/test/java/biz/paluch/spinach/examples/PeriodicallyUpdatingSocketAddressSupplierFactory.java
[ "@SuppressWarnings(\"serial\")\npublic class DisqueURI implements Serializable {\n\n public static final String URI_SCHEME_DISQUE = \"disque\";\n public static final String URI_SCHEME_DISQUE_SOCKET = \"disque-socket\";\n public static final String URI_SCHEME_DISQUE_SECURE = \"disques\";\n\n /**\n * The default Disque port.\n */\n public static final int DEFAULT_DISQUE_PORT = 7711;\n\n private char[] password = new char[0];\n private boolean ssl = false;\n private boolean verifyPeer = true;\n private boolean startTls = false;\n private long timeout = 60;\n private TimeUnit unit = TimeUnit.SECONDS;\n private final List<ConnectionPoint> connectionPoints = new ArrayList<ConnectionPoint>();\n\n /**\n * Default empty constructor.\n */\n public DisqueURI() {\n }\n\n /**\n * Constructor with host/port and timeout.\n * \n * @param host the host string, must not be empty\n * @param port the port, must be in the range between {@literal 1} to {@literal 65535}\n * @param timeout timeout value\n * @param unit unit of the timeout value\n */\n public DisqueURI(String host, int port, long timeout, TimeUnit unit) {\n\n DisqueHostAndPort hap = new DisqueHostAndPort();\n hap.setHost(host);\n hap.setPort(port);\n connectionPoints.add(hap);\n\n this.timeout = timeout;\n this.unit = unit;\n }\n\n /**\n * Create a Disque URI from {@code host} and {@code port}.\n *\n * @param host the host string, must not be empty\n * @param port the port, must be in the range between {@literal 1} to {@literal 65535}\n * @return An instance of {@link DisqueURI} containing details from the URI.\n */\n public static DisqueURI create(String host, int port) {\n return new Builder().withDisque(host, port).build();\n }\n\n /**\n * Create a Disque URI from an URI string. Supported formats are:\n * <ul>\n * <li>disque://[password@]host[:port][,host2[:port2]][,hostN[:port2N]]</li>\n * <li>disques://[password@]host[:port][,host2[:port2]][,hostN[:port2N]]</li>\n * <li>disque-socket://socket-path</li>\n * </ul>\n *\n * The {@code uri} must follow conventions of {@link java.net.URI}\n * \n * @param uri the URI string\n * @return An instance of {@link DisqueURI} containing details from the URI\n */\n public static DisqueURI create(String uri) {\n return create(URI.create(uri));\n }\n\n /**\n * Create a Disque URI from an URI string. Supported formats are:\n * <ul>\n * <li>disque://[password@]host[:port][,host2[:port2]][,hostN[:port2N]]</li>\n * <li>disques://[password@]host[:port][,host2[:port2]][,hostN[:port2N]]</li>\n * <li>disque-socket://socket-path</li>\n * </ul>\n *\n * The {@code uri} must follow conventions of {@link java.net.URI}\n *\n * @param uri the URI\n * @return An instance of {@link DisqueURI} containing details from the URI\n */\n public static DisqueURI create(URI uri) {\n\n DisqueURI.Builder builder;\n builder = configureDisque(uri);\n\n if (URI_SCHEME_DISQUE_SECURE.equals(uri.getScheme())) {\n builder.withSsl(true);\n }\n\n String userInfo = uri.getUserInfo();\n\n if (isEmpty(userInfo) && isNotEmpty(uri.getAuthority()) && uri.getAuthority().indexOf('@') > 0) {\n userInfo = uri.getAuthority().substring(0, uri.getAuthority().indexOf('@'));\n }\n\n if (isNotEmpty(userInfo)) {\n String password = userInfo;\n if (password.startsWith(\":\")) {\n password = password.substring(1);\n }\n builder.withPassword(password);\n }\n\n return builder.build();\n }\n\n private static DisqueURI.Builder configureDisque(URI uri) {\n DisqueURI.Builder builder = null;\n\n if (URI_SCHEME_DISQUE_SOCKET.equals(uri.getScheme())) {\n builder = Builder.disqueSocket(uri.getPath());\n } else\n\n if (isNotEmpty(uri.getHost())) {\n if (uri.getPort() != -1) {\n builder = DisqueURI.Builder.disque(uri.getHost(), uri.getPort());\n } else {\n builder = DisqueURI.Builder.disque(uri.getHost());\n }\n }\n\n if (builder == null && isNotEmpty(uri.getAuthority())) {\n String authority = uri.getAuthority();\n if (authority.indexOf('@') > -1) {\n authority = authority.substring(authority.indexOf('@') + 1);\n }\n\n String[] hosts = authority.split(\"\\\\,\");\n for (String host : hosts) {\n if (uri.getScheme().equals(URI_SCHEME_DISQUE_SOCKET)) {\n if (builder == null) {\n builder = DisqueURI.Builder.disqueSocket(host);\n } else {\n builder.withSocket(host);\n }\n } else {\n HostAndPort hostAndPort = HostAndPort.parse(host);\n if (builder == null) {\n if (hostAndPort.hasPort()) {\n builder = DisqueURI.Builder.disque(hostAndPort.getHostText(), hostAndPort.getPort());\n } else {\n builder = DisqueURI.Builder.disque(hostAndPort.getHostText());\n }\n } else {\n if (hostAndPort.hasPort()) {\n builder.withDisque(hostAndPort.getHostText(), hostAndPort.getPort());\n } else {\n builder.withDisque(hostAndPort.getHostText());\n }\n }\n }\n }\n\n }\n\n LettuceAssert.notNull(builder, \"Invalid URI, cannot get host part\");\n return builder;\n }\n\n public char[] getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password.toCharArray();\n }\n\n public long getTimeout() {\n return timeout;\n }\n\n public void setTimeout(long timeout) {\n this.timeout = timeout;\n }\n\n public TimeUnit getUnit() {\n return unit;\n }\n\n public void setUnit(TimeUnit unit) {\n this.unit = unit;\n }\n\n public boolean isSsl() {\n return ssl;\n }\n\n public void setSsl(boolean ssl) {\n this.ssl = ssl;\n }\n\n public boolean isVerifyPeer() {\n return verifyPeer;\n }\n\n public void setVerifyPeer(boolean verifyPeer) {\n this.verifyPeer = verifyPeer;\n }\n\n public boolean isStartTls() {\n return startTls;\n }\n\n public void setStartTls(boolean startTls) {\n this.startTls = startTls;\n }\n\n public List<ConnectionPoint> getConnectionPoints() {\n return connectionPoints;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" \").append(connectionPoints);\n return sb.toString();\n }\n\n /**\n * Builder for Disque URI.\n */\n public static class Builder {\n\n private final DisqueURI disqueURI = new DisqueURI();\n\n /**\n * Set Disque host. Creates a new builder.\n * \n * @param host the host string, must not be empty\n * @return New builder with Disque host and the default Disque port\n */\n public static Builder disque(String host) {\n return disque(host, DEFAULT_DISQUE_PORT);\n }\n\n /**\n * Set Disque host and port. Creates a new builder.\n * \n * @param host the host string, must not be empty\n * @param port the port, must be in the range between {@literal 1} to {@literal 65535}\n * @return New builder with Disque host/port\n */\n public static Builder disque(String host, int port) {\n Builder builder = new Builder();\n builder.withDisque(host, port);\n\n return builder;\n }\n\n /**\n * Set Disque socket. Creates a new builder.\n * \n * @param socket the socket name, must not be empty\n * @return New builder with Disque socket\n */\n public static Builder disqueSocket(String socket) {\n Builder builder = new Builder();\n builder.withSocket(socket);\n return builder;\n }\n\n /**\n * Set Disque socket.\n * \n * @param socket the socket name, must not be empty\n * @return the builder\n */\n public Builder withSocket(String socket) {\n this.disqueURI.connectionPoints.add(new DisqueSocket(socket));\n return this;\n }\n\n /**\n * Set Disque host\n * \n * @param host the host string, must not be empty\n * @return the builder\n */\n public Builder withDisque(String host) {\n return withDisque(host, DEFAULT_DISQUE_PORT);\n }\n\n /**\n * Set Disque host and port.\n * \n * @param host the host string, must not be empty\n * @param port the port, must be in the range between {@literal 1} to {@literal 65535}\n * @return the builder\n */\n public Builder withDisque(String host, int port) {\n DisqueHostAndPort hap = new DisqueHostAndPort(host, port);\n this.disqueURI.connectionPoints.add(hap);\n return this;\n }\n\n /**\n * Adds ssl information to the builder.\n *\n * @param ssl {@literal true} if use SSL\n * @return the builder\n */\n public Builder withSsl(boolean ssl) {\n disqueURI.setSsl(ssl);\n return this;\n }\n\n /**\n * Enables/disables StartTLS when using SSL.\n *\n * @param startTls {@literal true} if use StartTLS\n * @return the builder\n */\n public Builder withStartTls(boolean startTls) {\n disqueURI.setStartTls(startTls);\n return this;\n }\n\n /**\n * Enables/disables peer verification.\n *\n * @param verifyPeer {@literal true} to verify hosts when using SSL\n * @return the builder\n */\n public Builder withVerifyPeer(boolean verifyPeer) {\n disqueURI.setVerifyPeer(verifyPeer);\n return this;\n }\n\n /**\n * Adds authentication.\n * \n * @param password the password\n * @return the builder\n */\n public Builder withPassword(String password) {\n LettuceAssert.notNull(password, \"Password must not be null\");\n disqueURI.setPassword(password);\n return this;\n }\n\n /**\n * Adds timeout.\n * \n * @param timeout must be greater or equal {@literal 0}.\n * @param unit the timeout time unit.\n * @return the builder\n */\n public Builder withTimeout(long timeout, TimeUnit unit) {\n\n LettuceAssert.notNull(unit, \"TimeUnit must not be null\");\n LettuceAssert.isTrue(timeout >= 0, \"Timeout must be greater or equal 0\");\n\n disqueURI.setTimeout(timeout);\n disqueURI.setUnit(unit);\n return this;\n }\n\n /**\n * Build a the {@link DisqueURI}.\n * \n * @return the DisqueURI.\n */\n public DisqueURI build() {\n return disqueURI;\n }\n\n }\n\n /**\n * A Unix Domain Socket connection-point.\n */\n public static class DisqueSocket implements Serializable, ConnectionPoint {\n private String socket;\n private transient SocketAddress resolvedAddress;\n\n public DisqueSocket() {\n }\n\n public DisqueSocket(String socket) {\n LettuceAssert.notEmpty(socket, \"Socket must not be empty\");\n this.socket = socket;\n }\n\n @Override\n public String getHost() {\n return null;\n }\n\n @Override\n public int getPort() {\n return -1;\n }\n\n @Override\n public String getSocket() {\n return socket;\n }\n\n public void setSocket(String socket) {\n LettuceAssert.notEmpty(socket, \"Socket must not be empty\");\n this.socket = socket;\n }\n\n public SocketAddress getSocketAddress() {\n if (resolvedAddress == null) {\n resolvedAddress = new DomainSocketAddress(getSocket());\n }\n return resolvedAddress;\n }\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(socket.length());\n sb.append(socket);\n return sb.toString();\n }\n }\n\n /**\n * A Network connection-point.\n */\n public static class DisqueHostAndPort implements Serializable, ConnectionPoint {\n\n private String host;\n private int port;\n\n public DisqueHostAndPort() {\n }\n\n public DisqueHostAndPort(String host, int port) {\n LettuceAssert.notEmpty(host, \"Host must not be empty\");\n LettuceAssert.isTrue(isValidPort(port), \"Port is out of range\");\n this.host = host;\n this.port = port;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n LettuceAssert.notEmpty(host, \"Host must not be empty\");\n this.host = host;\n }\n\n public int getPort() {\n return port;\n }\n\n @Override\n public String getSocket() {\n return null;\n }\n\n public void setPort(int port) {\n LettuceAssert.isTrue(isValidPort(port), \"Port is out of range\");\n this.port = port;\n }\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer();\n sb.append(host);\n sb.append(\":\").append(port);\n return sb.toString();\n }\n\n /**\n *\n * @param port the port number\n * @return {@literal true} for valid port numbers\n */\n static boolean isValidPort(int port) {\n return port >= 1 && port <= 65535;\n }\n }\n}", "public interface DisqueConnection<K, V> extends StatefulConnection<K, V> {\n\n /**\n * Returns the {@link DisqueCommands} API for the current connection. Does not create a new connection.\n * \n * @return the synchronous API for the underlying connection.\n */\n DisqueCommands<K, V> sync();\n\n /**\n * Returns the {@link DisqueAsyncCommands} API for the current connection. Does not create a new connection.\n * \n * @return the asynchronous API for the underlying connection.\n */\n DisqueAsyncCommands<K, V> async();\n\n /**\n * Returns the {@link DisqueReactiveCommands} API for the current connection. Does not create a new connection.\n *\n * @return the reactive API for the underlying connection.\n */\n DisqueReactiveCommands<K, V> reactive();\n\n}", "public class HelloClusterSocketAddressSupplier extends ClusterAwareNodeSupport implements SocketAddressSupplier,\n ConnectionAware {\n\n protected final SocketAddressSupplier bootstrap;\n protected RoundRobin<DisqueNode> roundRobin;\n\n /**\n * \n * @param bootstrap bootstrap/fallback {@link SocketAddressSupplier} for bootstrapping before any communication is done.\n */\n public HelloClusterSocketAddressSupplier(SocketAddressSupplier bootstrap) {\n this.bootstrap = bootstrap;\n }\n\n @Override\n public SocketAddress get() {\n\n if (getNodes().isEmpty()) {\n return bootstrap.get();\n }\n\n DisqueNode disqueNode = roundRobin.next();\n return InetSocketAddress.createUnresolved(disqueNode.getAddr(), disqueNode.getPort());\n }\n\n @Override\n public <K, V> void setConnection(DisqueConnection<K, V> disqueConnection) {\n super.setConnection(disqueConnection);\n reloadNodes();\n }\n\n @Override\n public void reloadNodes() {\n super.reloadNodes();\n roundRobin = new RoundRobin<DisqueNode>(getNodes());\n }\n\n}", "public class RoundRobinSocketAddressSupplier implements SocketAddressSupplier {\n\n protected final Collection<? extends ConnectionPoint> connectionPoint;\n protected RoundRobin<? extends ConnectionPoint> roundRobin;\n\n /**\n * \n * @param connectionPoints the collection of {@link ConnectionPoint connection points}, must not be {@literal null}.\n */\n public RoundRobinSocketAddressSupplier(Collection<? extends ConnectionPoint> connectionPoints) {\n this(connectionPoints, null);\n }\n\n /**\n * \n * @param connectionPoints the collection of {@link ConnectionPoint connection points}, must not be {@literal null}.\n * @param offset {@link ConnectionPoint connection point} offset for starting the round robin cycle at that point, can be\n * {@literal null}.\n */\n public RoundRobinSocketAddressSupplier(Collection<? extends ConnectionPoint> connectionPoints, ConnectionPoint offset) {\n LettuceAssert.notNull(connectionPoints, \"ConnectionPoints must not be null\");\n this.connectionPoint = connectionPoints;\n this.roundRobin = new RoundRobin<ConnectionPoint>(connectionPoints, offset);\n }\n\n @Override\n public SocketAddress get() {\n ConnectionPoint connectionPoint = roundRobin.next();\n return getSocketAddress(connectionPoint);\n }\n\n protected static SocketAddress getSocketAddress(ConnectionPoint connectionPoint) {\n\n if (connectionPoint instanceof DisqueURI.DisqueSocket) {\n return ((DisqueURI.DisqueSocket) connectionPoint).getSocketAddress();\n }\n return InetSocketAddress.createUnresolved(connectionPoint.getHost(), connectionPoint.getPort());\n }\n}", "public interface SocketAddressSupplier extends Supplier<SocketAddress> {\n\n}", "public interface SocketAddressSupplierFactory {\n\n /**\n * Creates a new {@link SocketAddressSupplier} from a {@link SocketAddressSupplier}.\n * \n * @param disqueURI the connection URI object, must not be {@literal null}\n * @return an new instance of {@link SocketAddressSupplier}\n */\n SocketAddressSupplier newSupplier(DisqueURI disqueURI);\n\n enum Factories implements SocketAddressSupplierFactory {\n /**\n * Round-Robin address supplier that runs circularly over the provided connection points within the {@link DisqueURI}.\n */\n ROUND_ROBIN {\n @Override\n public SocketAddressSupplier newSupplier(DisqueURI disqueURI) {\n LettuceAssert.notNull(disqueURI, \"DisqueURI must not be null\");\n return new RoundRobinSocketAddressSupplier(LettuceLists.unmodifiableList(disqueURI.getConnectionPoints()));\n }\n },\n\n /**\n * Cluster-topology-aware address supplier that obtains its initial connection point from the {@link DisqueURI} and then\n * looks up the cluster topology using the {@code HELLO} command. Connections are established using the cluster node IP\n * addresses.\n */\n HELLO_CLUSTER {\n @Override\n public SocketAddressSupplier newSupplier(DisqueURI disqueURI) {\n LettuceAssert.notNull(disqueURI, \"DisqueURI must not be null\");\n return new HelloClusterSocketAddressSupplier(ROUND_ROBIN.newSupplier(disqueURI));\n }\n };\n\n @Override\n public SocketAddressSupplier newSupplier(DisqueURI disqueURI) {\n return null;\n }\n }\n}" ]
import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import biz.paluch.spinach.DisqueURI; import biz.paluch.spinach.api.DisqueConnection; import biz.paluch.spinach.impl.HelloClusterSocketAddressSupplier; import biz.paluch.spinach.impl.RoundRobinSocketAddressSupplier; import biz.paluch.spinach.impl.SocketAddressSupplier; import biz.paluch.spinach.impl.SocketAddressSupplierFactory; import io.netty.util.internal.ConcurrentSet;
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package biz.paluch.spinach.examples; /** * @author Mark Paluch */ public class PeriodicallyUpdatingSocketAddressSupplierFactory implements SocketAddressSupplierFactory { private final ScheduledExecutorService scheduledExecutorService; private final Set<ScheduledFuture<?>> futures = new ConcurrentSet<>(); public PeriodicallyUpdatingSocketAddressSupplierFactory(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; } @Override
public SocketAddressSupplier newSupplier(DisqueURI disqueURI) {
0
danielflower/app-runner
src/main/java/com/danielflower/apprunner/AppEstate.java
[ "public interface AppDescription {\n String name();\n\n String gitUrl();\n\n void gitUrl(String url) throws URISyntaxException, GitAPIException;\n\n Availability currentAvailability();\n\n BuildStatus lastBuildStatus();\n\n BuildStatus lastSuccessfulBuild();\n\n String latestBuildLog();\n\n String latestConsoleLog();\n\n ArrayList<String> contributors();\n\n File dataDir();\n\n void stopApp() throws Exception;\n\n void update(AppRunnerFactoryProvider runnerProvider, InvocationOutputHandler outputHandler) throws Exception;\n\n void delete();\n}", "public class AppManager implements AppDescription {\n public static final Logger log = LoggerFactory.getLogger(AppManager.class);\n private static final Executor deletionQueue = Executors.newSingleThreadExecutor();\n public static final int REMOTE_GIT_TIMEOUT = 300;\n\n public static AppManager create(String gitUrl, FileSandbox fileSandbox, String name) throws IOException, GitAPIException {\n if (!name.matches(\"^[A-Za-z0-9_-]+$\")) {\n throw new ValidationException(\"The app name can only contain letters, numbers, hyphens and underscores\");\n }\n\n File gitDir = fileSandbox.repoDir(name);\n File instanceDir = fileSandbox.tempDir(name + File.separator + \"instances\");\n File dataDir = fileSandbox.appDir(name, \"data\");\n File tempDir = fileSandbox.tempDir(name);\n File[] dirsToDelete = { gitDir, tempDir, fileSandbox.appDir(name) };\n\n Git git;\n boolean isNew = false;\n try {\n git = Git.open(gitDir);\n isNew = true;\n } catch (RepositoryNotFoundException e) {\n log.info(\"Clone app \" + name + \" from \" + gitUrl + \" to \" + Mutils.fullPath(gitDir));\n git = Git.cloneRepository()\n .setURI(gitUrl)\n .setBare(false)\n .setDirectory(gitDir)\n .setTimeout(REMOTE_GIT_TIMEOUT)\n .call();\n }\n\n StoredConfig gitCfg = git.getRepository().getConfig();\n gitCfg.setString(\"remote\", \"origin\", \"url\", gitUrl);\n try {\n gitCfg.save();\n } catch (IOException e) {\n throw new AppRunnerException(\"Error while setting remote on Git repo at \" + gitDir, e);\n }\n log.info(\"Created app manager for \" + name + \" in dir \" + dataDir);\n GitCommit gitCommit = getCurrentHead(name, git);\n AppManager appManager = new AppManager(name, gitUrl, git, instanceDir, dataDir, tempDir, gitCommit, dirsToDelete);\n if (isNew) {\n appManager.gitUpdateFromOrigin();\n }\n return appManager;\n }\n\n public static int getAFreePort() {\n try {\n try (ServerSocket serverSocket = new ServerSocket(0)) {\n return serverSocket.getLocalPort();\n }\n } catch (IOException e) {\n throw new AppRunnerException(\"Unable to get a port\", e);\n }\n }\n\n private GitCommit getCurrentHead() {\n return getCurrentHead(name, git);\n }\n private static GitCommit getCurrentHead(String name, Git git) {\n GitCommit gitCommit = null;\n try {\n gitCommit = GitCommit.fromHEAD(git);\n } catch (Exception e) {\n log.warn(\"Could not find git commit info for \" + name, e);\n }\n return gitCommit;\n }\n\n private void gitUpdateFromOrigin() throws GitAPIException {\n FetchResult fetchResult = git.fetch().setRemote(\"origin\").setTimeout(REMOTE_GIT_TIMEOUT).call();\n Ref headRef = fetchResult.getAdvertisedRef(Constants.HEAD);\n if (headRef != null) {\n git.checkout().setForced(true).setName(headRef.getObjectId().getName()).call();\n } else {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(\"origin/master\").call();\n }\n this.contributors = getContributorsFromRepo();\n }\n\n private volatile String gitUrl;\n private final String name;\n private final Git git;\n private final File instanceDir;\n private final File dataDir;\n private final File tempDir;\n private final File[] dirsToDelete;\n private ArrayList<String> contributors;\n private final List<AppChangeListener> listeners = new ArrayList<>();\n private volatile AppRunner currentRunner;\n private String latestBuildLog;\n private final CircularFifoQueue<String> consoleLog = new CircularFifoQueue<>(5000);\n private volatile Availability availability = Availability.unavailable(\"Not started\");\n private volatile BuildStatus lastBuildStatus;\n private volatile BuildStatus lastSuccessfulBuildStatus;\n\n private AppManager(String name, String gitUrl, Git git, File instanceDir, File dataDir, File tempDir, GitCommit gitCommit, File[] dirsToDelete) {\n this.gitUrl = gitUrl;\n this.name = name;\n this.git = git;\n this.instanceDir = instanceDir;\n this.dataDir = dataDir;\n this.tempDir = tempDir;\n this.dirsToDelete = dirsToDelete;\n this.contributors = new ArrayList<>();\n this.lastBuildStatus = BuildStatus.notStarted(gitCommit);\n }\n\n public String name() {\n return name;\n }\n\n public String gitUrl() {\n return gitUrl;\n }\n\n public void gitUrl(String url) throws URISyntaxException, GitAPIException {\n Objects.requireNonNull(url, \"url\");\n git.remoteSetUrl().setRemoteName(\"origin\").setRemoteUri(new URIish(url)).call();\n this.gitUrl = url;\n }\n\n @Override\n public Availability currentAvailability() {\n return availability;\n }\n\n @Override\n public BuildStatus lastBuildStatus() {\n return lastBuildStatus;\n }\n\n @Override\n public BuildStatus lastSuccessfulBuild() {\n return lastSuccessfulBuildStatus;\n }\n\n public String latestBuildLog() {\n return latestBuildLog;\n }\n\n public String latestConsoleLog() {\n synchronized (consoleLog) {\n return String.join(\"\", consoleLog);\n }\n }\n\n public ArrayList<String> contributors() {\n return contributors;\n }\n\n @Override\n public File dataDir() {\n return this.dataDir;\n }\n\n public synchronized void stopApp() throws Exception {\n if (currentRunner != null) {\n availability = Availability.unavailable(\"Stopping\");\n currentRunner.shutdown();\n currentRunner = null;\n availability = Availability.unavailable(\"Stopped\");\n }\n }\n\n public synchronized void update(AppRunnerFactoryProvider runnerProvider, InvocationOutputHandler outputHandler) throws Exception {\n clearLogs();\n markBuildAsFetching();\n\n LineConsumer buildLogHandler = line -> {\n try {\n outputHandler.consumeLine(line);\n } catch (IOException ignored) {\n }\n latestBuildLog += line + System.lineSeparator();\n };\n\n // Well this is complicated.\n // Basically, we want the build log to contain a bit of the startup, and then detach itself.\n AtomicReference<LineConsumer> buildLogHandle = new AtomicReference<>(buildLogHandler);\n LineConsumer consoleLogHandler = line -> {\n LineConsumer another = buildLogHandle.get();\n if (another != null) {\n another.consumeLine(StringUtils.stripEnd(line, \"\\r\\n\"));\n }\n synchronized (consoleLog) {\n consoleLog.add(line);\n }\n };\n\n\n buildLogHandler.consumeLine(\"Fetching latest changes from git...\");\n File instanceDir = fetchChangesAndCreateInstanceDir();\n buildLogHandler.consumeLine(\"Created new instance in \" + fullPath(instanceDir));\n\n AppRunner oldRunner = currentRunner;\n AppRunnerFactory appRunnerFactory = runnerProvider.runnerFor(name(), instanceDir);\n String runnerId = appRunnerFactory.id();\n markBuildAsStarting(runnerId);\n AppRunner newRunner = appRunnerFactory.appRunner(instanceDir);\n log.info(\"Using \" + appRunnerFactory.id() + \" for \" + name);\n int port = getAFreePort();\n\n Map<String, String> envVarsForApp = createAppEnvVars(port, name, dataDir, tempDir);\n\n try (Waiter startupWaiter = Waiter.waitForApp(name, port)) {\n newRunner.start(buildLogHandler, consoleLogHandler, envVarsForApp, startupWaiter);\n } catch (Exception e) {\n newRunner.shutdown();\n recordBuildFailure(\"Crashed during startup\", runnerId);\n throw e;\n }\n currentRunner = newRunner;\n recordBuildSuccess(runnerId);\n buildLogHandle.set(null);\n\n for (AppChangeListener listener : listeners) {\n listener.onAppStarted(name, new URL(\"http://localhost:\" + port + \"/\" + name));\n }\n if (oldRunner != null) {\n buildLogHandler.consumeLine(\"Shutting down previous version\");\n log.info(\"Shutting down previous version of \" + name);\n oldRunner.shutdown();\n buildLogHandler.consumeLine(\"Deployment complete.\");\n File oldInstanceDir = oldRunner.getInstanceDir();\n quietlyDeleteTheOldInstanceDirInTheBackground(oldInstanceDir);\n }\n }\n\n @Override\n public void delete() {\n git.close();\n for (File dir : dirsToDelete) {\n try {\n log.info(\"Deleting \" + Mutils.fullPath(dir));\n // pack files are read-only so we need to override that or delete fails on Windows\n // (on Linux it's not necessary because the directory is writable, but it does no harm)\n PathUtils.deleteDirectory(dir.toPath(), StandardDeleteOption.OVERRIDE_READ_ONLY);\n } catch (IOException e) {\n log.warn(\"Failed to delete \" + Mutils.fullPath(dir) + \" - message was \" + e.getMessage(), e);\n }\n }\n }\n\n private void markBuildAsFetching() {\n lastBuildStatus = BuildStatus.fetching(Instant.now());\n if (!availability.isAvailable) {\n availability = Availability.unavailable(\"Starting\");\n }\n }\n\n private void markBuildAsStarting(String runnerId) {\n lastBuildStatus = BuildStatus.inProgress(Instant.now(), getCurrentHead(), runnerId);\n if (!availability.isAvailable) {\n availability = Availability.unavailable(\"Starting\");\n }\n }\n\n private void recordBuildSuccess(String runnerId) {\n lastBuildStatus = lastSuccessfulBuildStatus = BuildStatus.success(lastBuildStatus.startTime, Instant.now(), getCurrentHead(), runnerId);\n availability = Availability.available();\n }\n\n private void recordBuildFailure(String message, String runnerId) {\n lastBuildStatus = BuildStatus.failure(lastBuildStatus.startTime, Instant.now(), message, getCurrentHead(), runnerId);\n if (!availability.isAvailable) {\n availability = Availability.unavailable(message);\n }\n }\n\n private static void quietlyDeleteTheOldInstanceDirInTheBackground(final File instanceDir) {\n deletionQueue.execute(() -> {\n try {\n log.info(\"Going to delete \" + fullPath(instanceDir));\n if (instanceDir.isDirectory()) {\n FileUtils.deleteDirectory(instanceDir);\n }\n log.info(\"Deletion completion\");\n } catch (Exception e) {\n log.info(\"Couldn't delete \" + fullPath(instanceDir) +\n \" but it doesn't really matter as it will get deleted on next AppRunner startup.\");\n }\n });\n }\n\n private File fetchChangesAndCreateInstanceDir() throws GitAPIException, IOException {\n try {\n gitUpdateFromOrigin();\n return copyToNewInstanceDir();\n } catch (Exception e) {\n recordBuildFailure(\"Could not fetch from git: \" + e.getMessage(), null);\n throw e;\n }\n }\n\n private ArrayList<String> getContributorsFromRepo() {\n ArrayList<String> contributors = new ArrayList<>();\n try {\n // get authors\n Iterable<RevCommit> commits = git.log().all().call();\n for (RevCommit commit : commits) {\n String author = commit.getAuthorIdent().getName();\n if (!contributors.contains(author)) {\n contributors.add(author);\n }\n }\n log.info(\"getting the contributors \" + contributors);\n } catch (Exception e) {\n log.warn(\"Failed to get authors from repo: \" + e.getMessage());\n }\n return contributors;\n }\n\n private void clearLogs() {\n latestBuildLog = \"\";\n synchronized (consoleLog) {\n consoleLog.clear();\n }\n }\n\n public static Map<String, String> createAppEnvVars(int port, String name, File dataDir, File tempDir) {\n HashMap<String, String> envVarsForApp = new HashMap<>(System.getenv());\n envVarsForApp.put(\"APP_PORT\", String.valueOf(port));\n envVarsForApp.put(\"APP_NAME\", name);\n envVarsForApp.put(\"APP_ENV\", \"prod\");\n envVarsForApp.put(\"TEMP\", fullPath(tempDir));\n envVarsForApp.put(\"APP_DATA\", fullPath(dataDir));\n return envVarsForApp;\n }\n\n public void addListener(AppChangeListener appChangeListener) {\n listeners.add(appChangeListener);\n }\n\n public interface AppChangeListener {\n void onAppStarted(String name, URL newUrl);\n }\n\n private File copyToNewInstanceDir() throws IOException {\n File dest = new File(instanceDir, String.valueOf(System.currentTimeMillis()));\n dest.mkdir();\n FileUtils.copyDirectory(git.getRepository().getWorkTree(), dest, pathname -> !pathname.getName().equals(\".git\"));\n return dest;\n }\n\n public static String nameFromUrl(String gitUrl) {\n String name = StringUtils.removeEndIgnoreCase(StringUtils.removeEnd(gitUrl, \"/\"), \".git\");\n name = name.substring(Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\\\')) + 1);\n return name;\n }\n}", "public class AppNotFoundException extends AppRunnerException {\n public AppNotFoundException(String message) {\n super(message);\n }\n}", "public class AppRunnerFactoryProvider {\n public static final Logger log = LoggerFactory.getLogger(AppRunnerFactoryProvider.class);\n\n private final List<AppRunnerFactory> factories;\n\n public AppRunnerFactoryProvider(List<AppRunnerFactory> factories) {\n this.factories = factories;\n }\n\n public static AppRunnerFactoryProvider create(Config config) throws ExecutionException, InterruptedException {\n // This is done asyncronously because around half the startup time in tests was due to these calls.\n\n ExecutorService executorService = Executors.newFixedThreadPool(6 /* the number of factories */);\n List<Future<Optional<? extends AppRunnerFactory>>> futures = new ArrayList<>();\n futures.add(executorService.submit(() -> MavenRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> NodeRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> LeinRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> SbtRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> GoRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> GradleRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> PythonRunnerFactory.createIfAvailable(config, 2)));\n futures.add(executorService.submit(() -> PythonRunnerFactory.createIfAvailable(config, 3)));\n futures.add(executorService.submit(() -> RustRunnerFactory.createIfAvailable(config)));\n futures.add(executorService.submit(() -> DotnetRunnerFactory.createIfAvailable(config)));\n\n List<AppRunnerFactory> factories = new ArrayList<>();\n for (Future<Optional<? extends AppRunnerFactory>> future : futures) {\n future.get().ifPresent(factories::add);\n }\n executorService.shutdown();\n return new AppRunnerFactoryProvider(factories);\n }\n\n public AppRunnerFactory runnerFor(String appName, File projectRoot) throws UnsupportedProjectTypeException {\n for (AppRunnerFactory factory : factories) {\n if (factory.canRun(projectRoot)) {\n return factory;\n }\n }\n throw new UnsupportedProjectTypeException(\"No app runner found for \" + appName);\n }\n\n public String describeRunners() {\n return factories.stream()\n .map(AppRunnerFactory::versionInfo)\n .collect(joining(System.lineSeparator()));\n }\n\n public List<AppRunnerFactory> factories() {\n return factories;\n }\n}", "public class UnsupportedProjectTypeException extends AppRunnerException {\n public UnsupportedProjectTypeException(String message) {\n super(message);\n }\n}", "public class ProxyMap {\n public static final Logger log = LoggerFactory.getLogger(ProxyMap.class);\n private final ConcurrentHashMap<String, URL> mapping = new ConcurrentHashMap<>();\n\n public void add(String prefix, URL url) {\n URL old = mapping.put(prefix, url);\n if (old == null) {\n log.info(prefix + \" maps to \" + url);\n } else {\n log.info(prefix + \" maps to \" + url + \" (previously \" + old + \")\");\n }\n }\n\n public void remove(String prefix) {\n URL remove = mapping.remove(prefix);\n if (remove == null) {\n log.info(\"Removed \" + prefix + \" mapping to \" + remove);\n }\n }\n\n public URL get(String prefix) {\n return mapping.getOrDefault(prefix, null);\n }\n}" ]
import com.danielflower.apprunner.mgmt.AppDescription; import com.danielflower.apprunner.mgmt.AppManager; import com.danielflower.apprunner.problems.AppNotFoundException; import com.danielflower.apprunner.runners.AppRunnerFactoryProvider; import com.danielflower.apprunner.runners.UnsupportedProjectTypeException; import com.danielflower.apprunner.web.ProxyMap; import org.apache.maven.shared.invoker.InvocationOutputHandler; import org.eclipse.jgit.api.errors.GitAPIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream;
package com.danielflower.apprunner; public class AppEstate { public static final Logger log = LoggerFactory.getLogger(AppEstate.class); private final List<AppDescription> managers = new ArrayList<>(); private final ProxyMap proxyMap; private final FileSandbox fileSandbox; private final List<AppChangedListener> appAddedListeners = new ArrayList<>(); private final List<AppChangedListener> appUpdatedListeners = new ArrayList<>(); private final List<AppChangedListener> appDeletedListeners = new ArrayList<>();
private final AppRunnerFactoryProvider runnerProvider;
3
xda/XDA-One
android/src/main/java/com/xda/one/auth/RegisterFragment.java
[ "public interface UserClient {\n\n public EventBus getBus();\n\n public void login(final String username, final String password);\n\n void register(final String email, final String username, final String password,\n final String challenge, final String response, final Consumer<Response> success,\n final Consumer<Result> failure);\n\n public MentionContainer getMentions(final int page);\n\n public QuoteContainer getQuotes(final int page);\n\n public ResponseUserProfile getUserProfile();\n\n public void getUserProfileAsync();\n\n public ResponseUserProfile getUserProfile(final String userId);\n}", "public interface Consumer<T> {\n\n public void run(T data);\n}", "public class Result {\n\n private static final String ERROR = \"error\";\n\n private static final String MESSAGE = \"message\";\n\n private boolean mSuccess;\n\n private String mMessage;\n\n public Result(final boolean success) {\n mSuccess = success;\n }\n\n public Result(final String message) {\n mMessage = message;\n }\n\n public static Result parseResultFromResponse(final Response response) {\n InputStream inputStream = null;\n try {\n inputStream = response.getBody().in();\n final String output = IOUtils.toString(inputStream);\n return Result.parseResultFromString(output);\n } catch (IOException | NullPointerException e) {\n e.printStackTrace();\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n return null;\n }\n\n public static Result parseResultFromString(final String line) {\n if (line == null) {\n return null;\n }\n\n final Result result;\n try {\n final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);\n\n if (error == null) {\n result = new Result(true);\n } else {\n result = new Result(error.get(MESSAGE).asText());\n }\n return result;\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static boolean isSuccess(Result result) {\n return result != null && result.isSuccess();\n }\n\n public boolean isSuccess() {\n return mSuccess;\n }\n\n public String getMessage() {\n return mMessage;\n }\n}", "public class RetrofitUserClient implements UserClient {\n\n private static UserClient sUserClient;\n\n private final UserAPI mUserAPI;\n\n private final Context mContext;\n\n private final EventBus mBus;\n\n private RetrofitUserClient(final Context context) {\n mUserAPI = RetrofitClient.getRestBuilder(context, XDAConstants.ENDPOINT_URL)\n .build()\n .create(UserAPI.class);\n mContext = context.getApplicationContext();\n mBus = new EventBus();\n }\n\n public static UserClient getClient(final Context context) {\n if (sUserClient == null) {\n sUserClient = new RetrofitUserClient(context);\n }\n return sUserClient;\n }\n\n private static String getCookieFromHeaders(final List<Header> headers) {\n final StringBuilder sb = new StringBuilder();\n for (final Header c : headers) {\n if (\"Set-Cookie\".equals(c.getName())) {\n sb.append(c.getValue()).append(\"; \");\n }\n }\n return sb.toString();\n }\n\n @Override\n public EventBus getBus() {\n return mBus;\n }\n\n @Override\n public void login(final String username, final String password) {\n final Map<String, String> map = new HashMap<>();\n map.put(\"username\", username);\n map.put(\"password\", password);\n\n mUserAPI.login(map, new Callback<Response>() {\n @Override\n public void success(final Response response, final Response response2) {\n final String authToken = getCookieFromHeaders(response.getHeaders());\n setAuthToken(authToken);\n getUserInternalAsync(new Consumer<ResponseUserProfile>() {\n @Override\n public void run(final ResponseUserProfile profile) {\n final XDAAccount account = XDAAccount.fromProfile(profile);\n mBus.post(new UserLoginEvent(account));\n }\n }, new Consumer<RetrofitError>() {\n @Override\n public void run(final RetrofitError data) {\n failure(data);\n }\n });\n }\n\n @Override\n public void failure(final RetrofitError error) {\n final String output = Utils.handleRetrofitErrorQuietly(error);\n final Result result = Result.parseResultFromString(output);\n mBus.post(new UserLoginFailedEvent(result));\n }\n });\n }\n\n @Override\n public void register(final String email, final String username, final String password,\n final String challenge, final String response, final Consumer<Response> success,\n final Consumer<Result> failure) {\n final Map<String, String> map = new HashMap<>();\n map.put(\"username\", username);\n map.put(\"password\", password);\n map.put(\"email\", email);\n map.put(\"captcha_chal\", challenge);\n map.put(\"captcha_resp\", response);\n\n mUserAPI.register(map, new Callback<Response>() {\n @Override\n public void success(final Response response, final Response response2) {\n final String authToken = getCookieFromHeaders(response.getHeaders());\n setAuthToken(authToken);\n success.run(response);\n }\n\n @Override\n public void failure(final RetrofitError error) {\n final String result = Utils.handleRetrofitErrorQuietly(error);\n failure.run(Result.parseResultFromString(result));\n }\n });\n }\n\n private void getUserInternalAsync(final Consumer<ResponseUserProfile> success,\n final Consumer<RetrofitError> failure) {\n mUserAPI.getUser(getAuthToken(), new Callback<ResponseUserProfile>() {\n @Override\n public void success(final ResponseUserProfile profile,\n final Response response) {\n final CharSequence parsedSig = ContentParser.parseBBCode(mContext,\n String.format(mContext.getString(R.string.user_profile_signature),\n profile.getSignature()));\n profile.setParsedSignature(parsedSig);\n success.run(profile);\n }\n\n @Override\n public void failure(final RetrofitError error) {\n Utils.handleRetrofitErrorQuietly(error);\n failure.run(error);\n }\n });\n }\n\n @Override\n public MentionContainer getMentions(int page) {\n try {\n return mUserAPI.getMentions(getAuthToken(), page);\n } catch (RetrofitError error) {\n Utils.handleRetrofitErrorQuietly(error);\n }\n return null;\n }\n\n @Override\n public QuoteContainer getQuotes(int page) {\n try {\n return mUserAPI.getQuotes(getAuthToken(), page);\n } catch (RetrofitError error) {\n Utils.handleRetrofitErrorQuietly(error);\n }\n return null;\n }\n\n @Override\n public ResponseUserProfile getUserProfile() {\n try {\n ResponseUserProfile profile = mUserAPI.getUser(getAuthToken());\n\n final CharSequence parsedSig = ContentParser.parseBBCode(mContext,\n String.format(mContext.getString(R.string.user_profile_signature),\n profile.getSignature()));\n profile.setParsedSignature(parsedSig);\n\n return profile;\n } catch (RetrofitError error) {\n Utils.handleRetrofitErrorQuietly(error);\n }\n return null;\n }\n\n @Override\n public void getUserProfileAsync() {\n getUserInternalAsync(new Consumer<ResponseUserProfile>() {\n @Override\n public void run(final ResponseUserProfile profile) {\n mBus.post(new UserProfileEvent(XDAAccount.fromProfile(profile), profile));\n }\n }, new Consumer<RetrofitError>() {\n @Override\n public void run(final RetrofitError error) {\n Utils.handleRetrofitErrorQuietly(error);\n mBus.post(new UserProfileFailedEvent(parseResultFromResponse(error.getResponse())));\n }\n });\n }\n\n @Override\n public ResponseUserProfile getUserProfile(final String userId) {\n try {\n final ResponseUserProfile profile = mUserAPI.getUserProfile(getAuthToken(), userId);\n\n final CharSequence parsedSig = ContentParser.parseBBCode(mContext,\n String.format(mContext.getString(R.string.user_profile_signature),\n profile.getSignature()));\n profile.setParsedSignature(parsedSig);\n\n return profile;\n } catch (RetrofitError error) {\n Utils.handleRetrofitErrorQuietly(error);\n }\n return null;\n }\n\n private static interface UserAPI {\n\n @POST(\"/user/login\")\n public void login(@Body final Map<String, String> body,\n final Callback<Response> callback);\n\n @POST(\"/user/register\")\n public void register(@Body final Map<String, String> body,\n final Callback<Response> callback);\n\n @GET(\"/user\")\n public ResponseUserProfile getUser(@retrofit.http.Header(\"Cookie\") final String cookie);\n\n @GET(\"/user\")\n public void getUser(@retrofit.http.Header(\"Cookie\") final String cookie,\n final Callback<ResponseUserProfile> callback);\n\n @GET(\"/user/quotes\")\n public ResponseQuoteContainer getQuotes(@retrofit.http.Header(\"Cookie\") final String cookie,\n @Query(\"page\") final int page);\n\n @GET(\"/user/mentions\")\n public ResponseMentionContainer getMentions(@retrofit.http.Header(\"Cookie\") final String\n cookie, @Query(\"page\") final int page);\n\n @GET(\"/user/userinfo\")\n public ResponseUserProfile getUserProfile(@retrofit.http.Header(\"Cookie\") final String\n cookie, @Query(\"userid\") final String userId);\n }\n}", "public class UserProfileFailedEvent extends Event {\n\n public final Result result;\n\n public UserProfileFailedEvent(final Result result) {\n this.result = result;\n }\n}", "public class MultipleNonEmptyTextViewListener implements TextWatcher {\n\n private final EditText[] mEditTexts;\n\n private View mView;\n\n public MultipleNonEmptyTextViewListener(final View button, final EditText... editTexts) {\n if (editTexts == null) {\n throw new NullPointerException();\n }\n\n mView = button;\n mEditTexts = editTexts;\n }\n\n @Override\n public void afterTextChanged(final Editable s) {\n }\n\n @Override\n public void beforeTextChanged(final CharSequence s, final int start, final int count,\n final int after) {\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n for (final EditText editText : mEditTexts) {\n if (editText.length() == 0) {\n mView.setEnabled(false);\n return;\n }\n }\n mView.setEnabled(true);\n }\n\n public void registerAll() {\n for (final EditText editText : mEditTexts) {\n editText.addTextChangedListener(this);\n }\n }\n}" ]
import com.squareup.otto.Subscribe; import com.xda.one.R; import com.xda.one.api.inteface.UserClient; import com.xda.one.api.misc.Consumer; import com.xda.one.api.misc.Result; import com.xda.one.api.retrofit.RetrofitUserClient; import com.xda.one.constants.XDAConstants; import com.xda.one.event.user.UserProfileEvent; import com.xda.one.event.user.UserProfileFailedEvent; import com.xda.one.ui.listener.MultipleNonEmptyTextViewListener; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import retrofit.client.Response;
package com.xda.one.auth; public class RegisterFragment extends Fragment { private UserClient mUserClient; private EditText mUsername; private EditText mPassword; private EditText mEmail; private EditText mResponse; private ReCaptcha mReCaptcha; private ProgressDialog mProgressDialog; private Object mEventListener; private ImageView mRecaptchaView; public static Fragment createInstance() { return new RegisterFragment(); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState);
mUserClient = RetrofitUserClient.getClient(getActivity());
3
sdadas/fsbrowser
src/main/java/pl/sdadas/fsbrowser/view/locations/StatusBarHelper.java
[ "public final class BeanFactory {\n\n private static Map<Class<?>, Object> beans = new HashMap<>();\n\n private BeanFactory() {\n }\n\n public static FsConnection connection(AppConnection connection) {\n ConnectionConfig config = new ConnectionConfig(connection.getUser(), connection.getPropertiesMap());\n return new FsConnection(config);\n }\n\n public static FileSystemTableModel tableModel(FsConnection connection) {\n try {\n return new FileSystemTableModel(connection, \"/\");\n } catch (FsException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static ClipboardHelper clipboardHelper() {\n return singleton(ClipboardHelper.class, ClipboardHelper::new);\n }\n\n public static MainPanel mainPanel() {\n return singleton(MainPanel.class, () -> {\n return new MainPanel(configProvider(), clipboardHelper(), executorService(), statusBarHelper());\n });\n }\n\n public static MainWindow mainWindow() {\n return singleton(MainWindow.class, () -> new MainWindow(mainPanel()));\n }\n\n public static AppConfigProvider configProvider() {\n return singleton(AppConfigProvider.class, AppConfigProvider::new);\n }\n\n public static ListeningExecutorService executorService() {\n return singleton(ListeningExecutorService.class, () -> {\n ExecutorService executor = Executors.newFixedThreadPool(3);\n return MoreExecutors.listeningDecorator(executor);\n });\n }\n\n public static StatusBarHelper statusBarHelper() {\n return singleton(StatusBarHelper.class, () -> {\n return new StatusBarHelper(configProvider());\n });\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <T> T singleton(Class<T> clazz, Supplier<T> supplier) {\n return (T) beans.computeIfAbsent(clazz, key -> supplier.get());\n }\n}", "public class AppConfigProvider {\n\n private AppConfig config;\n\n public AppConfigProvider() {\n this.config = readConfig();\n }\n\n private AppConfig readConfig() {\n File file = getConfigLocation();\n if(!file.exists()) return new AppConfig();\n try {\n return JaxbUtils.unmarshall(file, AppConfig.class);\n } catch(IllegalStateException ex) {\n return new AppConfig();\n }\n }\n\n public void writeConfig() {\n File file = getConfigLocation();\n JaxbUtils.marshall(config, file);\n }\n\n private File getConfigLocation() {\n try {\n File dir = getJarLocation();\n return new File(dir, \"config.xml\");\n } catch (URISyntaxException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private File getJarLocation() throws URISyntaxException {\n CodeSource codeSource = Application.class.getProtectionDomain().getCodeSource();\n File jarFile = new File(codeSource.getLocation().toURI().getPath());\n return jarFile.getParentFile();\n }\n\n public AppConfig getConfig() {\n return config;\n }\n}", "@XmlRootElement(name = \"connection\")\npublic class AppConnection implements Serializable {\n\n private String user;\n\n private String name;\n\n private List<ConfigProperty> properties = new ArrayList<>();\n\n public AppConnection() {\n }\n\n public AppConnection(String user, String name) {\n this.user = user;\n this.name = name;\n }\n\n public String getUser() {\n return user;\n }\n\n @XmlElement(name = \"user\")\n public void setUser(String user) {\n this.user = user;\n }\n\n public String getName() {\n return name;\n }\n\n @XmlElement(name = \"name\")\n public void setName(String name) {\n this.name = name;\n }\n\n public List<ConfigProperty> getProperties() {\n return properties;\n }\n\n @XmlElementWrapper(name = \"configuration\")\n @XmlElement(name = \"property\")\n public void setProperties(List<ConfigProperty> properties) {\n this.properties = properties;\n }\n\n @XmlTransient\n public Map<String, String> getPropertiesMap() {\n Map<String, String> result = new LinkedHashMap<>();\n if(this.properties == null) return result;\n for (ConfigProperty property : properties) {\n result.put(property.getName(), property.getValue());\n }\n return result;\n }\n\n @Override\n public String toString() {\n return name;\n }\n}", "@XmlRootElement(name = \"location\")\npublic class AppLocation implements Serializable {\n\n private String connectionId;\n\n private String path;\n\n public AppLocation() {\n }\n\n public AppLocation(String connectionId, String path) {\n this.connectionId = connectionId;\n this.path = path;\n }\n\n public String getConnectionId() {\n return connectionId;\n }\n\n @XmlAttribute(name = \"connectionId\")\n public void setConnectionId(String connectionId) {\n this.connectionId = connectionId;\n }\n\n public String getPath() {\n return path;\n }\n\n @XmlValue\n public void setPath(String path) {\n this.path = path;\n }\n\n @XmlTransient\n public String getLocationString() {\n return StringUtils.abbreviateMiddle(path, \"...\", 50) + \" @ \" + connectionId;\n }\n\n @Override\n public boolean equals(Object other) {\n if (this == other) return true;\n if (other == null || getClass() != other.getClass()) return false;\n AppLocation that = (AppLocation) other;\n return new EqualsBuilder()\n .append(connectionId, that.connectionId)\n .append(path, that.path)\n .isEquals();\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder(17, 37)\n .append(connectionId)\n .append(path)\n .toHashCode();\n }\n}", "public class HarFsConnection extends FsConnection {\n\n private final FileSystem parentFileSystem;\n\n public HarFsConnection(FsConnection other, Path harFile) {\n super(other.getConnectionConfig());\n this.setReadOnly(true);\n this.setRoot(getHarPath(harFile));\n this.parentFileSystem = new CloseSuppressingFileSystem(other.getFileSystem());\n }\n\n @Override\n protected FileSystem createNewFileSystem(Configuration configuration) throws IOException {\n HarFileSystem fs = new HarFileSystem(this.parentFileSystem);\n fs.initialize(this.getRoot().toUri(), configuration);\n return fs;\n }\n\n @Override\n protected FileSystem createSharedFileSystem(Configuration configuration) throws IOException {\n return this.getFileSystem() != null ? this.getFileSystem() : createNewFileSystem(configuration);\n }\n\n private URI getHarUri(Path file) {\n URI uri = file.toUri();\n try {\n return new URI(\"har\", uri.getScheme() + \"-\" + uri.getAuthority(), uri.getPath(), uri.getFragment());\n } catch (URISyntaxException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private Path getHarPath(Path file) {\n return new Path(getHarUri(file));\n }\n\n @Override\n protected Path fsPath(Path path) {\n String relative = StringUtils.stripToNull(StringUtils.removeStart(path.toUri().getPath(), \"/\"));\n return relative != null ? path : this.getRoot();\n }\n}", "public final class IconFactory {\n\n private final static Map<String, Icon> ICONS = new HashMap<String, Icon>();\n\n public static Icon getIcon(String name) {\n Icon icon = ICONS.get(name);\n if(icon == null) {\n Image image = getImageResource(String.format(\"icons/%s.png\", name));\n icon = new ImageIcon(image);\n ICONS.put(name, icon);\n }\n return icon;\n }\n\n public static Image getImageResource(String classpath) {\n InputStream is = IconFactory.class.getClassLoader().getResourceAsStream(classpath);\n try {\n byte[] bytes = IOUtils.toByteArray(is);\n Toolkit toolkit = Toolkit.getDefaultToolkit();\n return toolkit.createImage(bytes);\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private IconFactory() {\n }\n}", "public final class ViewUtils {\n\n public static void setupDialogWindow(JDialog dialog) {\n dialog.pack();\n dialog.setMinimumSize(dialog.getSize());\n dialog.setLocationRelativeTo(dialog.getOwner());\n }\n\n public static WebPanel rightLeftPanel(JComponent... comps) {\n return horizontalPanel(ComponentOrientation.RIGHT_TO_LEFT, null, comps);\n }\n\n public static WebPanel leftRightPanel(JComponent... comps) {\n return horizontalPanel(ComponentOrientation.LEFT_TO_RIGHT, null, comps);\n }\n\n public static WebPanel rightLeftPanel(Integer minWidth, JComponent... comps) {\n return horizontalPanel(ComponentOrientation.RIGHT_TO_LEFT, minWidth, comps);\n }\n\n public static WebPanel leftRightPanel(Integer minWidth, JComponent... comps) {\n return horizontalPanel(ComponentOrientation.LEFT_TO_RIGHT, minWidth, comps);\n }\n\n public static WebPanel horizontalPanel(ComponentOrientation orientation, Integer minWidth, JComponent... comps) {\n HorizontalFlowLayout layout = new HorizontalFlowLayout();\n WebPanel panel = new WebPanel(layout);\n panel.setComponentOrientation(orientation);\n for (JComponent button : comps) {\n if(minWidth != null) SizeUtils.setMinimumWidth(button, minWidth);\n panel.add(button);\n }\n return panel;\n }\n\n public static MessagePopup error(Component comp, String message) {\n return message(comp, MessageLevel.Error, \"Error\", message);\n }\n\n public static MessagePopup warning(Component comp, String message) {\n return message(comp, MessageLevel.Warning, \"Warning\", message);\n }\n\n public static MessagePopup info(Component comp, String message) {\n return message(comp, MessageLevel.Info, \"Information\", message);\n }\n\n public static MessagePopup message(Component comp, MessageLevel level, String title, String message) {\n Window window = SwingUtils.getWindowAncestor(comp);\n MessagePopup result = new MessagePopup(window);\n result.setLevel(level);\n result.setTitle(title);\n result.setText(message);\n result.pack();\n int x = window.getX() + (window.getWidth() / 2) - (result.getWidth() / 2);\n int y = window.getY() + (window.getHeight() / 2) - (result.getHeight() / 2);\n result.show(x, y);\n return result;\n }\n\n public static void handleErrors(Component comp, UnsafeRunnable runnable) {\n try {\n runnable.run();\n } catch(FsAccessException ex) {\n SwingUtils.invokeLater(() -> error(comp, \"Access denied\"));\n } catch(FsException ex) {\n ex.printStackTrace();\n SwingUtils.invokeLater(() -> error(comp, ex.getMessage()));\n }\n }\n\n public static void ignoreErrors(UnsafeRunnable runnable) {\n try {\n runnable.run();\n } catch (FsException ex) {\n ex.printStackTrace();\n }\n }\n\n public static boolean requireNativeLibraries(JComponent comp) {\n if(!FileSystemUtils.checkNativeLibraries()) {\n String message = \"This action requires hadoop native libraries.\\n\" +\n \"Please install them, set HADOOP_HOME environment variable and restart application.\\n\";\n warning(comp, message);\n return false;\n }\n return true;\n }\n\n private ViewUtils() {\n }\n}", "public class FileSystemPanel extends LoadingOverlay implements Closeable {\n\n private final FsConnection connection;\n\n private final FileSystemTableModel model;\n\n private WebBreadcrumb breadcrumb;\n\n private WebToolBar toolbar;\n\n private FileBrowser browser;\n\n private FileSystemActions actions;\n\n private ClipboardHelper clipboard;\n\n private WebPopupMenu filePopup;\n\n private WebPopupMenu noFilePopup;\n\n private boolean closed = false;\n\n private WebTextField filter;\n\n public FileSystemPanel(FsConnection connection, ClipboardHelper clipboard, ListeningExecutorService executor) {\n super(executor);\n this.connection = connection;\n this.model = BeanFactory.tableModel(connection);\n this.actions = new FileSystemActions(this);\n this.clipboard = clipboard;\n this.filePopup = createFilePopup();\n this.noFilePopup = createNoFilePopup();\n initView();\n initListeners();\n }\n\n private void initListeners() {\n onPathChanged(this.model.getCurrentPath());\n this.model.addPathListener(this::onPathChanged);\n this.browser.addMouseListener(this.contextMenuListener());\n this.browser.setTransferHandler(new FileSystemTransferHandler(this));\n this.browser.setBeforeSort(() -> asyncAction(model::loadAllRows));\n }\n\n private void initView() {\n this.filter = createFilter();\n this.breadcrumb = createBreadcrumb();\n this.browser = createFileBrowser();\n this.toolbar = createToolBar();\n WebScrollPane browserScroll = new WebScrollPane(browser);\n browserScroll.setDrawFocus(false);\n browserScroll.getVerticalScrollBar().addAdjustmentListener(this::onScrollBottom);\n browserScroll.getVerticalScrollBar().setUnitIncrement(50);\n\n JPanel head = new JPanel(new VerticalFlowLayout());\n head.add(toolbar);\n head.add(breadcrumb);\n\n WebPanel panel = new WebPanel(new BorderLayout());\n panel.add(head, BorderLayout.PAGE_START);\n panel.add(browserScroll, BorderLayout.CENTER);\n setComponent(panel);\n }\n\n private MouseAdapter contextMenuListener() {\n return new MouseAdapter() {\n @Override\n public void mouseReleased(MouseEvent event) {\n if(!SwingUtils.isPopupTrigger(event)) return;\n Point point = event.getPoint();\n int viewRowIdx = browser.rowAtPoint(point);\n int rowIdx = viewRowIdx >= 0 ? browser.convertRowIndexToModel(viewRowIdx) : -1;\n int colIdx = browser.columnAtPoint(point);\n if(!browser.isRowSelected(rowIdx)) {\n browser.changeSelection(rowIdx, colIdx, false, false);\n }\n\n if(rowIdx >=0) {\n FileItem item = model.getRow(rowIdx);\n if(item.isFile() || item.isDirectory()) {\n filePopup.show(event.getComponent(), event.getX(), event.getY());\n }\n } else {\n noFilePopup.show(event.getComponent(), event.getX(), event.getY());\n }\n }\n };\n }\n\n private void onSortChanged(RowSorterEvent event) {\n SwingUtils.invokeLater(() -> asyncAction(model::loadAllRows));\n }\n\n private void onPathChanged(Path value) {\n Path current = value;\n this.breadcrumb.removeAll();\n do {\n WebBreadcrumbButton button = createBreadcrumbButton(current);\n this.breadcrumb.add(button, 0);\n current = current.getParent();\n } while (current != null);\n this.breadcrumb.repaint();\n }\n\n private WebTextField createFilter() {\n WebTextField result = new WebTextField();\n result.setMinimumWidth(200);\n result.setTrailingComponent(new WebImage(IconFactory.getIcon(\"search\")));\n result.setInputPrompt(\"Press ENTER to filter files\");\n result.setHideInputPromptOnFocus(false);\n result.addKeyListener(new KeyAdapter() {\n @Override\n public void keyPressed(KeyEvent event) {\n if (event.getKeyCode() == KeyEvent.VK_ENTER) {\n String text = result.getText();\n if(StringUtils.isNotBlank(text) && model.hasMoreRows()) {\n asyncAction(model::loadAllRows);\n }\n browser.filter(text);\n }\n }\n });\n return result;\n }\n\n private WebBreadcrumbButton createBreadcrumbButton(Path path) {\n String name = path.getName();\n if(StringUtils.isBlank(name)) {\n name = \"/\";\n }\n WebBreadcrumbButton button = new WebBreadcrumbButton(name);\n button.setIcon(IconFactory.getIcon(\"folder-small\"));\n button.addActionListener(event -> {\n ViewUtils.handleErrors(this, () -> {\n this.clearFilterAndSort();\n this.model.onFileClicked(path);\n });\n });\n return button;\n }\n\n private void onScrollBottom(AdjustmentEvent event) {\n if(!event.getValueIsAdjusting()) {\n Adjustable adjustable = event.getAdjustable();\n int position = event.getValue() + adjustable.getVisibleAmount();\n int bottom = adjustable.getMaximum() - 5;\n if(position >= bottom) {\n this.model.loadMoreRows();\n }\n }\n }\n\n private WebBreadcrumb createBreadcrumb() {\n return new WebBreadcrumb(false);\n }\n\n private FileBrowser createFileBrowser() {\n FileBrowser browser = new FileBrowser(model);\n browser.addMouseListener(this.onClick());\n browser.addKeyListener(this.onEnter());\n return browser;\n }\n\n private KeyAdapter onEnter() {\n return new KeyAdapter() {\n @Override\n public void keyPressed(KeyEvent event) {\n if (event.getKeyCode() == KeyEvent.VK_ENTER) {\n int idx = browser.getSelectedRow();\n if (idx >= 0) {\n onFileAccessed(idx);\n }\n }\n }\n };\n }\n\n private MouseAdapter onClick() {\n return new MouseAdapter() {\n @Override\n public void mouseClicked(MouseEvent event) {\n if (event.getClickCount() != 2) return;\n Point point = event.getPoint();\n int idx = browser.rowAtPoint(point);\n onFileAccessed(idx);\n }\n };\n }\n\n private void onFileAccessed(int idx) {\n if (idx < 0) return;\n\n ViewUtils.handleErrors(this, () -> {\n int modelIdx = this.browser.convertRowIndexToModel(idx);\n FileItem item = model.getRow(modelIdx);\n if(item == null) return;\n\n if(item.isFile()) {\n asyncAction(() -> this.actions.doPreviewFile(Collections.singletonList(item)));\n } else {\n this.clearFilterAndSort();\n model.onFileClicked(modelIdx);\n }\n });\n }\n\n private WebToolBar createToolBar() {\n WebToolBar result = new WebToolBar();\n result.setToolbarStyle(ToolbarStyle.attached);\n result.setFloatable(false);\n result.add(createToolButton(this.actions.copyFromLocalAction()));\n result.add(createToolButton(this.actions.copyToLocalAction()));\n result.add(createToolButton(this.actions.cutAction()));\n result.add(createToolButton(this.actions.copyAction()));\n result.add(createToolButton(this.actions.pasteAction()));\n result.add(createToolButton(this.actions.archiveAction()));\n result.add(createToolButton(this.actions.mkdirAction()));\n result.add(createToolButton(this.actions.touchAction()));\n result.add(createToolButton(this.actions.moveToTrashAction()));\n result.add(createToolButton(this.actions.removeAction()));\n result.add(createToolButton(this.actions.chmodAction()));\n result.add(createToolButton(this.actions.chownAction()));\n result.addSeparator();\n result.add(createToolButton(this.actions.previewFileAction()));\n result.add(createToolButton(this.actions.fsckAction()));\n result.addSeparator();\n result.add(createToolButton(this.actions.refreshAction()));\n result.add(createToolButton(this.actions.gotoAction()));\n result.add(createToolButton(this.actions.emptyTrashAction()));\n result.add(createToolButton(this.actions.cleanupAction()));\n result.addToEnd(this.filter);\n return result;\n }\n\n private WebButton createToolButton(FileAction action) {\n WebButton result = new WebButton(action.getIcon());\n result.setRolloverDecoratedOnly(true);\n result.setDrawFocus(false);\n if(StringUtils.isNotBlank(action.getName())) result.setToolTipText(action.getName());\n createActionInvoker(result, action);\n return result;\n }\n\n private WebPopupMenu createFilePopup() {\n WebPopupMenu result = new WebPopupMenu();\n result.add(createMenuItem(this.actions.copyToLocalAction()));\n result.add(createMenuItem(this.actions.cutAction()));\n result.add(createMenuItem(this.actions.copyAction()));\n result.add(createMenuItem(this.actions.pasteAction()));\n result.add(createMenuItem(this.actions.archiveAction()));\n result.add(createMenuItem(this.actions.renameAction()));\n result.add(createMenuItem(this.actions.moveToTrashAction()));\n result.add(createMenuItem(this.actions.removeAction()));\n result.add(createMenuItem(this.actions.chmodAction()));\n result.add(createMenuItem(this.actions.chownAction()));\n result.add(createMenuItem(this.actions.previewFileAction()));\n result.add(createMenuItem(this.actions.fsckAction()));\n result.add(createMenuItem(this.actions.openArchiveAction()));\n return result;\n }\n\n private WebPopupMenu createNoFilePopup() {\n WebPopupMenu result = new WebPopupMenu();\n result.add(createMenuItem(this.actions.pasteAction()));\n result.add(createMenuItem(this.actions.refreshAction()));\n result.add(createMenuItem(this.actions.gotoAction()));\n result.add(createMenuItem(this.actions.emptyTrashAction()));\n result.add(createMenuItem(this.actions.cleanupAction()));\n return result;\n }\n\n private WebMenuItem createMenuItem(FileAction action) {\n WebMenuItem result = new WebMenuItem(action.getName(), action.getIcon());\n createActionInvoker(result, action);\n return result;\n }\n\n private void createActionInvoker(AbstractButton button, FileAction action) {\n if(this.connection.isReadOnly() && !action.isReadOnly()) {\n button.setEnabled(false);\n } else {\n button.addActionListener((event) -> invokeAsync(action));\n }\n }\n\n private void invokeAsync(FileAction action) {\n if(action.supportsProgress()) {\n Progress progress = new Progress();\n asyncAction(() -> action.run(browser.selectedItems(), progress), progress);\n } else {\n asyncAction(() -> action.run(browser.selectedItems()));\n }\n }\n\n public FsConnection getConnection() {\n return connection;\n }\n\n public FileSystemTableModel getModel() {\n return model;\n }\n\n public WebBreadcrumb getBreadcrumb() {\n return breadcrumb;\n }\n\n public WebToolBar getToolbar() {\n return toolbar;\n }\n\n public FileBrowser getBrowser() {\n return browser;\n }\n\n public ClipboardHelper getClipboard() {\n return clipboard;\n }\n\n @Override\n public void close() throws IOException {\n this.closed = true;\n IOUtils.closeQuietly(this.connection);\n }\n\n public boolean isClosed() {\n return closed;\n }\n\n public FileSystemActions getActions() {\n return actions;\n }\n\n public void clearFilterAndSort() {\n this.filter.setText(\"\");\n this.browser.filter(\"\");\n this.browser.clearSort();\n }\n\n public void setCurrentPath(String path) {\n ViewUtils.handleErrors(this, () -> {\n this.clearFilterAndSort();\n this.getModel().onFileClicked(new Path(path));\n });\n }\n}", "public class MainPanel extends WebPanel {\n\n private final WebDocumentPane<DocumentData> pane;\n\n private final WebStatusBar statusBar;\n\n private final AppConfigProvider configProvider;\n\n private final ClipboardHelper clipboard;\n\n private final ListeningExecutorService executor;\n\n private final StatusBarHelper statusBarHelper;\n\n private ConnectionsDialog connectionsDialog;\n\n public MainPanel(AppConfigProvider configProvider, ClipboardHelper clipboard,\n ListeningExecutorService executor, StatusBarHelper statusBarHelper) {\n super(new BorderLayout());\n this.executor = executor;\n this.configProvider = configProvider;\n this.statusBarHelper = statusBarHelper;\n this.pane = createDocumentPane();\n this.statusBar = createStatusBar();\n this.clipboard = clipboard;\n initView();\n }\n\n private void initView() {\n add(this.pane, BorderLayout.CENTER);\n add(this.statusBar, BorderLayout.PAGE_END);\n }\n\n private WebDocumentPane<DocumentData> createDocumentPane() {\n WebDocumentPane<DocumentData> result = new WebDocumentPane<>();\n result.setTabMenuEnabled(true);\n result.addDocumentListener(new DocumentAdapter<DocumentData>() {\n @Override\n public void closed(DocumentData document, PaneData<DocumentData> pane, int index) {\n FileSystemPanel comp = (FileSystemPanel) document.getComponent();\n IOUtils.closeQuietly(comp);\n }\n });\n return result;\n }\n\n private WebStatusBar createStatusBar() {\n WebStatusBar result = new WebStatusBar();\n result.add(this.createButton(\"Connect\", \"connection\", this::showConnections));\n result.add(this.createButton(\"Locations\", \"locations\", this::showLocations));\n result.add(this.createButton(\"About\", \"about\", (event) -> showAboutDialog()));\n\n WebMemoryBar memoryBar = new WebMemoryBar ();\n memoryBar.setPreferredWidth(memoryBar.getPreferredSize().width + 20);\n memoryBar.setFontSize(11);\n result.add(memoryBar, ToolbarLayout.END);\n return result;\n }\n\n private WebButton createButton(String text, String icon, ActionListener listener) {\n WebButton button = new WebButton(text, IconFactory.getIcon(icon));\n button.setFontSize(11);\n button.addActionListener(listener);\n button.setMinimumWidth(80);\n return button;\n }\n\n public void showConnectionsDialog() {\n if(this.connectionsDialog == null) {\n Window window = SwingUtils.getWindowAncestor(this);\n this.connectionsDialog = new ConnectionsDialog(this.configProvider, window);\n this.connectionsDialog.addConnectListener(this::onConnect);\n }\n this.connectionsDialog.setVisible(true);\n }\n\n private void showAboutDialog() {\n try {\n doShowAboutDialog();\n } catch (IOException e) {\n ViewUtils.error(this, e.getMessage());\n }\n }\n\n private void showPopup(ActionEvent event, Supplier<WebPopupMenu> supplier) {\n WebButton button = (WebButton) event.getSource();\n WebPopupMenu popup = supplier.get();\n popup.setPopupMenuWay(PopupMenuWay.aboveStart);\n popup.show(button, button.getX() - button.getWidth(), button.getY());\n }\n\n void showLocations(ActionEvent event) {\n showPopup(event, () -> this.statusBarHelper.createLocationsPopup(this));\n }\n\n void showConnections(ActionEvent event) {\n showPopup(event, () -> this.statusBarHelper.createConnectionsPopup(this));\n }\n\n private void doShowAboutDialog() throws IOException {\n Resource resource = new ClassPathResource(\"about.html\");\n String text = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);\n Map<String, String> params = new HashMap<>();\n params.put(\"fullVersionString\", Version.getFullVersionString());\n ViewUtils.message(this, MessageLevel.Info, \"\", StrSubstitutor.replace(text, params));\n }\n\n private void onConnect(AppConnection connection) {\n openFileSystemTab(connection);\n }\n\n public void openFileSystemTab(AppConnection connection) {\n openFileSystemTab(BeanFactory.connection(connection), connection.getName());\n }\n\n public void openFileSystemTab(FsConnection connection, String name) {\n openFileSystemTab(connection, name, null);\n }\n\n public void openFileSystemTab(FsConnection connection, String name, String workingDirectory) {\n try {\n FileSystemPanel fspanel = new FileSystemPanel(connection, this.clipboard, this.executor);\n if(StringUtils.isNotBlank(workingDirectory)) {\n fspanel.setCurrentPath(workingDirectory);\n }\n String id = RandomStringUtils.randomAlphabetic(32);\n DocumentData document = new DocumentData(id, IconFactory.getIcon(\"disk\"), name, fspanel);\n this.pane.openDocument(document);\n } catch (RuntimeException ex) {\n ViewUtils.error(this, \"Error opening HDFS connection:\\n\" + ex.getMessage());\n }\n }\n\n public DocumentData getActiveDocument() {\n return this.pane.getSelectedDocument();\n }\n\n public List<DocumentData> getAllDocuments() {\n return this.pane.getDocuments();\n }\n\n public void setActiveDocument(DocumentData data) {\n this.pane.setSelected(data);\n }\n\n public boolean hasConnections() {\n return !this.configProvider.getConfig().getConnections().isEmpty();\n }\n\n public WebButton getStatusBarButton(String text) {\n Component[] components = statusBar.getComponents();\n for (Component component : components) {\n if(component instanceof WebButton) {\n if(StringUtils.equalsIgnoreCase(((WebButton) component).getText(), text)) {\n return (WebButton) component;\n }\n }\n }\n return null;\n }\n}" ]
import com.alee.extended.tab.DocumentData; import com.alee.laf.menu.WebMenuItem; import com.alee.laf.menu.WebPopupMenu; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.fs.Path; import pl.sdadas.fsbrowser.app.BeanFactory; import pl.sdadas.fsbrowser.app.config.AppConfigProvider; import pl.sdadas.fsbrowser.app.config.AppConnection; import pl.sdadas.fsbrowser.app.config.AppLocation; import pl.sdadas.fsbrowser.fs.connection.HarFsConnection; import pl.sdadas.fsbrowser.utils.IconFactory; import pl.sdadas.fsbrowser.utils.ViewUtils; import pl.sdadas.fsbrowser.view.filesystempanel.FileSystemPanel; import pl.sdadas.fsbrowser.view.mainwindow.MainPanel; import java.util.List;
package pl.sdadas.fsbrowser.view.locations; /** * @author Sławomir Dadas */ public class StatusBarHelper { private final AppConfigProvider provider; public StatusBarHelper(AppConfigProvider provider) { this.provider = provider; }
public void addLocation(AppLocation location) {
3
koendeschacht/count-db
src/main/java/be/bagofwords/db/filedb/FileDataInterfaceFactory.java
[ "public interface DataInterface<T extends Object> extends DataIterable<KeyValue<T>> {\n\n T read(long key);\n\n default long readCount(long key) {\n Long result = (Long) read(key);\n if (result == null)\n return 0;\n else\n return result;\n }\n\n default T read(String key) {\n return read(HashUtils.hashCode(key));\n }\n\n default T read(BowString key) {\n return read(HashUtils.hashCode(key));\n }\n\n default long readCount(BowString key) {\n return readCount(HashUtils.hashCode(key));\n }\n\n default long readCount(String key) {\n return readCount(HashUtils.hashCode(key));\n }\n\n default boolean mightContain(String key) {\n return mightContain(HashUtils.hashCode(key));\n }\n\n default boolean mightContain(long key) {\n return read(key) != null;\n }\n\n default CloseableIterator<Long> keyIterator() {\n return IterableUtils.mapIterator(iterator(), KeyValue::getKey);\n }\n\n default CloseableIterator<T> valueIterator() {\n return IterableUtils.mapIterator(iterator(), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(KeyFilter keyFilter) {\n return IterableUtils.mapIterator(iterator(keyFilter), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(Predicate<T> valueFilter) {\n return IterableUtils.mapIterator(iterator(valueFilter), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(CloseableIterator<Long> keyIterator) {\n return IterableUtils.mapIterator(iterator(keyIterator), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(Stream<Long> keyStream) {\n return valueIterator(StreamUtils.iterator(keyStream));\n }\n\n default CloseableIterator<KeyValue<T>> iterator(KeyFilter keyFilter) {\n final CloseableIterator<KeyValue<T>> keyValueIterator = iterator();\n return IterableUtils.iterator(new SimpleIterator<KeyValue<T>>() {\n @Override\n public KeyValue<T> next() throws Exception {\n while (keyValueIterator.hasNext()) {\n KeyValue<T> next = keyValueIterator.next();\n if (keyFilter.acceptKey(next.getKey())) {\n return next;\n }\n }\n return null;\n }\n\n @Override\n public void close() throws Exception {\n keyValueIterator.close();\n }\n });\n }\n\n default CloseableIterator<KeyValue<T>> iterator(Predicate<T> valueFilter) {\n final CloseableIterator<KeyValue<T>> keyValueIterator = iterator();\n return IterableUtils.iterator(new SimpleIterator<KeyValue<T>>() {\n @Override\n public KeyValue<T> next() throws Exception {\n while (keyValueIterator.hasNext()) {\n KeyValue<T> next = keyValueIterator.next();\n if (valueFilter.test(next.getValue())) {\n return next;\n }\n }\n return null;\n }\n\n @Override\n public void close() throws Exception {\n keyValueIterator.close();\n }\n });\n }\n\n default CloseableIterator<KeyValue<T>> iterator(Stream<Long> keyStream) {\n return iterator(StreamUtils.iterator(keyStream));\n }\n\n default CloseableIterator<KeyValue<T>> iterator(CloseableIterator<Long> keyIterator) {\n return new CloseableIterator<KeyValue<T>>() {\n\n KeyValue<T> next;\n\n {\n //Constructor\n findNext();\n }\n\n private void findNext() {\n next = null;\n while (next == null && keyIterator.hasNext()) {\n Long nextKey = keyIterator.next();\n T nextValue = read(nextKey);\n if (nextValue != null) {\n next = new KeyValue<>(nextKey, nextValue);\n }\n }\n }\n\n @Override\n protected void closeInt() {\n keyIterator.close();\n }\n\n @Override\n public boolean hasNext() {\n return next != null;\n }\n\n @Override\n public KeyValue<T> next() {\n KeyValue<T> curr = next;\n findNext();\n return curr;\n }\n };\n }\n\n default CloseableIterator<KeyValue<T>> cachedValueIterator() {\n return new CloseableIterator<KeyValue<T>>() {\n @Override\n protected void closeInt() {\n //ok\n }\n\n @Override\n public boolean hasNext() {\n return false;\n }\n\n @Override\n public KeyValue<T> next() {\n return null;\n }\n };\n }\n\n CloseableIterator<KeyValue<T>> iterator();\n\n long apprSize();\n\n long apprDataChecksum();\n\n long exactSize();\n\n default Stream<KeyValue<T>> stream() {\n return StreamUtils.stream(this, true);\n }\n\n default Stream<KeyValue<T>> stream(KeyFilter keyFilter) {\n return StreamUtils.stream(iterator(keyFilter), apprSize(), true);\n }\n\n default Stream<KeyValue<T>> stream(Predicate<T> valueFilter) {\n return StreamUtils.stream(iterator(valueFilter), apprSize(), true);\n }\n\n default Stream<KeyValue<T>> stream(CloseableIterator<Long> keyIterator) {\n return StreamUtils.stream(iterator(keyIterator), apprSize(), true);\n }\n\n default Stream<T> streamValues() {\n return StreamUtils.stream(valueIterator(), apprSize(), false);\n }\n\n default Stream<T> streamValues(KeyFilter keyFilter) {\n return StreamUtils.stream(valueIterator(keyFilter), apprSize(), false);\n }\n\n default Stream<T> streamValues(Predicate<T> valueFilter) {\n return StreamUtils.stream(valueIterator(valueFilter), apprSize(), false);\n }\n\n default Stream<T> streamValues(CloseableIterator<Long> keyIterator) {\n return StreamUtils.stream(valueIterator(keyIterator), apprSize(), false);\n }\n\n default Stream<T> streamValues(Stream<Long> keysStream) {\n //This could be improved... Mapping twice from streams to closeable iterators does have a certain overhead\n return StreamUtils.stream(valueIterator(StreamUtils.iterator(keysStream)), apprSize(), false);\n }\n\n default Stream<Long> streamKeys() {\n return StreamUtils.stream(keyIterator(), apprSize(), true);\n }\n\n Class<T> getObjectClass();\n\n String getName();\n\n void optimizeForReading();\n\n void write(long key, T value);\n\n default void write(Iterator<KeyValue<T>> entries) {\n write(IterableUtils.iterator(entries));\n }\n\n default void write(CloseableIterator<KeyValue<T>> entries) {\n while (entries.hasNext()) {\n KeyValue<T> entry = entries.next();\n write(entry.getKey(), entry.getValue());\n }\n entries.close();\n }\n\n default void write(BowString key, T value) {\n write(HashUtils.hashCode(key.getS()), value);\n }\n\n default void write(String key, T value) {\n write(HashUtils.hashCode(key), value);\n }\n\n default void increaseCount(String key, Long value) {\n write(key, (T) value);\n }\n\n default void increaseCount(long key, Long value) {\n write(key, (T) value);\n }\n\n default void increaseCount(String key) {\n increaseCount(key, 1l);\n }\n\n default void increaseCount(long key) {\n increaseCount(key, 1l);\n }\n\n default void remove(String key) {\n remove(HashUtils.hashCode(key));\n }\n\n default void remove(long key) {\n write(key, null);\n }\n\n Combinator<T> getCombinator();\n\n void close();\n\n boolean wasClosed();\n\n boolean isTemporaryDataInterface();\n\n void flush();\n\n void dropAllData();\n\n void ifNotClosed(Runnable action);\n\n DataInterface<T> getCoreDataInterface();\n\n ObjectSerializer<T> getObjectSerializer();\n\n void registerUpdateListener(UpdateListener<T> updateListener);\n}", "public interface Combinator<T extends Object> extends Serializable {\n\n T combine(T first, T second);\n\n default void addRemoteClasses(RemoteObjectConfig objectConfig) {\n //Don't add any classes by default\n }\n\n default RemoteObjectConfig createExecConfig() {\n RemoteObjectConfig result = RemoteObjectConfig.create(this);\n result.add(getClass());\n addRemoteClasses(result);\n return result;\n }\n}", "public abstract class BaseDataInterface<T extends Object> implements DataInterface<T> {\n\n protected final Combinator<T> combinator;\n protected final Class<T> objectClass;\n protected final String name;\n protected final boolean isTemporaryDataInterface;\n protected final ObjectSerializer<T> objectSerializer;\n private final Object closeLock = new Object();\n private boolean wasClosed;\n\n public BaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface) {\n if (StringUtils.isEmpty(name)) {\n throw new IllegalArgumentException(\"Name can not be null or empty\");\n }\n this.objectClass = objectClass;\n this.name = name;\n this.isTemporaryDataInterface = isTemporaryDataInterface;\n this.combinator = combinator;\n this.objectSerializer = objectSerializer;\n }\n\n public abstract DataInterface<T> getCoreDataInterface();\n\n protected abstract void doClose();\n\n public Combinator<T> getCombinator() {\n return combinator;\n }\n\n @Override\n public ObjectSerializer<T> getObjectSerializer() {\n return objectSerializer;\n }\n\n\n public Class<T> getObjectClass() {\n return objectClass;\n }\n\n public String getName() {\n return name;\n }\n\n public final void close() {\n ifNotClosed(() -> {\n if (isTemporaryDataInterface) {\n dropAllData();\n }\n flush();\n doClose();\n wasClosed = true;\n }\n );\n }\n\n public final boolean wasClosed() {\n return wasClosed;\n }\n\n @Override\n protected void finalize() throws Throwable {\n ifNotClosed(() -> {\n if (!isTemporaryDataInterface()) {\n //the user did not close the data interface himself?\n Log.i(\"Closing data interface \" + getName() + \" because it is about to be garbage collected.\");\n }\n close();\n });\n super.finalize();\n }\n\n public void ifNotClosed(Runnable action) {\n synchronized (closeLock) {\n if (!wasClosed()) {\n action.run();\n }\n }\n }\n\n public boolean isTemporaryDataInterface() {\n return isTemporaryDataInterface;\n }\n\n @Override\n public long apprDataChecksum() {\n CloseableIterator<KeyValue<T>> valueIterator = iterator();\n final int numToSample = 10000;\n long checksum = 0;\n int numDone = 0;\n while (valueIterator.hasNext() && numDone < numToSample) {\n KeyValue<T> next = valueIterator.next();\n if (next.getValue() == null) {\n throw new RuntimeException(\"Iterating over values returned null for key \" + next.getKey());\n }\n T value = next.getValue();\n checksum += checksum * 31 + value.hashCode();\n numDone++;\n }\n valueIterator.close();\n return checksum;\n }\n\n /**\n * You don't want to use this if you could use apprSize()\n */\n\n @Override\n public long exactSize() {\n long result = 0;\n CloseableIterator<Long> keyIt = keyIterator();\n while (keyIt.hasNext()) {\n keyIt.next();\n result++;\n }\n keyIt.close();\n return result;\n }\n\n}", "public abstract class BaseDataInterfaceFactory implements LifeCycleBean, DataInterfaceFactory {\n\n private int tmpDataInterfaceCount = 0;\n\n private final CachesManager cachesManager;\n protected final MemoryManager memoryManager;\n protected final AsyncJobService asyncJobService;\n private final List<DataInterfaceReference> allInterfaces;\n private final ReferenceQueue<DataInterface> allInterfacesReferenceQueue;\n\n private BaseDataInterface<LongBloomFilterWithCheckSum> bloomFiltersInterface;\n\n public BaseDataInterfaceFactory(ApplicationContext context) {\n this.cachesManager = context.getBean(CachesManager.class);\n this.memoryManager = context.getBean(MemoryManager.class);\n this.asyncJobService = context.getBean(AsyncJobService.class);\n this.allInterfaces = new ArrayList<>();\n this.allInterfacesReferenceQueue = new ReferenceQueue<>();\n }\n\n public <T> DataInterfaceConfig<T> dataInterface(String name, Class<T> objectClass, Class... genericParams) {\n return new DataInterfaceConfig<>(name, objectClass, this, genericParams);\n }\n\n @Override\n public <T> MultiDataInterfaceIndex<T> multiIndex(DataInterface<T> dataInterface, String nameOfIndex, MultiDataIndexer<T> indexer) {\n return new MultiDataInterfaceIndex<>(nameOfIndex, this, dataInterface, indexer);\n }\n\n @Override\n public <T> UniqueDataInterfaceIndex<T> uniqueIndex(DataInterface<T> dataInterface, String nameOfIndex, UniqueDataIndexer<T> indexer) {\n return new UniqueDataInterfaceIndex<>(nameOfIndex, this, dataInterface, indexer);\n }\n\n public <T> BaseDataInterface<T> createFromConfig(DataInterfaceConfig<T> config) {\n BaseDataInterface<T> dataInterface;\n String name = config.name;\n if (config.isTemporary) {\n name = createNameForTemporaryInterface(name);\n }\n if (config.objectClass == null) {\n throw new RuntimeException(\"The object class is not set\");\n }\n if (config.combinator == null) {\n throw new RuntimeException(\"The object combinator is not set\");\n }\n if (config.inMemory) {\n dataInterface = new InMemoryDataInterface<>(name, config.objectClass, config.combinator);\n } else {\n if (config.objectSerializer == null) {\n throw new RuntimeException(\"The object serializer is not set\");\n }\n dataInterface = createBaseDataInterface(name, config.objectClass, config.combinator, config.objectSerializer, config.isTemporary);\n }\n if (config.cache) {\n dataInterface = new CachedDataInterface<>(memoryManager, cachesManager, dataInterface, asyncJobService);\n }\n if (config.bloomFilter) {\n checkInitialisationCachedBloomFilters();\n dataInterface = new BloomFilterDataInterface<>(dataInterface, bloomFiltersInterface, asyncJobService);\n }\n registerInterface(dataInterface);\n return dataInterface;\n }\n\n private <T> void registerInterface(BaseDataInterface<T> dataInterface) {\n synchronized (allInterfaces) {\n allInterfaces.add(new DataInterfaceReference(dataInterface, allInterfacesReferenceQueue));\n }\n }\n\n protected abstract <T extends Object> BaseDataInterface<T> createBaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface);\n\n protected abstract Class<? extends DataInterface> getBaseDataInterfaceClass();\n\n public DataInterface<Long> createCountDataInterface(String name) {\n return createDataInterface(name, Long.class, new LongCombinator(), new LongObjectSerializer(), false, false);\n }\n\n public DataInterface<Long> createTmpCountDataInterface(String name) {\n return createDataInterface(createNameForTemporaryInterface(name), Long.class, new LongCombinator(), new LongObjectSerializer(), true, false);\n }\n\n public DataInterface<Long> createInMemoryCountDataInterface(String name) {\n return createDataInterface(name, Long.class, new LongCombinator(), new LongObjectSerializer(), false, true);\n }\n\n public <T extends Object> BaseDataInterface<T> createDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer) {\n return createDataInterface(name, objectClass, combinator, objectSerializer, false, false);\n }\n\n private <T extends Object> BaseDataInterface<T> createDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean temporary, boolean inMemory) {\n DataInterfaceConfig<T> config = dataInterface(name, objectClass);\n config.combinator(combinator);\n config.serializer(objectSerializer);\n if (temporary) {\n config.temporary();\n }\n if (inMemory) {\n config.inMemory();\n }\n return config.create();\n }\n\n private void checkInitialisationCachedBloomFilters() {\n if (bloomFiltersInterface == null) {\n bloomFiltersInterface = createBaseDataInterface(\"system/bloomFilter\", LongBloomFilterWithCheckSum.class, new OverWriteCombinator<>(), new JsonObjectSerializer<>(LongBloomFilterWithCheckSum.class), false);\n synchronized (allInterfaces) {\n allInterfaces.add(new DataInterfaceReference(bloomFiltersInterface, allInterfacesReferenceQueue));\n }\n }\n }\n\n public List<DataInterfaceReference> getAllInterfaces() {\n return allInterfaces;\n }\n\n @Override\n public void startBean() {\n //Do nothing\n }\n\n @Override\n public synchronized void stopBean() {\n terminate();\n }\n\n public synchronized void terminate() {\n closeAllInterfaces();\n }\n\n public void closeAllInterfaces() {\n synchronized (allInterfaces) {\n for (WeakReference<DataInterface> referenceToDI : allInterfaces) {\n final DataInterface dataInterface = referenceToDI.get();\n if (dataInterface != null && !isSystemInterface(dataInterface)) {\n dataInterface.close();\n }\n }\n if (bloomFiltersInterface != null) {\n bloomFiltersInterface.close();\n bloomFiltersInterface = null;\n }\n allInterfaces.clear();\n }\n\n }\n\n private boolean isSystemInterface(DataInterface dataInterface) {\n return dataInterface == bloomFiltersInterface;\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n public void cleanupClosedInterfaces() {\n DataInterfaceReference reference = (DataInterfaceReference) allInterfacesReferenceQueue.poll();\n while (reference != null) {\n synchronized (allInterfaces) {\n allInterfaces.remove(reference);\n }\n reference = (DataInterfaceReference) allInterfacesReferenceQueue.poll();\n }\n }\n\n private String createNameForTemporaryInterface(String name) {\n return \"tmp/\" + name + \"_\" + System.currentTimeMillis() + \"_\" + tmpDataInterfaceCount++ + \"/\";\n }\n\n}", "public interface ObjectSerializer<T> extends Serializable {\n\n void writeValue(T obj, DataStream ds);\n\n T readValue(DataStream ds, int size);\n\n int getObjectSize();\n\n default RemoteObjectConfig createExecConfig() {\n return RemoteObjectConfig.create(this).add(getClass());\n }\n}" ]
import be.bagofwords.db.DataInterface; import be.bagofwords.db.combinator.Combinator; import be.bagofwords.db.impl.BaseDataInterface; import be.bagofwords.db.impl.BaseDataInterfaceFactory; import be.bagofwords.db.methods.ObjectSerializer; import be.bagofwords.logging.Log; import be.bagofwords.memory.MemoryManager; import be.bagofwords.minidepi.ApplicationContext;
package be.bagofwords.db.filedb; public class FileDataInterfaceFactory extends BaseDataInterfaceFactory { private final MemoryManager memoryManager; private final String directory; public FileDataInterfaceFactory(ApplicationContext context) { super(context); this.memoryManager = context.getBean(MemoryManager.class); this.directory = context.getProperty("data_directory"); } @Override
protected <T extends Object> BaseDataInterface<T> createBaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface) {
2
BCA-Team/Buildcraft-Additions
src/main/java/buildcraftAdditions/core/GuiHandler.java
[ "@SideOnly(Side.CLIENT)\npublic class GuiMachineConfigurator extends GuiBase {\n\n\tprivate static final ResourceLocation texture = new ResourceLocation(\"bcadditions:textures/gui/guiMachineConfigurator.png\");\n\tprivate final IConfigurableOutput configurableOutput;\n\tprivate final IUpgradableMachine upgradableMachine;\n\tprivate final boolean configurable, upgradable;\n\tprivate WidgetButtonText northConfiguration, eastConfiguration, southConfiguration, westConfiguration, upConfiguration, downConfiguration;\n\tprivate WidgetButtonText northPriority, eastPriority, southPriority, westPriority, upPriority, downPriority, toggleMode;\n\tprivate WidgetImage upgrades[];\n\tprivate boolean configurationMode;\n\n\tpublic GuiMachineConfigurator(InventoryPlayer inventoryPlayer, TileEntity entity) {\n\t\tsuper(new ContainerMachineConfigurator(inventoryPlayer, entity));\n\t\tif (entity instanceof IConfigurableOutput) {\n\t\t\tconfigurableOutput = (IConfigurableOutput) entity;\n\t\t\tconfigurable = true;\n\t\t} else {\n\t\t\tconfigurableOutput = null;\n\t\t\tconfigurable = false;\n\t\t}\n\t\tif (entity instanceof IUpgradableMachine) {\n\t\t\tupgradableMachine = (IUpgradableMachine) entity;\n\t\t\tupgradable = true;\n\t\t} else {\n\t\t\tupgradableMachine = null;\n\t\t\tupgradable = false;\n\t\t}\n\t\tconfigurationMode = configurable;\n\t\tsetCenterTitle(true);\n\t}\n\n\t@Override\n\tpublic ResourceLocation texture() {\n\t\treturn texture;\n\t}\n\n\t@Override\n\tpublic int getXSize() {\n\t\treturn 224;\n\t}\n\n\t@Override\n\tpublic int getYSize() {\n\t\treturn 165;\n\t}\n\n\t@Override\n\tpublic String getInventoryName() {\n\t\treturn \"machineConfigurator\";\n\t}\n\n\t@Override\n\tpublic void initialize() {\n\t\ttoggleMode = new WidgetButtonText(30, guiLeft + 40, guiTop + 145, 140, 15, this).setText(configurationMode ? Utils.localize(\"gui.configureIO\") : Utils.localize(\"gui.showUpgrades\"));\n\t\tif (configurationMode) {\n\t\t\tnorthConfiguration = new WidgetButtonText(2, guiLeft + 45, guiTop + 26, 60, 15, this);\n\t\t\teastConfiguration = new WidgetButtonText(5, guiLeft + 45, guiTop + 46, 60, 15, this);\n\t\t\tsouthConfiguration = new WidgetButtonText(3, guiLeft + 45, guiTop + 66, 60, 15, this);\n\t\t\twestConfiguration = new WidgetButtonText(4, guiLeft + 45, guiTop + 86, 60, 15, this);\n\t\t\tupConfiguration = new WidgetButtonText(1, guiLeft + 45, guiTop + 106, 60, 15, this);\n\t\t\tdownConfiguration = new WidgetButtonText(0, guiLeft + 45, guiTop + 126, 60, 15, this);\n\n\t\t\tnorthPriority = new WidgetButtonText(8, guiLeft + 158, guiTop + 26, 62, 15, this);\n\t\t\teastPriority = new WidgetButtonText(11, guiLeft + 158, guiTop + 46, 62, 15, this);\n\t\t\tsouthPriority = new WidgetButtonText(9, guiLeft + 158, guiTop + 66, 62, 15, this);\n\t\t\twestPriority = new WidgetButtonText(10, guiLeft + 158, guiTop + 86, 62, 15, this);\n\t\t\tupPriority = new WidgetButtonText(7, guiLeft + 158, guiTop + 106, 62, 15, this);\n\t\t\tdownPriority = new WidgetButtonText(6, guiLeft + 158, guiTop + 126, 62, 15, this);\n\t\t\taddWidget(downConfiguration);\n\t\t\taddWidget(upConfiguration);\n\t\t\taddWidget(northConfiguration);\n\t\t\taddWidget(southConfiguration);\n\t\t\taddWidget(westConfiguration);\n\t\t\taddWidget(eastConfiguration);\n\n\t\t\taddWidget(downPriority);\n\t\t\taddWidget(upPriority);\n\t\t\taddWidget(northPriority);\n\t\t\taddWidget(southPriority);\n\t\t\taddWidget(westPriority);\n\t\t\taddWidget(eastPriority);\n\t\t} else {\n\t\t\tint t = 1;\n\t\t\tfor (EnumMachineUpgrades upgrade : upgradableMachine.getInstalledUpgrades()) {\n\t\t\t\taddWidget(new WidgetImage(14 + t, guiLeft + (25 * t), guiTop + 50, 20, 20, this, upgrade.getTexture(), Utils.localize(\"item.upgrade.\" + upgrade.getTag() + \".name\")));\n\t\t\t\tt++;\n\t\t\t}\n\t\t}\n\t\tif (upgradable && configurable)\n\t\t\taddWidget(toggleMode);\n\t\tupdateButtons();\n\t}\n\n\t@Override\n\tprotected void drawGuiContainerBackgroundLayer(float f, int x, int y) {\n\t\tsuper.drawGuiContainerBackgroundLayer(f, x, y);\n\t\tif (configurationMode) {\n\t\t\tdrawString(Utils.localize(\"gui.north\") + \":\", guiLeft + 10, guiTop + 30);\n\t\t\tdrawString(Utils.localize(\"gui.east\") + \": \", guiLeft + 10, guiTop + 50);\n\t\t\tdrawString(Utils.localize(\"gui.south\") + \": \", guiLeft + 10, guiTop + 70);\n\t\t\tdrawString(Utils.localize(\"gui.west\") + \": \", guiLeft + 10, guiTop + 90);\n\t\t\tdrawString(Utils.localize(\"gui.up\") + \": \", guiLeft + 10, guiTop + 110);\n\t\t\tdrawString(Utils.localize(\"gui.down\") + \": \", guiLeft + 10, guiTop + 130);\n\n\t\t\tif (configurableOutput.getStatus(ForgeDirection.NORTH).hasPriority())\n\t\t\t\tdrawString(Utils.localize(\"gui.priority\") + \": \", guiLeft + 110, guiTop + 30);\n\t\t\tif (configurableOutput.getStatus(ForgeDirection.EAST).hasPriority())\n\t\t\t\tdrawString(Utils.localize(\"gui.priority\") + \": \", guiLeft + 110, guiTop + 50);\n\t\t\tif (configurableOutput.getStatus(ForgeDirection.SOUTH).hasPriority())\n\t\t\t\tdrawString(Utils.localize(\"gui.priority\") + \": \", guiLeft + 110, guiTop + 70);\n\t\t\tif (configurableOutput.getStatus(ForgeDirection.WEST).hasPriority())\n\t\t\t\tdrawString(Utils.localize(\"gui.priority\") + \": \", guiLeft + 110, guiTop + 90);\n\t\t\tif (configurableOutput.getStatus(ForgeDirection.UP).hasPriority())\n\t\t\t\tdrawString(Utils.localize(\"gui.priority\") + \": \", guiLeft + 110, guiTop + 110);\n\t\t\tif (configurableOutput.getStatus(ForgeDirection.DOWN).hasPriority())\n\t\t\t\tdrawString(Utils.localize(\"gui.priority\") + \": \", guiLeft + 110, guiTop + 130);\n\t\t} else {\n\t\t\tdrawString(Utils.localize(\"gui.installedUpgrades\"), guiLeft + 20, guiTop + 25);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void widgetActionPerformed(WidgetBase widget) {\n\t\tif (widget.id < 6)\n\t\t\tconfigurableOutput.changeStatus(ForgeDirection.getOrientation(widget.id));\n\t\telse if (widget.id < 14)\n\t\t\tconfigurableOutput.changePriority(ForgeDirection.getOrientation(widget.id - 6));\n\t\telse if (widget.id == 30)\n\t\t\tconfigurationMode = !configurationMode;\n\t\tif (configurableOutput != null)\n\t\t\tPacketHandler.instance.sendToServer(new MessageConfiguration(configurableOutput));\n\t}\n\n\t@Override\n\tprotected void mouseClicked(int x, int y, int button) {\n\t\tsuper.mouseClicked(x, y, button);\n\t\tredraw();\n\t\tupdateButtons();\n\t}\n\n\tprivate void updateButtons() {\n\t\tif (!configurationMode)\n\t\t\treturn;\n\t\tWidgetButtonText button;\n\t\tfor (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) {\n\t\t\tbutton = ((WidgetButtonText) widgets.get(direction.ordinal()));\n\t\t\tbutton.setText(configurableOutput.getStatus(direction).getName());\n\t\t\tbutton.setColor(configurableOutput.getStatus(direction).getColor());\n\n\t\t\tbutton = ((WidgetButtonText) widgets.get(direction.ordinal() + 6));\n\t\t\tbutton.setText(configurableOutput.getPriority(direction).getName());\n\t\t\tbutton.setColor(configurableOutput.getPriority(direction).getColor());\n\t\t\tbutton.setShouldRender(configurableOutput.getStatus(direction).hasPriority());\n\t\t}\n\t}\n\n}", "public class ContainerChargingStation extends ContainerBase<TileChargingStation> {\n\n\tpublic ContainerChargingStation(InventoryPlayer inventoryPlayer, TileChargingStation tile) {\n\t\tsuper(inventoryPlayer, tile);\n\t\taddSlotToContainer(new Slot(tile, 0, 80, 30) {\n\n\t\t\t@Override\n\t\t\tpublic int getSlotStackLimit() {\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isItemValid(ItemStack stack) {\n\t\t\t\treturn stack != null && stack.getItem() != null && stack.getItem() instanceof IEnergyContainerItem;\n\t\t\t}\n\n\t\t});\n\t\taddPlayerInventory(8, 71);\n\t}\n\n}", "public class ContainerCoolingTower extends ContainerBase<TileCoolingTower> {\n\n\tprivate int heat, fluidIDInput, fluidAmountInput, fluidIDOutput, fluidAmountOutput, fluidIDCoolant, fluidAmountCoolant;\n\n\tpublic ContainerCoolingTower(TileCoolingTower tile) {\n\t\tsuper(null, tile);\n\t\tsetCanShift(false);\n\t}\n\n\t@Override\n\tpublic void addCraftingToCrafters(ICrafting crafting) {\n\t\tsuper.addCraftingToCrafters(crafting);\n\t\tcrafting.sendProgressBarUpdate(this, 0, MathHelper.floor_float(inventory.heat * 32));\n\t\tcrafting.sendProgressBarUpdate(this, 1, inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1);\n\t\tcrafting.sendProgressBarUpdate(this, 2, inventory.input.getFluidAmount());\n\t\tcrafting.sendProgressBarUpdate(this, 3, inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1);\n\t\tcrafting.sendProgressBarUpdate(this, 4, inventory.output.getFluidAmount());\n\t\tcrafting.sendProgressBarUpdate(this, 5, inventory.coolant.getFluidAmount() > 0 ? inventory.coolant.getFluid().getFluidID() : -1);\n\t\tcrafting.sendProgressBarUpdate(this, 6, inventory.coolant.getFluidAmount());\n\t}\n\n\t@Override\n\tpublic void detectAndSendChanges() {\n\t\tsuper.detectAndSendChanges();\n\t\tif (crafters != null) {\n\t\t\tfor (Object o : crafters) {\n\t\t\t\tif (o != null && o instanceof ICrafting) {\n\t\t\t\t\tICrafting crafting = (ICrafting) o;\n\t\t\t\t\tif (heat != MathHelper.floor_float(inventory.heat * 32))\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 0, MathHelper.floor_float(inventory.heat * 32));\n\t\t\t\t\tif (fluidIDInput != (inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1))\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 1, inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1);\n\t\t\t\t\tif (fluidAmountInput != inventory.input.getFluidAmount())\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 2, inventory.input.getFluidAmount());\n\t\t\t\t\tif (fluidIDOutput != (inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1))\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 3, inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1);\n\t\t\t\t\tif (fluidAmountOutput != inventory.output.getFluidAmount())\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 4, inventory.output.getFluidAmount());\n\t\t\t\t\tif (fluidIDCoolant != (inventory.coolant.getFluidAmount() > 0 ? inventory.coolant.getFluid().getFluidID() : -1))\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 5, inventory.coolant.getFluidAmount() > 0 ? inventory.coolant.getFluid().getFluidID() : -1);\n\t\t\t\t\tif (fluidAmountCoolant != inventory.coolant.getFluidAmount())\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 6, inventory.coolant.getFluidAmount());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\theat = MathHelper.floor_float(inventory.heat * 32);\n\t\tfluidIDInput = inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1;\n\t\tfluidAmountInput = inventory.input.getFluidAmount();\n\t\tfluidIDOutput = inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1;\n\t\tfluidAmountOutput = inventory.output.getFluidAmount();\n\t\tfluidIDCoolant = inventory.coolant.getFluidAmount() > 0 ? inventory.coolant.getFluid().getFluidID() : -1;\n\t\tfluidAmountCoolant = inventory.coolant.getFluidAmount();\n\t}\n\n\t@Override\n\t@SideOnly(Side.CLIENT)\n\tpublic void updateProgressBar(int id, int value) {\n\t\tsuper.updateProgressBar(id, value);\n\t\tswitch (id) {\n\t\t\tcase 0:\n\t\t\t\tinventory.heat = value / 32F;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (value >= 0)\n\t\t\t\t\tinventory.input.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.input.getFluidAmount()));\n\t\t\t\telse\n\t\t\t\t\tinventory.input.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (value > 0 && inventory.input.getFluid() != null)\n\t\t\t\t\tinventory.input.setFluid(new FluidStack(inventory.input.getFluid(), value));\n\t\t\t\telse\n\t\t\t\t\tinventory.input.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tif (value >= 0)\n\t\t\t\t\tinventory.output.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.output.getFluidAmount()));\n\t\t\t\telse\n\t\t\t\t\tinventory.output.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tif (value > 0 && inventory.output.getFluid() != null)\n\t\t\t\t\tinventory.output.setFluid(new FluidStack(inventory.output.getFluid(), value));\n\t\t\t\telse\n\t\t\t\t\tinventory.output.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tif (value >= 0)\n\t\t\t\t\tinventory.coolant.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.coolant.getFluidAmount()));\n\t\t\t\telse\n\t\t\t\t\tinventory.coolant.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tif (value > 0 && inventory.coolant.getFluid() != null)\n\t\t\t\t\tinventory.coolant.setFluid(new FluidStack(inventory.coolant.getFluid(), value));\n\t\t\t\telse\n\t\t\t\t\tinventory.coolant.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void addPlayerInventory(int x, int y) {\n\n\t}\n\n\t@Override\n\tpublic ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected Slot addSlotToContainer(Slot slot) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Slot getSlot(int id) {\n\t\treturn new SlotFake(null, -5, -5, 0);\n\t}\n}", "public class ContainerRefinery extends ContainerBase<TileRefinery> {\n\n\tprivate int currentHeat, requiredHeat, energyCost, fluidIDInput, fluidAmountInput, fluidIDOutput, fluidAmountOutput;\n\n\tpublic ContainerRefinery(InventoryPlayer inventoryPlayer, TileRefinery tile) {\n\t\tsuper(inventoryPlayer, tile);\n\t}\n\n\t@Override\n\tpublic void addCraftingToCrafters(ICrafting crafting) {\n\t\tsuper.addCraftingToCrafters(crafting);\n\t\tcrafting.sendProgressBarUpdate(this, 0, inventory.currentHeat);\n\t\tcrafting.sendProgressBarUpdate(this, 1, inventory.requiredHeat);\n\t\tcrafting.sendProgressBarUpdate(this, 2, inventory.energyCost);\n\t\tcrafting.sendProgressBarUpdate(this, 3, inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1);\n\t\tcrafting.sendProgressBarUpdate(this, 4, inventory.input.getFluidAmount());\n\t\tcrafting.sendProgressBarUpdate(this, 5, inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1);\n\t\tcrafting.sendProgressBarUpdate(this, 6, inventory.output.getFluidAmount());\n\t}\n\n\t@Override\n\tpublic void detectAndSendChanges() {\n\t\tsuper.detectAndSendChanges();\n\t\tif (crafters != null) {\n\t\t\tfor (Object o : crafters) {\n\t\t\t\tif (o != null && o instanceof ICrafting) {\n\t\t\t\t\tICrafting crafting = (ICrafting) o;\n\t\t\t\t\tif (currentHeat != inventory.currentHeat)\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 0, inventory.currentHeat);\n\t\t\t\t\tif (requiredHeat != inventory.requiredHeat)\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 1, inventory.requiredHeat);\n\t\t\t\t\tif (energyCost != inventory.energyCost)\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 2, inventory.energyCost);\n\t\t\t\t\tif (fluidIDInput != (inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1))\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 3, inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1);\n\t\t\t\t\tif (fluidAmountInput != inventory.input.getFluidAmount())\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 4, inventory.input.getFluidAmount());\n\t\t\t\t\tif (fluidIDOutput != (inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1))\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 5, inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1);\n\t\t\t\t\tif (fluidAmountOutput != inventory.output.getFluidAmount())\n\t\t\t\t\t\tcrafting.sendProgressBarUpdate(this, 6, inventory.output.getFluidAmount());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcurrentHeat = inventory.currentHeat;\n\t\trequiredHeat = inventory.requiredHeat;\n\t\tenergyCost = inventory.energyCost;\n\t\tfluidIDInput = inventory.input.getFluidAmount() > 0 ? inventory.input.getFluid().getFluidID() : -1;\n\t\tfluidAmountInput = inventory.input.getFluidAmount();\n\t\tfluidIDOutput = inventory.output.getFluidAmount() > 0 ? inventory.output.getFluid().getFluidID() : -1;\n\t\tfluidAmountOutput = inventory.output.getFluidAmount();\n\t}\n\n\t@Override\n\t@SideOnly(Side.CLIENT)\n\tpublic void updateProgressBar(int id, int value) {\n\t\tsuper.updateProgressBar(id, value);\n\t\tswitch (id) {\n\t\t\tcase 0:\n\t\t\t\tinventory.currentHeat = value;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tinventory.requiredHeat = value;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tinventory.energyCost = value;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tif (value >= 0)\n\t\t\t\t\tinventory.input.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.input.getFluidAmount()));\n\t\t\t\telse\n\t\t\t\t\tinventory.input.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tif (value > 0 && inventory.input.getFluid() != null)\n\t\t\t\t\tinventory.input.setFluid(new FluidStack(inventory.input.getFluid(), value));\n\t\t\t\telse\n\t\t\t\t\tinventory.input.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tif (value >= 0)\n\t\t\t\t\tinventory.output.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.output.getFluidAmount()));\n\t\t\t\telse\n\t\t\t\t\tinventory.output.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tif (value > 0 && inventory.output.getFluid() != null)\n\t\t\t\t\tinventory.output.setFluid(new FluidStack(inventory.output.getFluid(), value));\n\t\t\t\telse\n\t\t\t\t\tinventory.output.setFluid(null);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void addPlayerInventory(int x, int y) {\n\n\t}\n\n\t@Override\n\tpublic ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected Slot addSlotToContainer(Slot slot) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Slot getSlot(int id) {\n\t\treturn new SlotFake(null, -5, -5, 0);\n\t}\n\n}", "public abstract class TileKineticEnergyBufferBase extends TileBase implements IEnergyReceiver, IEnergyProvider, IConfigurableOutput, ISynchronizedTile, IOwnableMachine, IPipeConnection {\n\n\tpublic final int tier;\n\tprotected final SideConfiguration configuration = new SideConfiguration();\n\tprotected final boolean[] blocked = new boolean[6];\n\tpublic int energy, capacity, maxTransfer, loss, fuse;\n\tpublic boolean selfDestruct, engineControl;\n\tpublic EntityPlayer destroyer;\n\tprivate UUID owner;\n\n\tpublic TileKineticEnergyBufferBase(int capacity, int maxTransfer, int loss, int tier, int identifier) {\n\t\tsuper(identifier);\n\t\tthis.capacity = capacity;\n\t\tthis.maxTransfer = maxTransfer;\n\t\tthis.loss = loss;\n\t\tthis.tier = tier;\n\t}\n\n\t@Override\n\tpublic int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) {\n\t\tif (!configuration.canReceive(from))\n\t\t\treturn 0;\n\t\tint energyReceived = Math.min(capacity - energy, Math.min(maxTransfer, maxReceive));\n\t\tif (!simulate) {\n\t\t\tenergy += energyReceived;\n\t\t\tblocked[from.ordinal()] = true;\n\t\t}\n\t\treturn energyReceived;\n\t}\n\n\t@Override\n\tpublic int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) {\n\t\tif (!configuration.canSend(from))\n\t\t\treturn 0;\n\t\tint energyExtracted = Math.min(energy, Math.min(maxTransfer, maxExtract));\n\t\tif (!simulate)\n\t\t\tenergy -= energyExtracted;\n\t\treturn energyExtracted;\n\t}\n\n\t@Override\n\tpublic int getEnergyStored(ForgeDirection from) {\n\t\treturn energy;\n\t}\n\n\t@Override\n\tpublic int getMaxEnergyStored(ForgeDirection from) {\n\t\treturn capacity;\n\t}\n\n\t@Override\n\tpublic void readFromNBT(NBTTagCompound tag) {\n\t\tsuper.readFromNBT(tag);\n\t\tif (tag.hasKey(\"energy\")) {\n\t\t\tenergy = tag.getInteger(\"energy\");\n\t\t\tcapacity = tag.getInteger(\"maxEnergy\");\n\t\t\tmaxTransfer = Math.max(tag.getInteger(\"maxTransfer\"), Math.max(tag.getInteger(\"maxInput\"), tag.getInteger(\"maxOutput\")));\n\t\t\tloss = tag.getInteger(\"loss\");\n\t\t\tengineControl = tag.getBoolean(\"engineControl\");\n\t\t\tconfiguration.readFromNBT(tag);\n\t\t\towner = PlayerUtils.readFromNBT(tag);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void writeToNBT(NBTTagCompound tag) {\n\t\tsuper.writeToNBT(tag);\n\t\ttag.setInteger(\"energy\", energy);\n\t\ttag.setInteger(\"maxEnergy\", capacity);\n\t\ttag.setInteger(\"maxTransfer\", maxTransfer);\n\t\ttag.setInteger(\"loss\", loss);\n\t\ttag.setBoolean(\"engineControl\", engineControl);\n\t\tconfiguration.writeToNBT(tag);\n\t\tPlayerUtils.writeToNBT(tag, owner);\n\t}\n\n\t@Override\n\tpublic void updateEntity() {\n\t\tif (getEnergyLevel() > 85)\n\t\t\tengineControl = false;\n\t\tif (getEnergyLevel() < 30)\n\t\t\tengineControl = true;\n\t\tsuper.updateEntity();\n\t\tif (selfDestruct) {\n\t\t\tfuse--;\n\t\t\tif (fuse % 20 == 0)\n\t\t\t\tdestroyer.addChatComponentMessage(new ChatComponentText(Utils.localize(\"selfdestructCountdouwn\") + \": \" + fuse / 20));\n\t\t}\n\t\tif (fuse <= 0 && selfDestruct)\n\t\t\tbyeBye();\n\t\tif (ConfigurationHandler.powerloss)\n\t\t\tenergy -= loss;\n\t\tif (energy < 0)\n\t\t\tenergy = 0;\n\t\tif(energy > capacity)\n\t\t\tenergy = capacity;\n\t\toutputEnergy();\n\t}\n\n\tpublic abstract void outputEnergy();\n\n\tprotected boolean canSharePower(TileEntity target, ForgeDirection outputSide) {\n\t\tif (configuration.canReceive(outputSide) && configuration.canSend(outputSide) && target instanceof TileKineticEnergyBufferTier1) {\n\t\t\tTileKineticEnergyBufferTier1 keb = (TileKineticEnergyBufferTier1) target;\n\t\t\tif (keb.getStatus(outputSide.getOpposite()) == EnumSideStatus.BOTH)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean canConnectEnergy(ForgeDirection from) {\n\t\treturn configuration.canReceive(from) || configuration.canSend(from);\n\t}\n\n\tpublic void sendConfigurationToSever() {\n\t\tPacketHandler.instance.sendToServer(new MessageConfiguration(this));\n\t}\n\n\t@Override\n\tpublic UUID getOwner() {\n\t\treturn owner;\n\t}\n\n\t@Override\n\tpublic void setOwner(UUID owner) {\n\t\tthis.owner = owner;\n\t}\n\n\t@Override\n\tpublic boolean hasOwner() {\n\t\treturn owner != null;\n\t}\n\n\tpublic void activateSelfDestruct() {\n\t\tif (worldObj.isRemote) {\n\t\t\tPacketHandler.instance.sendToServer(new MessageSelfDestruct(xCoord, yCoord, zCoord));\n\t\t\treturn;\n\t\t}\n\t\tselfDestruct = true;\n\t\tfuse = 100;\n\t\tdestroyer.addChatComponentMessage(new ChatComponentText(Utils.localize(\"selfdestructActivated\")));\n\t\tdestroyer.closeScreen();\n\t}\n\n\tpublic void byeBye() {\n\t\tExplosion explosion = worldObj.createExplosion(destroyer, xCoord, yCoord, zCoord, (energy / 900000) + 5, true);\n\t\texplosion.doExplosionA();\n\t\texplosion.doExplosionB(true);\n\t}\n\n\t@Override\n\tpublic EnumSideStatus getStatus(ForgeDirection side) {\n\t\treturn configuration.getStatus(side);\n\t}\n\n\t@Override\n\tpublic void changeStatus(ForgeDirection side) {\n\t\tconfiguration.changeStatus(side);\n\t\tworldObj.markBlockForUpdate(xCoord, yCoord, zCoord);\n\t}\n\n\t@Override\n\tpublic void writeToByteBuff(ByteBuf buf) {\n\t\tbuf.writeInt(energy);\n\t\tconfiguration.writeToByteBuff(buf);\n\t\tPlayerUtils.writeToByteBuff(buf, owner);\n\t}\n\n\t@Override\n\tpublic void readFromByteBuff(ByteBuf buf) {\n\t\tenergy = buf.readInt();\n\t\tconfiguration.readFromByteBuff(buf);\n\t\towner = PlayerUtils.readFromByteBuff(buf);\n\t}\n\n\t@Override\n\tpublic int getX() {\n\t\treturn xCoord;\n\t}\n\n\t@Override\n\tpublic int getY() {\n\t\treturn yCoord;\n\t}\n\n\t@Override\n\tpublic int getZ() {\n\t\treturn zCoord;\n\t}\n\n\tpublic int getEnergyLevel() {\n\t\tif (getMaxEnergyStored(ForgeDirection.UNKNOWN) == 0)\n\t\t\treturn 0;\n\t\treturn (int) ((float) getEnergyStored(ForgeDirection.UNKNOWN) / getMaxEnergyStored(ForgeDirection.UNKNOWN) * 100);\n\t}\n\n\t@Override\n\tpublic EnumPriority getPriority(ForgeDirection side) {\n\t\treturn configuration.getPriority(side);\n\t}\n\n\t@Override\n\tpublic void changePriority(ForgeDirection side) {\n\t\tconfiguration.changePriority(side);\n\t}\n\n\t@Override\n\tpublic SideConfiguration getSideConfiguration() {\n\t\treturn configuration;\n\t}\n\n\t@Override\n\tpublic void setSideConfiguration(SideConfiguration configuration) {\n\t\tthis.configuration.load(configuration);\n\t}\n\n\tpublic ConnectOverride overridePipeConnection(IPipeTile.PipeType type, ForgeDirection from) {\n\t\tif ((configuration.getStatus(from).canReceive() || configuration.getStatus(from).canSend()) && type == IPipeTile.PipeType.POWER)\n\t\t\treturn ConnectOverride.CONNECT;\n\t\treturn ConnectOverride.DISCONNECT;\n\t}\n}", "public class TileFluidicCompressor extends TileMachineBase implements ISidedInventory, IFluidHandler, IWidgetListener {\n\n\tpublic final Tank tank = new Tank(FluidContainerRegistry.BUCKET_VOLUME * 10, this, \"Tank\");\n\tprivate final CustomInventory inventory = new CustomInventory(\"FluidicCompressor\", 2, 1, this);\n\tpublic boolean fill;\n\n\tpublic TileFluidicCompressor() {\n\t\tsuper(ConfigurationHandler.capacityFluidicCompressor, ConfigurationHandler.maxTransferFluidicCompressor, Variables.SyncIDs.FLUIDIC_COMPRESSOR.ordinal());\n\t}\n\n\t@Override\n\tpublic void updateEntity() {\n\t\tsuper.updateEntity();\n\t\tif (worldObj.isRemote)\n\t\t\treturn;\n\t\tItemStack stack = inventory.getStackInSlot(0);\n\t\tif (stack != null) {\n\t\t\tItem stackItem = stack.getItem();\n\t\t\tif (stackItem instanceof IFluidContainerItem) {\n\t\t\t\tIFluidContainerItem iFluidContainerItem = (IFluidContainerItem) stackItem;\n\t\t\t\tif (fill) {\n\t\t\t\t\tif (!tank.isEmpty()) {\n\t\t\t\t\t\tint amount = 128;\n\t\t\t\t\t\tif (tank.getFluidAmount() < amount)\n\t\t\t\t\t\t\tamount = tank.getFluidAmount();\n\t\t\t\t\t\tif (energy >= amount) {\n\t\t\t\t\t\t\tdrain(ForgeDirection.UNKNOWN, iFluidContainerItem.fill(stack, new FluidStack(tank.getFluid(), amount), true), true);\n\t\t\t\t\t\t\tenergy -= amount;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tFluidStack contained = iFluidContainerItem.getFluid(stack);\n\t\t\t\t\tif (!fill && !tank.isFull() && contained != null && contained.amount > 0) {\n\t\t\t\t\t\tint amount = 64;\n\t\t\t\t\t\tif (tank.getFreeSpace() < amount)\n\t\t\t\t\t\t\tamount = tank.getFreeSpace();\n\t\t\t\t\t\tif (amount > contained.amount)\n\t\t\t\t\t\t\tamount = contained.amount;\n\t\t\t\t\t\tiFluidContainerItem.drain(stack, fill(ForgeDirection.UNKNOWN, new FluidStack(contained, amount), true), true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (FluidContainerRegistry.isContainer(stack)) {\n\t\t\t\tif (fill) {\n\t\t\t\t\tif (!tank.isEmpty()) {\n\t\t\t\t\t\tint amount = FluidContainerRegistry.getContainerCapacity(tank.getFluid(), stack);\n\t\t\t\t\t\tif (amount > 0 && energy >= amount && tank.getFluidAmount() >= amount) {\n\t\t\t\t\t\t\tItemStack filledContainer = FluidContainerRegistry.fillFluidContainer(new FluidStack(tank.getFluid(), amount), stack);\n\t\t\t\t\t\t\tif (filledContainer != null && filledContainer.getItem() != null && filledContainer.stackSize > 0) {\n\t\t\t\t\t\t\t\tenergy -= amount;\n\t\t\t\t\t\t\t\tdrain(ForgeDirection.UNKNOWN, amount, true);\n\t\t\t\t\t\t\t\tinventory.setInventorySlotContents(0, filledContainer.copy());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tFluidStack contained = FluidContainerRegistry.getFluidForFilledItem(stack);\n\t\t\t\t\tif (contained != null && contained.amount > 0 && tank.getFreeSpace() >= contained.amount) {\n\t\t\t\t\t\tif (fill(ForgeDirection.UNKNOWN, contained, false) == contained.amount) {\n\t\t\t\t\t\t\tfill(ForgeDirection.UNKNOWN, contained, true);\n\t\t\t\t\t\t\tItemStack drainedContainer = FluidContainerRegistry.drainFluidContainer(stack);\n\t\t\t\t\t\t\tif (drainedContainer != null && drainedContainer.getItem() != null && drainedContainer.stackSize > 0)\n\t\t\t\t\t\t\t\tinventory.setInventorySlotContents(0, drainedContainer.copy());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (getProgress() >= 16) {\n\t\t\t\tstack = getStackInSlot(0);\n\t\t\t\tif (stack != null) {\n\t\t\t\t\tItemStack outputStack = getStackInSlot(1);\n\t\t\t\t\tif (outputStack == null || outputStack.getItem() == null || outputStack.stackSize <= 0) {\n\t\t\t\t\t\tItemStack copyStack = stack.copy();\n\t\t\t\t\t\tcopyStack.stackSize = 1;\n\t\t\t\t\t\tinventory.setInventorySlotContents(1, copyStack);\n\t\t\t\t\t\tinventory.decrStackSize(0, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void readFromNBT(NBTTagCompound nbtTagCompound) {\n\t\tsuper.readFromNBT(nbtTagCompound);\n\t\tfill = nbtTagCompound.getBoolean(\"fill\");\n\t\tinventory.readFromNBT(nbtTagCompound);\n\t\tif (nbtTagCompound.hasKey(\"tank\", Constants.NBT.TAG_COMPOUND))\n\t\t\ttank.readFromNBT(nbtTagCompound.getCompoundTag(\"tank\"));\n\t}\n\n\t@Override\n\tpublic void writeToNBT(NBTTagCompound nbtTagCompound) {\n\t\tsuper.writeToNBT(nbtTagCompound);\n\t\tnbtTagCompound.setBoolean(\"fill\", fill);\n\t\tinventory.writeToNBT(nbtTagCompound);\n\t\tnbtTagCompound.setTag(\"tank\", tank.writeToNBT(new NBTTagCompound()));\n\t}\n\n\t@Override\n\tpublic int getSizeInventory() {\n\t\treturn inventory.getSizeInventory();\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlot(int slotId) {\n\t\treturn inventory.getStackInSlot(slotId);\n\t}\n\n\t@Override\n\tpublic ItemStack decrStackSize(int slotId, int count) {\n\t\treturn inventory.decrStackSize(slotId, count);\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlotOnClosing(int var1) {\n\t\treturn inventory.getStackInSlotOnClosing(var1);\n\t}\n\n\t@Override\n\tpublic void setInventorySlotContents(int slotId, ItemStack itemstack) {\n\t\tinventory.setInventorySlotContents(slotId, itemstack);\n\t}\n\n\t@Override\n\tpublic String getInventoryName() {\n\t\treturn inventory.getInventoryName();\n\t}\n\n\t@Override\n\tpublic boolean hasCustomInventoryName() {\n\t\treturn inventory.hasCustomInventoryName();\n\t}\n\n\t@Override\n\tpublic int getInventoryStackLimit() {\n\t\treturn inventory.getInventoryStackLimit();\n\t}\n\n\t@Override\n\tpublic boolean isUseableByPlayer(EntityPlayer entityPlayer) {\n\t\treturn worldObj.getTileEntity(xCoord, yCoord, zCoord) == this && entityPlayer.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64;\n\t}\n\n\t@Override\n\tpublic void openInventory() {\n\t\tinventory.openInventory();\n\t}\n\n\t@Override\n\tpublic void closeInventory() {\n\t\tinventory.openInventory();\n\t}\n\n\t@Override\n\tpublic boolean isItemValidForSlot(int slot, ItemStack stack) {\n\t\treturn stack != null && stack.getItem() != null && slot == 0 && (stack.getItem() instanceof IFluidContainerItem || FluidContainerRegistry.isContainer(stack));\n\t}\n\n\t@Override\n\tpublic int fill(ForgeDirection from, FluidStack resource, boolean doFill) {\n\t\treturn tank.fill(resource, doFill);\n\t}\n\n\t@Override\n\tpublic FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {\n\t\treturn tank.drain(resource, doDrain);\n\t}\n\n\t@Override\n\tpublic FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {\n\t\treturn tank.drain(maxDrain, doDrain);\n\t}\n\n\t@Override\n\tpublic boolean canFill(ForgeDirection from, Fluid fluid) {\n\t\treturn tank.getFluidType() == fluid;\n\t}\n\n\t@Override\n\tpublic boolean canDrain(ForgeDirection from, Fluid fluid) {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic FluidTankInfo[] getTankInfo(ForgeDirection from) {\n\t\treturn new FluidTankInfo[]{new FluidTankInfo(tank)};\n\t}\n\n\tpublic FluidStack getFluid() {\n\t\treturn tank.getFluid();\n\t}\n\n\tpublic int getProgress() {\n\t\tItemStack stack = inventory.getStackInSlot(0);\n\t\tif (stack == null)\n\t\t\treturn 0;\n\t\tItem item = stack.getItem();\n\t\tFluidStack fluidstack = null;\n\t\tint capacity = 0;\n\t\tif (item instanceof IFluidContainerItem) {\n\t\t\tIFluidContainerItem iFluidContainerItem = (IFluidContainerItem) stack.getItem();\n\t\t\tfluidstack = iFluidContainerItem.getFluid(stack);\n\t\t\tcapacity = iFluidContainerItem.getCapacity(stack);\n\t\t} else if (FluidContainerRegistry.isContainer(stack)) {\n\t\t\tfluidstack = FluidContainerRegistry.getFluidForFilledItem(stack);\n\t\t\tcapacity = FluidContainerRegistry.getContainerCapacity(fill ? tank.getFluid() : fluidstack, stack);\n\t\t}\n\n\t\tif (fluidstack == null || capacity <= 0) {\n\t\t\tif (fill)\n\t\t\t\treturn 0;\n\t\t\treturn 16;\n\t\t}\n\t\tif (fill)\n\t\t\treturn (int) ((fluidstack.amount * 16D) / capacity);\n\t\treturn (int) (((capacity - fluidstack.amount) * 16D) / capacity);\n\t}\n\n\t@Override\n\tpublic int[] getAccessibleSlotsFromSide(int side) {\n\t\treturn Utils.createSlotArray(0, 2);\n\t}\n\n\t@Override\n\tpublic boolean canInsertItem(int slot, ItemStack stack, int side) {\n\t\treturn slot == 0 && isItemValidForSlot(slot, stack);\n\t}\n\n\t@Override\n\tpublic boolean canExtractItem(int slot, ItemStack stack, int side) {\n\t\treturn slot == 1;\n\t}\n\n\t@Override\n\tpublic void writeToByteBuff(ByteBuf buf) {\n\t\tsuper.writeToByteBuff(buf);\n\t\tbuf.writeBoolean(fill);\n\t\ttank.writeToByteBuff(buf);\n\t\tinventory.writeToByteBuff(buf);\n\t}\n\n\t@Override\n\tpublic void readFromByteBuff(ByteBuf buf) {\n\t\tsuper.readFromByteBuff(buf);\n\t\tfill = buf.readBoolean();\n\t\ttank.readFromByteBuff(buf);\n\t\tinventory.readFromByteBuff(buf);\n\t}\n\n\t@Override\n\tpublic void onWidgetPressed(int id, int value) {\n\t\tfill = value == 1;\n\t}\n}" ]
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import cpw.mods.fml.common.network.IGuiHandler; import buildcraftAdditions.api.configurableOutput.IConfigurableOutput; import buildcraftAdditions.client.gui.GuiBasicCoil; import buildcraftAdditions.client.gui.GuiChargingStation; import buildcraftAdditions.client.gui.GuiCoolingTower; import buildcraftAdditions.client.gui.GuiFluidicCompressor; import buildcraftAdditions.client.gui.GuiHeatedFurnace; import buildcraftAdditions.client.gui.GuiItemSorter; import buildcraftAdditions.client.gui.GuiKEB; import buildcraftAdditions.client.gui.GuiKineticMultiTool; import buildcraftAdditions.client.gui.GuiMachineConfigurator; import buildcraftAdditions.client.gui.GuiPipeColoringTool; import buildcraftAdditions.client.gui.GuiPortableLaser; import buildcraftAdditions.client.gui.GuiRefinery; import buildcraftAdditions.inventories.InventoryKineticMultiTool; import buildcraftAdditions.inventories.InventoryPortableLaser; import buildcraftAdditions.inventories.containers.ContainerBasicCoil; import buildcraftAdditions.inventories.containers.ContainerChargingStation; import buildcraftAdditions.inventories.containers.ContainerCoolingTower; import buildcraftAdditions.inventories.containers.ContainerFluidicCompressor; import buildcraftAdditions.inventories.containers.ContainerHeatedFurnace; import buildcraftAdditions.inventories.containers.ContainerItemSorter; import buildcraftAdditions.inventories.containers.ContainerKEB; import buildcraftAdditions.inventories.containers.ContainerKineticMultiTool; import buildcraftAdditions.inventories.containers.ContainerMachineConfigurator; import buildcraftAdditions.inventories.containers.ContainerPipeColoringTool; import buildcraftAdditions.inventories.containers.ContainerPortableLaser; import buildcraftAdditions.inventories.containers.ContainerRefinery; import buildcraftAdditions.items.Tools.ItemKineticMultiTool; import buildcraftAdditions.items.Tools.ItemPipeColoringTool; import buildcraftAdditions.items.Tools.ItemPortableLaser; import buildcraftAdditions.multiBlocks.IMultiBlockTile; import buildcraftAdditions.reference.Variables; import buildcraftAdditions.tileEntities.Bases.TileKineticEnergyBufferBase; import buildcraftAdditions.tileEntities.TileBasicCoil; import buildcraftAdditions.tileEntities.TileChargingStation; import buildcraftAdditions.tileEntities.TileCoolingTower; import buildcraftAdditions.tileEntities.TileFluidicCompressor; import buildcraftAdditions.tileEntities.TileHeatedFurnace; import buildcraftAdditions.tileEntities.TileItemSorter; import buildcraftAdditions.tileEntities.TileRefinery; import buildcraftAdditions.tileEntities.interfaces.IUpgradableMachine;
package buildcraftAdditions.core; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public final class GuiHandler implements IGuiHandler { public static final GuiHandler INSTANCE = new GuiHandler(); private GuiHandler() { } @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { TileEntity tile = world.getTileEntity(x, y, z); switch (Variables.Gui.values()[ID]) { case FLUIDIC_COMPRESSOR: if (tile instanceof TileFluidicCompressor) return new ContainerFluidicCompressor(player.inventory, (TileFluidicCompressor) tile); case CHARGING_STATION: if (tile instanceof TileChargingStation) return new ContainerChargingStation(player.inventory, (TileChargingStation) tile); case KINETIC_MULTI_TOOL: if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemKineticMultiTool) return new ContainerKineticMultiTool(player.inventory, new InventoryKineticMultiTool(player.getHeldItem())); case PORTABLE_LASER: if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemPortableLaser) return new ContainerPortableLaser(player.inventory, new InventoryPortableLaser(player.getHeldItem())); case HEATED_FURNACE: if (tile instanceof TileHeatedFurnace) return new ContainerHeatedFurnace(player.inventory, (TileHeatedFurnace) tile); case BASIC_COIL: if (tile instanceof TileBasicCoil) return new ContainerBasicCoil(player.inventory, (TileBasicCoil) tile); case KEB: if (tile instanceof TileKineticEnergyBufferBase) return new ContainerKEB(player, (TileKineticEnergyBufferBase) tile); case MACHINE_CONFIGURATOR: return new ContainerMachineConfigurator(player.inventory, tile); case REFINERY:
return new ContainerRefinery(player.inventory, (TileRefinery) tile);
3
Azure/azure-storage-android
microsoft-azure-storage/src/com/microsoft/azure/storage/table/TableOperation.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 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 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.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import com.fasterxml.jackson.core.JsonParseException; import com.microsoft.azure.storage.Constants; import com.microsoft.azure.storage.OperationContext; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.StorageExtendedErrorInformation; import com.microsoft.azure.storage.core.ExecutionEngine; import com.microsoft.azure.storage.core.SR; import com.microsoft.azure.storage.core.StorageRequest; import com.microsoft.azure.storage.core.Utility;
/** * 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.table; /** * A class which represents a single table operation. * <p> * Use the static factory methods to construct {@link TableOperation} instances for operations on tables that insert, * update, merge, delete, replace or retrieve table entities. To execute a {@link TableOperation} instance, call the * <code>execute</code> method on a {@link CloudTableClient} instance. A {@link TableOperation} may be executed directly * or as part of a {@link TableBatchOperation}. If a {@link TableOperation} returns an entity result, it is stored in * the corresponding {@link TableResult} returned by the <code>execute</code> method. * */ public class TableOperation { /** * A static factory method returning a {@link TableOperation} instance to delete the specified entity from Microsoft * Azure storage. To execute this {@link TableOperation} on a given table, call the * {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @return * A new {@link TableOperation} instance to insert the table entity. */ public static TableOperation delete(final TableEntity entity) { Utility.assertNotNull("entity", entity); Utility.assertNotNullOrEmpty("entity etag", entity.getEtag()); return new TableOperation(entity, TableOperationType.DELETE); } /** * A static factory method returning a {@link TableOperation} instance to insert the specified entity into * Microsoft Azure storage. To execute this {@link TableOperation} on a given table, call the * {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @return * A new {@link TableOperation} instance to insert the table entity. */ public static TableOperation insert(final TableEntity entity) { return insert(entity, false); } /** * A static factory method returning a {@link TableOperation} instance to insert the specified entity into * Microsoft Azure storage. To execute this {@link TableOperation} on a given table, call the * {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @param echoContent * The boolean representing whether the message payload should be returned in the response. * @return * A new {@link TableOperation} instance to insert the table entity. */ public static TableOperation insert(final TableEntity entity, boolean echoContent) { Utility.assertNotNull("entity", entity); return new TableOperation(entity, TableOperationType.INSERT, echoContent); } /** * A static factory method returning a {@link TableOperation} instance to merge the specified entity into * Microsoft Azure storage, or insert it if it does not exist. To execute this {@link TableOperation} on a given * table, call * the {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with * the table name and the {@link TableOperation} as arguments. * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @return * A new {@link TableOperation} instance for inserting or merging the table entity. */ public static TableOperation insertOrMerge(final TableEntity entity) { Utility.assertNotNull("entity", entity); return new TableOperation(entity, TableOperationType.INSERT_OR_MERGE); } /** * A static factory method returning a {@link TableOperation} instance to replace the specified entity in * Microsoft Azure storage, or insert it if it does not exist. To execute this {@link TableOperation} on a given * table, call * the {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with * the table name and the {@link TableOperation} as arguments. * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @return * A new {@link TableOperation} instance for inserting or replacing the table entity. */ public static TableOperation insertOrReplace(final TableEntity entity) { Utility.assertNotNull("entity", entity); return new TableOperation(entity, TableOperationType.INSERT_OR_REPLACE); } /** * A static factory method returning a {@link TableOperation} instance to merge the specified table entity into * Microsoft Azure storage. To execute this {@link TableOperation} on a given table, call the * {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @return * A new {@link TableOperation} instance for merging the table entity. */ public static TableOperation merge(final TableEntity entity) { Utility.assertNotNull("entity", entity); Utility.assertNotNullOrEmpty("entity etag", entity.getEtag()); return new TableOperation(entity, TableOperationType.MERGE); } /** * A static factory method returning a {@link TableOperation} instance to retrieve the specified table entity and * return it as the specified type. To execute this {@link TableOperation} on a given table, call the * {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance with the * * @param partitionKey * A <code>String</code> which specifies the PartitionKey value for the entity to retrieve. * @param rowKey * A <code>String</code> which specifies the RowKey value for the entity to retrieve. * @param clazzType * The class type of the table entity object to retrieve. * @return * A new {@link TableOperation} instance for retrieving the table entity. */ public static TableOperation retrieve(final String partitionKey, final String rowKey, final Class<? extends TableEntity> clazzType) { final QueryTableOperation retOp = new QueryTableOperation(partitionKey, rowKey); retOp.setClazzType(clazzType); return retOp; } /** * A static factory method returning a {@link TableOperation} instance to retrieve the specified table entity and * return a projection of it using the specified resolver. To execute this {@link TableOperation} on a given table, * call the {@link CloudTable#execute(TableOperation)} method on a {@link CloudTableClient} instance * with the table name and the {@link TableOperation} as arguments. * * @param partitionKey * A <code>String</code> which specifies the PartitionKey value for the entity to retrieve. * @param rowKey * A <code>String</code> which specifies the RowKey value for the entity to retrieve. * @param resolver * The implementation of {@link EntityResolver} to use to project the result entity as type T. * @return * A new {@link TableOperation} instance for retrieving the table entity. */ public static TableOperation retrieve(final String partitionKey, final String rowKey, final EntityResolver<?> resolver) { final QueryTableOperation retOp = new QueryTableOperation(partitionKey, rowKey); retOp.setResolver(resolver); return retOp; } /** * A static factory method returning a {@link TableOperation} instance to replace the specified table entity. To * execute this {@link TableOperation} on a given table, call the * {@link CloudTable#execute(TableOperation)} method. * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @return * A new {@link TableOperation} instance for replacing the table entity. */ public static TableOperation replace(final TableEntity entity) { Utility.assertNotNullOrEmpty("entity etag", entity.getEtag()); return new TableOperation(entity, TableOperationType.REPLACE); } /** * The table entity instance associated with the operation. */ private TableEntity entity; /** * The {@link TableOperationType} enumeration value for the operation type. */ private TableOperationType opType = null; /** * The value that represents whether the message payload should be returned in the response. */ private boolean echoContent; /** * Nullary Default Constructor. */ protected TableOperation() { // Empty constructor. } /** * Reserved for internal use. Constructs a {@link TableOperation} with the specified table entity and operation * type. * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @param opType * The {@link TableOperationType} enumeration value for the operation type. */ protected TableOperation(final TableEntity entity, final TableOperationType opType) { this(entity, opType, false); } /** * Reserved for internal use. Constructs a {@link TableOperation} with the specified table entity and operation * type. * * @param entity * The object instance implementing {@link TableEntity} to associate with the operation. * @param opType * The {@link TableOperationType} enumeration value for the operation type. * @param echoContent * The boolean representing whether the message payload should be returned in the response. */ protected TableOperation(final TableEntity entity, final TableOperationType opType, final boolean echoContent) { this.entity = entity; this.opType = opType; this.echoContent = echoContent; } /** * Reserved for internal use. Performs a delete operation on the specified table, using the specified * {@link TableRequestOptions} and {@link OperationContext}. * <p> * This method will invoke the <a href="http://msdn.microsoft.com/en-us/library/azure/dd135727.aspx">Delete * Entity</a> REST API to execute this table operation, using the Table service endpoint and storage account * credentials in the {@link CloudTableClient} object. * * @param client * A {@link CloudTableClient} instance specifying the Table service endpoint, storage account * credentials, and any additional query parameters. * @param tableName * A <code>String</code> which specifies the name of the table. * @param options * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout * settings for the operation. * @param opContext * An {@link OperationContext} object for tracking the current operation. * * @return * A {@link TableResult} which represents the results of executing the operation. * * @throws StorageException * if an error occurs in the storage operation. */ private TableResult performDelete(final CloudTableClient client, final String tableName,
final TableRequestOptions options, final OperationContext opContext) throws StorageException {
1