answer
stringlengths
17
10.2M
package com.continuuity; import ch.qos.logback.classic.Logger; import com.continuuity.app.guice.BigMamaModule; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.service.ServerException; import com.continuuity.common.utils.Copyright; import com.continuuity.common.utils.PortDetector; import com.continuuity.common.zookeeper.InMemoryZookeeper; import com.continuuity.data.runtime.DataFabricLevelDBModule; import com.continuuity.data.runtime.DataFabricModules; import com.continuuity.gateway.Gateway; import com.continuuity.gateway.runtime.GatewayModules; import com.continuuity.internal.app.services.AppFabricServer; import com.continuuity.metadata.MetadataServerInterface; import com.continuuity.metrics2.collector.MetricsCollectionServerInterface; import com.continuuity.metrics2.frontend.MetricsFrontendServerInterface; import com.continuuity.runtime.MetadataModules; import com.continuuity.runtime.MetricsModules; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.Service; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import org.apache.commons.lang.StringUtils; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.util.concurrent.TimeUnit; /** * Singlenode Main * NOTE: Use AbstractIdleService */ public class SingleNodeMain { private InMemoryZookeeper zookeeper; private final WebCloudAppService webCloudAppService; private Gateway gateway; private MetricsCollectionServerInterface overlordCollection; private MetricsFrontendServerInterface overloadFrontend; private MetadataServerInterface metaDataServer; private AppFabricServer appFabricServer; private static final String ZOOKEEPER_DATA_DIR = "data/zookeeper"; private final CConfiguration configuration; private final ImmutableList<Module> modules; public SingleNodeMain(ImmutableList<Module> modules, CConfiguration configuration) { this.modules = modules; this.configuration = configuration; this.webCloudAppService = new WebCloudAppService(); Injector injector = Guice.createInjector(modules); gateway = injector.getInstance(Gateway.class); overlordCollection = injector.getInstance(MetricsCollectionServerInterface.class); overloadFrontend = injector.getInstance(MetricsFrontendServerInterface.class); metaDataServer = injector.getInstance(MetadataServerInterface.class); appFabricServer = injector.getInstance(AppFabricServer.class); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { webCloudAppService.stop(true); } catch (ServerException e) { System.err.println("Failed to shutdown node web cloud app"); } } }); } /** * Start the service. */ protected void startUp(String[] args) throws Exception { // Create temporary directory where zookeeper data files will be stored. File temporaryDir = new File(ZOOKEEPER_DATA_DIR); temporaryDir.mkdir(); int port = PortDetector.findFreePort(); zookeeper = new InMemoryZookeeper(port, temporaryDir); configuration.set(Constants.CFG_ZOOKEEPER_ENSEMBLE, zookeeper.getConnectionString()); // Start all the services. Service.State state = appFabricServer.startAndWait(); if(state != Service.State.RUNNING) { throw new Exception("Unable to start Application Fabric."); } metaDataServer.start(args, configuration); overlordCollection.start(args, configuration); overloadFrontend.start(args, configuration); gateway.start(args, configuration); webCloudAppService.start(args, configuration); String hostname = InetAddress.getLocalHost().getHostName(); System.out.println("Continuuity Devsuite AppFabric started successfully. Connect to dashboard at " + "http://" + hostname + ":9999"); } /** * Shutdown the service. */ public void shutDown() { try { webCloudAppService.stop(true); gateway.stop(true); metaDataServer.stop(true); overloadFrontend.stop(true); overlordCollection.stop(true); metaDataServer.stop(true); appFabricServer.startAndWait(); } catch (ServerException e) { // There is nothing we can do. } } static void usage(boolean error) { // Which output stream should we use? PrintStream out = (error ? System.err : System.out); // And our requirements and usage out.println("Requirements: "); out.println(" Java: JDK 1.6+ must be installed and JAVA_HOME environment variable set to the java executable"); out.println(" Node.js: Node.js must be installed (obtain from http://nodejs.org/#download). "); out.println(" The \"node\" executable must be in the system $PATH environment variable"); out.println(""); out.println("Usage: "); out.println(" ./continuuity-app-fabric [options]"); out.println(""); out.println("Additional options:"); out.println(" --help To print this message"); out.println(" --in-memory To run everything in memory"); out.println(""); if (error) { throw new IllegalArgumentException(); } } /** * Checks if node is in path or no. * @return */ public static boolean nodeExists() { try { Process proc = Runtime.getRuntime().exec("node -v"); TimeUnit.SECONDS.sleep(2); int exitValue = proc.exitValue(); if(exitValue != 0) { return false; } } catch (IOException e) { throw new RuntimeException("Nodejs not in path. Please add it to PATH in the shell you are starting devsuite"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return true; } /** * The root of all goodness! * * @param args Our cmdline arguments */ public static void main(String[] args) { Copyright.print(System.out); // Checks if node exists. try { if(! nodeExists()) { System.err.println("Unable to find nodejs in path. Please add it to PATH."); } } catch (Exception e) { System.err.println(e.getMessage()); System.exit(-1); } boolean inMemory = false; // We only support 'help' command line options currently if (args.length > 0) { if ("--help".equals(args[0]) || "-h".equals(args[0])) { usage(false); return; } else if ("--in-memory".equals(args[0])) { inMemory = true; } else { usage(true); } } CConfiguration configuration = CConfiguration.create(); boolean inVPC = false; String environment = configuration.get("appfabric.environment", "devsuite"); if(environment.equals("vpc")) { inVPC = true; } ImmutableList<Module> inMemoryModules = ImmutableList.of( new BigMamaModule(configuration), new MetricsModules().getInMemoryModules(), new GatewayModules().getInMemoryModules(), new DataFabricModules().getInMemoryModules(), new MetadataModules().getInMemoryModules() ); ImmutableList<Module> singleNodeModules = ImmutableList.of( new BigMamaModule(configuration), new MetricsModules().getSingleNodeModules(), new GatewayModules().getSingleNodeModules(), inVPC ? new DataFabricLevelDBModule() : new DataFabricModules().getSingleNodeModules(), new MetadataModules().getSingleNodeModules() ); SingleNodeMain main = inMemory ? new SingleNodeMain(inMemoryModules, configuration) : new SingleNodeMain(singleNodeModules, configuration); try { main.startUp(args); } catch (Exception e) { main.shutDown(); System.err.println("Failed to start server. " + e.getMessage()); System.exit(-2); } } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.List; /** * 216. Combination Sum III * * Find all possible combinations of k numbers that add up to a number n, * given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Example 1: Input: k = 3, n = 7 Output: [[1,2,4]] Example 2: Input: k = 3, n = 9 Output: [[1,2,6], [1,3,5], [2,3,4]]*/ public class _216 { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> result = new ArrayList(); int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; backtracking(k, n, nums, 0, new ArrayList(), result); return result; } void backtracking(int k, int n, int[] nums, int start, List<Integer> curr, List<List<Integer>> result) { if (n > 0) { for (int i = start; i < nums.length; i++) { curr.add(nums[i]); /** it needs to be a unique set of numbers, so we need to set it as i+1 here: each number is used only once in this array: [1,2,3,4,5,6,7,8,9]*/ backtracking(k, n - nums[i], nums, i + 1, curr, result); curr.remove(curr.size() - 1); } } else if (n == 0 && curr.size() == k) { //this is the major difference here: check size of curr list is of k before adding it result.add(new ArrayList(curr)); } } }
package com.fishercoder.solutions; import com.fishercoder.common.classes.ListNode; import java.util.ArrayList; import java.util.List; /** * 234. Palindrome Linked List * * Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space? */ public class _234 { public static class Solution1 { /**O(n) time * O(1) space * */ public boolean isPalindrome(ListNode head) { if (head == null) { return true; } ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } ListNode reversedHead = reverse(slow.next); ListNode firstHalfHead = head; while (firstHalfHead != null && reversedHead != null) { if (firstHalfHead.val != reversedHead.val) { return false; } firstHalfHead = firstHalfHead.next; reversedHead = reversedHead.next; } return true; } private ListNode reverse(ListNode head) { ListNode pre = null; while (head != null) { ListNode next = head.next; head.next = pre; pre = head; head = next; } return pre; } } public static class Solution2 { /**O(n) time * O(n) space * */ public boolean isPalindrome(ListNode head) { int len = 0; ListNode fast = head; ListNode slow = head; List<Integer> firstHalf = new ArrayList<>(); while (fast != null && fast.next != null) { fast = fast.next.next; firstHalf.add(slow.val); slow = slow.next; len += 2; } if (fast != null) { len++; } if (len % 2 != 0) { slow = slow.next; } int i = firstHalf.size() - 1; while (slow != null) { if (firstHalf.get(i--) != slow.val) { return false; } slow = slow.next; } return true; } } }
package com.fishercoder.solutions; import java.util.LinkedList; import java.util.Queue; /** * You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. For example, given the 2D grid: INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF After running your function, the 2D grid should be: 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 */ public class _286 { public static class Solution1 { int[] dirs = new int[]{0, 1, 0, -1, 0}; public void wallsAndGates(int[][] rooms) { if (rooms == null || rooms.length == 0 || rooms[0].length == 0) { return; } int m = rooms.length; int n = rooms[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (rooms[i][j] == 0) { bfs(rooms, i, j, m, n); } } } } void bfs(int[][] rooms, int i, int j, int m, int n) { for (int k = 0; k < 4; k++) { int x = dirs[k] + i; int y = dirs[k + 1] + j; if (x >= 0 && y >= 0 && x < m && y < n && rooms[x][y] > rooms[i][j] + 1) { rooms[x][y] = rooms[i][j] + 1; bfs(rooms, x, y, m, n); } } } } public static class Solution2 { //push all gates into the queue first, and then put all its neighbours into the queue with one distance to the gate, then continue to push the rest of the nodes into the queue, and put all their neighbours into the queue with the nodes' value plus one until the queue is empty int[] dirs = new int[]{0, 1, 0, -1, 0}; public void wallsAndGates(int[][] rooms) { if (rooms == null || rooms.length == 0 || rooms[0].length == 0) { return; } int m = rooms.length; int n = rooms[0].length; Queue<int[]> queue = new LinkedList(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (rooms[i][j] == 0) { queue.offer(new int[]{i, j}); } } } while (!queue.isEmpty()) { int[] curr = queue.poll(); for (int k = 0; k < 4; k++) { int x = curr[0] + dirs[k]; int y = curr[1] + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && rooms[x][y] == Integer.MAX_VALUE) { rooms[x][y] = rooms[curr[0]][curr[1]] + 1; queue.offer(new int[]{x, y}); } } } } } }
package com.fishercoder.solutions; public class _322 { public static class Solution1 { public int coinChange(int[] coins, int amount) { if (amount < 1) { return 0; } return coinChange(coins, amount, new int[amount]); } private int coinChange(int[] coins, int rem, int[] count) { if (rem < 0) { return -1; } if (rem == 0) { return 0; } if (count[rem - 1] != 0) { return count[rem - 1]; } int min = Integer.MAX_VALUE; for (int coin : coins) { int res = coinChange(coins, rem - coin, count); if (res >= 0 && res < min) { min = 1 + res; } } count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min; return count[rem - 1]; } } }
package com.fishercoder.solutions; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Random; public class _380 { public static class Solution1 { public static class RandomizedSet { Map<Integer, Integer> map; List<Integer> list; Random random; public RandomizedSet() { map = new HashMap<>(); random = new Random(); list = new ArrayList<>(); } public boolean insert(int val) { if (map.containsKey(val)) { return false; } map.put(val, list.size()); list.add(list.size(), val); return true; } public boolean remove(int val) { if (!map.containsKey(val)) { return false; } else { int lastElement = list.get(list.size() - 1); int index = map.get(val); list.set(index, lastElement); map.put(lastElement, index); list.remove(list.size() - 1); map.remove(val); return true; } } public int getRandom() { return list.get(random.nextInt(list.size())); } } } }
package com.fishercoder.solutions; public class _405 { public static class Solution1 { public String toHex(int num) { char[] hexChars = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; String result = ""; while (num != 0) { result = hexChars[(num & 15)] + result; num >>>= 4; } return result.isEmpty() ? "0" : result; } } }
package com.fishercoder.solutions; import java.util.Deque; import java.util.LinkedList; /** * 456. 132 Pattern * * Given a sequence of n integers a1, a2, ..., an, * a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. * Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list. Note: n will be less than 15,000. Example 1: Input: [1, 2, 3, 4] Output: False Explanation: There is no 132 pattern in the sequence. Example 2: Input: [3, 1, 4, 2] Output: True Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. Example 3: Input: [-1, 3, 2, 0] Output: True Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. */ public class _456 { public static boolean find132pattern(int[] nums) { Deque<Integer> stack = new LinkedList<>(); int s3 = Integer.MIN_VALUE; for (int i = nums.length-1; i >= 0; i if (nums[i] < s3) return true; else { while (!stack.isEmpty() && nums[i] > stack.peek()){ s3 = Math.max(s3, stack.pop()); } } stack.push(nums[i]); } return false; } public static void main (String...args){ int[] nums = new int[]{-1, 3, 2, 0}; System.out.println(find132pattern(nums)); } }
package com.fishercoder.solutions; import com.fishercoder.common.classes.TreeNode; /** * 687. Longest Univalue Path * * Given a binary tree, find the length of the longest path where each node in the path has the same value. * This path may or may not pass through the root. Note: The length of path between two nodes is represented by the number of edges between them. Example 1: Input: 5 / \ 4 5 / \ \ 1 1 5 Output: 2 Example 2: Input: 1 / \ 4 5 / \ \ 4 4 5 Output: 2 Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000. */ public class _687 { public static class Solution1 { /** * Use a one element array to pass in and out is a common technique for handling tree questions. */ public int longestUnivaluePath(TreeNode root) { int[] result = new int[1]; if (root != null) { dfs(root, result); } return result[0]; } private int dfs(TreeNode root, int[] result) { int leftPath = root.left == null ? 0 : dfs(root.left, result); int rightPath = root.right == null ? 0 : dfs(root.right, result); int leftResult = (root.left != null && root.left.val == root.val) ? leftPath + 1 : 0; int rightResult = (root.right != null && root.right.val == root.val) ? rightPath + 1 : 0; result[0] = Math.max(result[0], leftResult + rightResult); return Math.max(leftResult, rightResult); } } }
package com.github.andriell.gui; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import java.awt.*; public class Colors { public static Color[] colors; public static CompoundBorder[] borders; public static Border emptyBorder; private static int position = 0; static { colors = new Color[27]; borders = new CompoundBorder[colors.length]; emptyBorder = BorderFactory.createEmptyBorder(4, 4, 4, 4); int i = 0; for (int r = 64; r < 256; r += 64) { for (int g = 64; g < 256; g += 64) { for (int b = 64; b < 256; b += 64) { colors[i] = new Color(r, g, b); borders[i] = BorderFactory.createCompoundBorder(emptyBorder, BorderFactory.createLineBorder(colors[i], 2)); i++; } } } } public static Color nextColor() { position++; if (position >= colors.length) { position = 0; } return colors[position]; } public static CompoundBorder nextBorder() { position++; if (position >= borders.length) { position = 0; } return borders[position]; } }
package com.ht.scada.oildata; import com.ht.scada.common.tag.entity.EndTag; import com.ht.scada.common.tag.service.EndTagService; import com.ht.scada.common.tag.util.CommonUtils; import com.ht.scada.common.tag.util.EndTagTypeEnum; import com.ht.scada.common.tag.util.RedisKeysEnum; import com.ht.scada.common.tag.util.VarSubTypeEnum; import com.ht.scada.data.service.RealtimeDataService; import com.ht.scada.oildata.entity.WetkSGT; import com.ht.scada.oildata.service.ReportService; import com.ht.scada.oildata.service.WellService; import com.ht.scada.oildata.service.WetkSGTService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * * @author */ @Component public class Scheduler { //@Autowired //@Qualifier("scheduledService1") //private ScheduledService scheduledService; @Autowired private EndTagService endTagService; @Autowired private ReportService reportService; @Autowired private RealtimeDataService realtimeDataService; @Autowired private WellService wellService; @Autowired private WetkSGTService wetkSGTService; private int interval = 20; //@Scheduled(cron = "30 0 0 * * ? ") @Scheduled(cron="0 0/30 * * * ? ") public void hourlyTask() { //List<EndTag> oilWellList = endTagService.getByType(EndTagTypeEnum.YOU_JING.toString()); //if (oilWellList != null && !oilWellList.isEmpty()) { // for (EndTag endTag : oilWellList) { // OilWellHourlyDataRecord oilWellHourlyDataRecord = scheduledService.getOilWellHourlyDataRecordByCode(endTag.getCode(), interval, new Date()); // reportService.insertOilWellHourlyDataRecord(oilWellHourlyDataRecord); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); //List<EndTag> waterList = endTagService.getByType(EndTagTypeEnum.SHUI_YUAN_JING.toString()); //if (waterList != null && !waterList.isEmpty()) { // for (EndTag endTag : waterList) { // WaterWellHourlyDataRecord record = scheduledService.getWaterWellHourlyDataRecordByCode(endTag.getCode(), interval, new Date()); // reportService.insertWaterWellHourlyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); //String trqType = EndTagTypeEnum.TIAN_RAN_QI_JING.toString(); //List<EndTag> gasList = endTagService.getByType(trqType); //if (gasList != null && !gasList.isEmpty()) { // for (EndTag endTag : gasList) { // GasWellHourlyDataRecord record = scheduledService.getGasWellHourlyDataRecordByCode(endTag.getCode(), interval, new Date()); // reportService.insertGasWellHourlyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); //List<EndTag> zhuShuiList = endTagService.getByType(EndTagTypeEnum.ZHU_SHUI_ZHAN.toString()); //if (zhuShuiList != null && !zhuShuiList.isEmpty()) { // for (EndTag endTag : zhuShuiList) { // ZhuShuiHourlyDataRecord record = scheduledService.getZhuShuiHourlyDataRecordByCode(endTag.getCode(), interval, new Date()); // reportService.insertZhuShuiHourlyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); //List<EndTag> zhuQiList = endTagService.getByType(EndTagTypeEnum.ZHU_QI_ZHAN.toString()); //if (zhuQiList != null && !zhuQiList.isEmpty()) { // for (EndTag endTag : zhuQiList) { // ZhuQiHourlyDataRecord record = scheduledService.getZhuQiHourlyDataRecordByCode(endTag.getCode(), interval, new Date()); // reportService.insertZhuQiHourlyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // id(32) String gtId; float CC; float CC1; float ZDZH; float ZXZH; Map<String, String> dateMap = new HashMap<String, String>(); List<EndTag> youJingList = endTagService.getByType(EndTagTypeEnum.YOU_JING.toString()); if (youJingList != null && youJingList.size() > 0) { for (EndTag youJing : youJingList) { String code = youJing.getCode(); if (getDianYCData(code, VarSubTypeEnum.ZUI_DA_ZAI_HE.toString().toLowerCase()) > 0) { String newDateTime = realtimeDataService.getEndTagVarInfo(code, RedisKeysEnum.GT_DATETIME.toString()); if (dateMap.get(code) != null && dateMap.get(code).equals(newDateTime)) { return; } dateMap.put(code, newDateTime); WetkSGT wetkSGT = new WetkSGT(); gtId = CommonUtils.getCode(); CC = getDianYCData(code, VarSubTypeEnum.CHONG_CHENG.toString().toLowerCase()); CC1 = getDianYCData(code, VarSubTypeEnum.CHONG_CI.toString().toLowerCase()); ZDZH = getDianYCData(code, VarSubTypeEnum.ZUI_DA_ZAI_HE.toString().toLowerCase()); ZXZH = getDianYCData(code, VarSubTypeEnum.ZUI_XIAO_ZAI_HE.toString().toLowerCase()); wetkSGT.setID(gtId); wetkSGT.setJH(code); String dateTime = realtimeDataService.getEndTagVarInfo(code, RedisKeysEnum.GT_DATETIME.toString()); if (dateTime != null){ wetkSGT.setCJSJ(CommonUtils.string2Date(dateTime)); }else { wetkSGT.setCJSJ(new Date()); } wetkSGT.setCC(CC); wetkSGT.setCC1(CC1); wetkSGT.setSXCC1(getDianYCData(code, VarSubTypeEnum.CHONG_CI.toString().toLowerCase())); //todo wetkSGT.setXXCC1(getDianYCData(code, VarSubTypeEnum.CHONG_CI.toString().toLowerCase())); //todo String weiyi = realtimeDataService.getEndTagVarYcArray(code, VarSubTypeEnum.WEI_YI_ARRAY.toString().toLowerCase()); weiyi = CommonUtils.string2String(weiyi, 3); wetkSGT.setWY(weiyi); wetkSGT.setZH(CommonUtils.string2String(realtimeDataService.getEndTagVarYcArray(code, VarSubTypeEnum.ZAI_HE_ARRAY.toString().toLowerCase()), 3)); wetkSGT.setGL(CommonUtils.string2String(realtimeDataService.getEndTagVarYcArray(code, VarSubTypeEnum.GONG_LV_ARRAY.toString().toLowerCase()), 3)); wetkSGT.setDL(CommonUtils.string2String(realtimeDataService.getEndTagVarYcArray(code, VarSubTypeEnum.DIAN_LIU_ARRAY.toString().toLowerCase()), 3)); wetkSGT.setBPQSCGL(CommonUtils.string2String(realtimeDataService.getEndTagVarYcArray(code, VarSubTypeEnum.GONG_LV_YIN_SHU_ARRAY.toString().toLowerCase()), 3)); wetkSGT.setZJ(CommonUtils.string2String(realtimeDataService.getEndTagVarYcArray(code, VarSubTypeEnum.DIAN_GONG_TU_ARRAY.toString().toLowerCase()), 3)); wetkSGT.setZDZH(ZDZH); wetkSGT.setZXZH(ZXZH); wetkSGT.setBZGT(null); wetkSGT.setGLYS(getDianYCData(code, VarSubTypeEnum.GV_GLYS.toString().toLowerCase())); wetkSGT.setYGGL(getDianYCData(code, VarSubTypeEnum.GV_YG.toString().toLowerCase())); wetkSGT.setWGGL(getDianYCData(code, VarSubTypeEnum.GV_WG.toString().toLowerCase())); wetkSGTService.addOneRecord(wetkSGT); //Map<String, Object> gtfxMap = new HashMap<>(); //gtfxMap.put("JH", code); if (dateTime != null){ //gtfxMap.put("CJSJ", CommonUtils.string2Date(dateTime)); wetkSGTService.addOneGTFXRecord(gtId,code,CommonUtils.string2Date(dateTime),CC,CC1,ZDZH,ZXZH); }else { //gtfxMap.put("CJSJ", new Date()); wetkSGTService.addOneGTFXRecord(gtId,code,new Date(),CC,CC1,ZDZH,ZXZH); } //gtfxMap.put("GTID", gtId); //gtfxMap.put("CC", CC); //gtfxMap.put("CC1", CC1); //gtfxMap.put("ZDZH", ZDZH); //gtfxMap.put("ZXZH", ZXZH); } } } System.out.println("" + CommonUtils.date2String(new Date())); } /** * * @param code * @param varName * @return */ private float getDianYCData(String code, String varName) { String value = realtimeDataService.getEndTagVarInfo(code, varName); if (value != null && !value.isEmpty()) { return CommonUtils.string2Float(value, 4); } else { return 0; } } ////@Scheduled(cron = "5 0 0 * * ? ") //public void dailyTask() { // List<EndTag> oilWellList = endTagService.getByType(EndTagTypeEnum.YOU_JING.toString()); // if (oilWellList != null && !oilWellList.isEmpty()) { // for (EndTag endTag : oilWellList) { // OilWellDailyDataRecord oilWellDailyDataRecord = scheduledService.getYesterdayOilWellDailyDataRecordByCode(endTag.getCode()); // reportService.insertOilWellDailyDataRecord(oilWellDailyDataRecord); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> waterWellList = endTagService.getByType(EndTagTypeEnum.SHUI_YUAN_JING.toString()); // if (waterWellList != null && !waterWellList.isEmpty()) { // for (EndTag endTag : waterWellList) { // WaterWellDailyDataRecord record = scheduledService.getYesterdayWaterWellDailyDataRecordByCode(endTag.getCode()); // reportService.insertWaterWellDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> gasWellList = endTagService.getByType(EndTagTypeEnum.TIAN_RAN_QI_JING.toString()); // if (gasWellList != null && !gasWellList.isEmpty()) { // for (EndTag endTag : gasWellList) { // GasWellDailyDataRecord record = scheduledService.getYesterdayGasWellDailyDataRecordByCode(endTag.getCode()); // reportService.insertGasWellDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> zyzList = endTagService.getByType(EndTagTypeEnum.ZENG_YA_ZHAN.toString()); // if (zyzList != null && !zyzList.isEmpty()) { // for (EndTag endTag : zyzList) { // ZengYaZhanDailyDataRecord record = scheduledService.getYesterdayZengYaZhanDailyDataRecordByCode(endTag.getCode()); // reportService.insertZengYaZhanDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> zszList = endTagService.getByType(EndTagTypeEnum.ZHU_SHUI_ZHAN.toString()); // if (zszList != null && !zszList.isEmpty()) { // for (EndTag endTag : zszList) { // ZhuShuiDailyDataRecord record = scheduledService.getYesterdayZhuShuiDailyDataRecordByCode(endTag.getCode()); // reportService.insertZhuShuiDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> zqzList = endTagService.getByType(EndTagTypeEnum.ZHU_QI_ZHAN.toString()); // if (zqzList != null && !zqzList.isEmpty()) { // for (EndTag endTag : zqzList) { // ZhuQiDailyDataRecord record = scheduledService.getYesterdayZhuQiDailyDataRecordByCode(endTag.getCode()); // reportService.insertZhuQiDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); ///** // * SCY_SGT_GTCJ // */ //public void dailyTask2() { // List<EndTag> oilWellList = endTagService.getByType(EndTagTypeEnum.YOU_JING.toString()); // if (oilWellList != null && !oilWellList.isEmpty()) { // for (EndTag endTag : oilWellList) { // OilWellDailyDataRecord oilWellDailyDataRecord = scheduledService.getYesterdayOilWellDailyDataRecordByCode(endTag.getCode()); // reportService.insertOilWellDailyDataRecord(oilWellDailyDataRecord); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> waterWellList = endTagService.getByType(EndTagTypeEnum.SHUI_YUAN_JING.toString()); // if (waterWellList != null && !waterWellList.isEmpty()) { // for (EndTag endTag : waterWellList) { // WaterWellDailyDataRecord record = scheduledService.getYesterdayWaterWellDailyDataRecordByCode(endTag.getCode()); // reportService.insertWaterWellDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> gasWellList = endTagService.getByType(EndTagTypeEnum.TIAN_RAN_QI_JING.toString()); // if (gasWellList != null && !gasWellList.isEmpty()) { // for (EndTag endTag : gasWellList) { // GasWellDailyDataRecord record = scheduledService.getYesterdayGasWellDailyDataRecordByCode(endTag.getCode()); // reportService.insertGasWellDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> zyzList = endTagService.getByType(EndTagTypeEnum.ZENG_YA_ZHAN.toString()); // if (zyzList != null && !zyzList.isEmpty()) { // for (EndTag endTag : zyzList) { // ZengYaZhanDailyDataRecord record = scheduledService.getYesterdayZengYaZhanDailyDataRecordByCode(endTag.getCode()); // reportService.insertZengYaZhanDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> zszList = endTagService.getByType(EndTagTypeEnum.ZHU_SHUI_ZHAN.toString()); // if (zszList != null && !zszList.isEmpty()) { // for (EndTag endTag : zszList) { // ZhuShuiDailyDataRecord record = scheduledService.getYesterdayZhuShuiDailyDataRecordByCode(endTag.getCode()); // reportService.insertZhuShuiDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); // List<EndTag> zqzList = endTagService.getByType(EndTagTypeEnum.ZHU_QI_ZHAN.toString()); // if (zqzList != null && !zqzList.isEmpty()) { // for (EndTag endTag : zqzList) { // ZhuQiDailyDataRecord record = scheduledService.getYesterdayZhuQiDailyDataRecordByCode(endTag.getCode()); // reportService.insertZhuQiDailyDataRecord(record); // System.out.println(new Date().toString() + "" + endTag.getCode() + ""); //@Scheduled(cron = "0 0/1 * * * ? ") //public void testSGT() { // Map<String, String> map = realtimeDataService.getEndTagVarGroupInfo("test_001", VarGroupEnum.YOU_JING_SGT.toString()); // if (map != null) { // TestSGT testSGT = new TestSGT(); // testSGT.setChongCheng(Float.valueOf(map.get(VarSubTypeEnum.CHONG_CHENG.toString().toLowerCase()))); // testSGT.setChongCi(Float.valueOf(map.get(VarSubTypeEnum.CHONG_CI.toString().toLowerCase()))); // testSGT.setChongCiShang(Float.valueOf(map.get(VarSubTypeEnum.SHANG_XING_CHONG_CI.toString().toLowerCase()))); // testSGT.setChongCiXia(Float.valueOf(map.get(VarSubTypeEnum.XIA_XING_CHONG_CI.toString().toLowerCase()))); // testSGT.setMinZaihe(Float.valueOf(map.get(VarSubTypeEnum.ZUI_XIAO_ZAI_HE.toString().toLowerCase()))); // testSGT.setMaxZaihe(Float.valueOf(map.get(VarSubTypeEnum.ZUI_DA_ZAI_HE.toString().toLowerCase()))); // String weiyi = realtimeDataService.getEndTagVarYcArray("test_001", VarSubTypeEnum.WEI_YI_ARRAY.toString().toLowerCase()); // String zaihe = realtimeDataService.getEndTagVarYcArray("test_001", VarSubTypeEnum.ZAI_HE_ARRAY.toString().toLowerCase()); // testSGT.setWeiyi(weiyi); // testSGT.setZaihe(zaihe); // testSGT.setDate(new Date()); // float[] weiyiArray = String2FloatArrayUtil.string2FloatArrayUtil(weiyi, ","); // float[] zaiheArray = String2FloatArrayUtil.string2FloatArrayUtil(zaihe, ","); // float weiyiSum = 0, zaiheSum = 0; // for (float f : weiyiArray) { // weiyiSum += f; // for (float f : zaiheArray) { // zaiheSum += f; // testSGT.setWeiyiSum(weiyiSum); // testSGT.setZaiheSum(zaiheSum); // testSGTDao.save(testSGT); // System.out.println(""); //private void sendFaultData(FaultDiagnoseRecord record) { // String message = JSON.toJSONString(record); // // redisTemplate.convertAndSend("FaultDiagnoseChannel", message); }
package com.jakewharton.u2020; import android.app.Application; import android.support.annotation.NonNull; import com.jakewharton.threetenabp.AndroidThreeTen; import com.jakewharton.u2020.data.Injector; import com.jakewharton.u2020.data.LumberYard; import com.jakewharton.u2020.ui.ActivityHierarchyServer; import com.squareup.leakcanary.LeakCanary; import dagger.ObjectGraph; import javax.inject.Inject; import timber.log.Timber; import static timber.log.Timber.DebugTree; public final class U2020App extends Application { private ObjectGraph objectGraph; @Inject ActivityHierarchyServer activityHierarchyServer; @Inject LumberYard lumberYard; @Override public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { return; } AndroidThreeTen.init(this); LeakCanary.install(this); if (BuildConfig.DEBUG) { Timber.plant(new DebugTree()); } else { // TODO Crashlytics.start(this); // TODO Timber.plant(new CrashlyticsTree()); } objectGraph = ObjectGraph.create(Modules.list(this)); objectGraph.inject(this); lumberYard.cleanUp(); Timber.plant(lumberYard.tree()); registerActivityLifecycleCallbacks(activityHierarchyServer); } @Override public Object getSystemService(@NonNull String name) { if (Injector.matchesService(name)) { return objectGraph; } return super.getSystemService(name); } }
package org.voltdb.iv2; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadFactory; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.CoreUtils; import org.voltdb.BackendTarget; import org.voltdb.CatalogContext; import org.voltdb.LoadedProcedureSet; import org.voltdb.StarvationTracker; /** * Provide a pool of MP Read-only sites to do MP RO work. * This should be owned by the MpTransactionTaskQueue and expects all operations * to be done while holding its lock. */ class MpRoSitePool { final static VoltLogger tmLog = new VoltLogger("TM"); static final int MAX_POOL_SIZE = Integer.getInteger("MPI_READ_POOL_SIZE", 3); static final int INITIAL_POOL_SIZE = 1; class MpRoSiteContext { final private SiteTaskerQueue m_queue; final private MpRoSite m_site; final private CatalogContext m_catalogContext; final private LoadedProcedureSet m_loadedProcedures; final private Thread m_siteThread; MpRoSiteContext(long siteId, BackendTarget backend, CatalogContext context, int partitionId, InitiatorMailbox initiatorMailbox, ThreadFactory threadFactory) { m_catalogContext = context; m_queue = new SiteTaskerQueue(partitionId); // IZZY: Just need something non-null for now m_queue.setStarvationTracker(new StarvationTracker(siteId)); m_queue.setupQueueDepthTracker(siteId); m_site = new MpRoSite(m_queue, siteId, backend, m_catalogContext, partitionId); m_loadedProcedures = new LoadedProcedureSet(m_site); m_loadedProcedures.loadProcedures(m_catalogContext); m_site.setLoadedProcedures(m_loadedProcedures); m_siteThread = threadFactory.newThread(m_site); m_siteThread.start(); } boolean offer(SiteTasker task) { return m_queue.offer(task); } long getCatalogCRC() { return m_catalogContext.getCatalogCRC(); } long getCatalogVersion() { return m_catalogContext.catalogVersion; } void shutdown() { m_site.startShutdown(); // Need to unblock the site's run() loop on the take() call on the queue m_queue.offer(Scheduler.m_nullTask); } void joinThread() { try { m_siteThread.join(); } catch (InterruptedException e) { } } } // Stack of idle MpRoSites private Deque<MpRoSiteContext> m_idleSites = new ArrayDeque<>(); // Active sites, hashed by the txnID they're working on private Map<Long, MpRoSiteContext> m_busySites = new HashMap<>(); //The reference for all sites, used for shutdown private List<MpRoSiteContext> m_allSites = Collections.synchronizedList(new ArrayList<>()); // Stuff we need to construct new MpRoSites private final long m_siteId; private final BackendTarget m_backend; private final int m_partitionId; private final InitiatorMailbox m_initiatorMailbox; private CatalogContext m_catalogContext; private ThreadFactory m_poolThreadFactory; private volatile boolean m_shuttingDown = false; MpRoSitePool( long siteId, BackendTarget backend, CatalogContext context, int partitionId, InitiatorMailbox initiatorMailbox) { m_siteId = siteId; m_backend = backend; m_catalogContext = context; m_partitionId = partitionId; m_initiatorMailbox = initiatorMailbox; m_poolThreadFactory = CoreUtils.getThreadFactory("RO MP Site - " + CoreUtils.hsIdToString(m_siteId), CoreUtils.MEDIUM_STACK_SIZE); tmLog.info("Setting maximum size of MPI read pool to: " + MAX_POOL_SIZE); // Construct the initial pool for (int i = 0; i < INITIAL_POOL_SIZE; i++) { MpRoSiteContext site = new MpRoSiteContext(m_siteId, m_backend, m_catalogContext, m_partitionId, m_initiatorMailbox, m_poolThreadFactory); m_idleSites.push(site); m_allSites.add(site); } } /** * Update the catalog */ void updateCatalog(String diffCmds, CatalogContext context) { if (m_shuttingDown) { return; } m_catalogContext = context; // Wipe out all the idle sites with stale catalogs. // Non-idle sites will get killed and replaced when they finish // whatever they started before the catalog update Iterator<MpRoSiteContext> siterator = m_idleSites.iterator(); while (siterator.hasNext()) { MpRoSiteContext site = siterator.next(); if (site.getCatalogCRC() != m_catalogContext.getCatalogCRC() || site.getCatalogVersion() != m_catalogContext.catalogVersion) { site.shutdown(); m_idleSites.remove(site); m_allSites.remove(site); } } } /** * update cluster settings */ void updateSettings(CatalogContext context) { m_catalogContext = context; } /** * Repair: Submit the provided task to the MpRoSite running the transaction associated * with txnId. This occurs when the MPI has survived a node failure and needs to interrupt and * re-run the current MP transaction; this task is used to run the repair algorithm in the site thread. */ void repair(long txnId, SiteTasker task) { if (m_busySites.containsKey(txnId)) { MpRoSiteContext site = m_busySites.get(txnId); site.offer(task); } else { // Should be impossible throw new RuntimeException("MPI repair attempted to repair transaction: " + txnId); } } /** * Is there a RO site available to do MP RO work? */ boolean canAcceptWork() { //lock down the pool and accept no more work upon shutting down. if (m_shuttingDown) { return false; } return (!m_idleSites.isEmpty() || m_busySites.size() < MAX_POOL_SIZE); } /** * Attempt to start the transaction represented by the given task. Need the txn ID for future reference. * @return true if work was started successfully, false if not. */ boolean doWork(long txnId, TransactionTask task) { boolean retval = canAcceptWork(); if (!retval) { return false; } MpRoSiteContext site; // Repair case if (m_busySites.containsKey(txnId)) { site = m_busySites.get(txnId); } else { if (m_idleSites.isEmpty()) { MpRoSiteContext newSite = new MpRoSiteContext(m_siteId, m_backend, m_catalogContext, m_partitionId, m_initiatorMailbox, m_poolThreadFactory); m_idleSites.push(newSite); m_allSites.add(newSite); } site = m_idleSites.pop(); m_busySites.put(txnId, site); } site.offer(task); return true; } /** * Inform the pool that the work associated with the given txnID is complete */ void completeWork(long txnId) { if (m_shuttingDown) { return; } MpRoSiteContext site = m_busySites.remove(txnId); if (site == null) { throw new RuntimeException("No busy site for txnID: " + txnId + " found, shouldn't happen."); } // check the catalog versions, only push back onto idle if the catalog hasn't changed // otherwise, just let it get garbage collected and let doWork() construct new ones for the // pool with the updated catalog. if (site.getCatalogCRC() == m_catalogContext.getCatalogCRC() && site.getCatalogVersion() == m_catalogContext.catalogVersion) { m_idleSites.push(site); } else { site.shutdown(); m_allSites.remove(site); } } void shutdown() { m_shuttingDown = true; // Shutdown all, then join all, hopefully save some shutdown time for tests. synchronized(m_allSites) { for (MpRoSiteContext site : m_allSites) { site.shutdown(); } for (MpRoSiteContext site : m_allSites) { site.joinThread(); } } } }
package com.platform.common.crypto; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AES { private static final String ALGORITHM = "AES"; private static final String LOCAL_ENCODING = "UTF-8"; public static String encrypt(String content, String authCode) throws Exception { KeyGenerator keyG = KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG","SUN"); secureRandom.setSeed(authCode.getBytes(LOCAL_ENCODING)); keyG.init(128,secureRandom); SecretKey secretKey = keyG.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat,ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(LOCAL_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, key); return byte2Hex(cipher.doFinal(byteContent)); } public static String decrypt(String ciphertext, String authCode) throws Exception { KeyGenerator keyG = KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG","SUN"); secureRandom.setSeed(authCode.getBytes(LOCAL_ENCODING)); keyG.init(128,secureRandom); SecretKey secretKey = keyG.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat,ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(hex2Byte(ciphertext))); } private static String byte2Hex(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private static byte[] hex2Byte(String hexStr) { if (hexStr.length() < 1){ return null; } byte[] result = new byte[hexStr.length()/2]; for (int i = 0;i< hexStr.length()/2; i++) { int high = Integer.parseInt(hexStr.substring(i*2, i*2+1),16); int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2),16); result[i] = (byte)(high * 16 + low); } return result; } }
package com.wizzardo.http; import com.wizzardo.epoll.ByteBufferProvider; import com.wizzardo.epoll.Connection; import com.wizzardo.epoll.EpollCore; import com.wizzardo.epoll.IOThread; import com.wizzardo.epoll.readable.ReadableByteArray; import com.wizzardo.http.mapping.Path; import com.wizzardo.http.request.Header; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import com.wizzardo.http.response.Status; import com.wizzardo.http.utils.AsciiReader; import com.wizzardo.tools.misc.ExceptionDrivenStringBuilder; import com.wizzardo.tools.misc.Unchecked; import com.wizzardo.tools.misc.pool.*; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicReference; public class ProxyHandler implements Handler { protected static final Pool<ExceptionDrivenStringBuilder> BUILDER_POOL = new PoolBuilder<ExceptionDrivenStringBuilder>() .supplier(ExceptionDrivenStringBuilder::new) .resetter(sb -> sb.setLength(0)) .build(); protected Queue<ProxyConnection> connections = new LinkedBlockingQueue<>(); protected EpollCore<ProxyConnection> epoll = new EpollCore<ProxyConnection>() { @Override protected ProxyConnection createConnection(int fd, int ip, int port) { return new ProxyConnection(fd, ip, port); } @Override protected IOThread<ProxyConnection> createIOThread(int number, int divider) { return new IOThread<ProxyConnection>(number, divider) { @Override public void onRead(ProxyConnection connection) { connection.read(this); } }; } }; { epoll.start(); } protected String host; protected int port; public ProxyHandler(String host) { this(host, 80); } public ProxyHandler(String host, int port) { this.host = host; this.port = port; } class ProxyConnection extends Connection { Request srcRequest; Response srcResponse; volatile ResponseReader responseReader; final AtomicReference<Thread> processingBy = new AtomicReference<>(); final byte[] buffer = new byte[16 * 1024]; volatile long limit; public ProxyConnection(int fd, int ip, int port) { super(fd, ip, port); } protected void read(ByteBufferProvider byteBufferProvider) { Thread current = Thread.currentThread(); Thread processing = processingBy.get(); if (processing != current && processing != null) processing = null; if (!processingBy.compareAndSet(processing, current)) return; if (!srcRequest.connection().isAlive()) { processingBy.set(null); end(); return; } try { int r; byte[] buffer = this.buffer; while ((r = read(buffer, byteBufferProvider)) > 0) { int offset = 0; if (!responseReader.isComplete()) { int k = responseReader.read(buffer, 0, r); if (k < 0) continue; srcResponse.headersReset(); for (Map.Entry<String, MultiValue> entry : responseReader.headers.entrySet()) { String name = entry.getKey(); if (entry.getValue().size() > 1) for (String value : entry.getValue().getValues()) { srcResponse.appendHeader(name, value); } else srcResponse.appendHeader(name, entry.getValue().getValue()); } offset = k; MultiValue length = responseReader.getHeaders().get(Header.KEY_CONTENT_LENGTH.value); if (!responseReader.status.equals("200")) srcResponse.setStatus(Status.valueOf(Integer.parseInt(responseReader.getStatus()))); srcResponse.commit(srcRequest.connection()); if (length == null) { processingBy.set(null); end(); return; } limit = Long.valueOf(length.getValue()); } limit -= r - offset; if (limit == 0) proxyWrite(new CustomReadableByteArray(buffer, offset, r - offset), byteBufferProvider); else proxyWrite(new CustomReadableByteArray(Arrays.copyOfRange(buffer, offset, r)), byteBufferProvider); // System.out.println("response: " + new String(buffer, offset, r - offset)); // System.out.println("need to read: " + limit + "; r:" + r + " ,offset:" + offset); if (limit == 0) { processingBy.set(null); end(); return; } break; } } catch (Exception e) { try { close(); } catch (IOException ignored) { } try { srcRequest.connection().close(); } catch (IOException ignored) { } e.printStackTrace(); } // System.out.println("wait "+srcRequest.connection().hasDataToWrite()); processingBy.set(null); } protected void proxyWrite(CustomReadableByteArray readable, ByteBufferProvider bufferProvider) { srcRequest.connection().write(readable, bufferProvider); } protected void end() { if (srcRequest.header(Header.KEY_CONNECTION).equalsIgnoreCase(Header.VALUE_CLOSE.value)) srcRequest.connection().setCloseOnFinishWriting(true); srcRequest.connection().onFinishingHandling(); limit = -1; connections.add(this); } private class CustomReadableByteArray extends ReadableByteArray { public CustomReadableByteArray(byte[] bytes) { super(bytes); } public CustomReadableByteArray(byte[] bytes, int offset, int length) { super(bytes, offset, length); } @Override public void onComplete() { Unchecked.run(() -> ProxyConnection.this.read((ByteBufferProvider) Thread.currentThread())); } } } @Override public Response handle(Request request, Response response) throws IOException { ProxyConnection connection = connections.poll(); if (connection == null || !connection.isAlive()) { // System.out.println("create new connection " + (connection == null ? "" : ", not alive")); connection = epoll.connect(host, port); } connection.srcRequest = request; connection.srcResponse = response; connection.responseReader = new ResponseReader(); final ProxyConnection finalConnection = connection; BUILDER_POOL.provide(requestBuilder -> { requestBuilder.append(request.method().name()) .append(" ").append(sb -> rewritePath(sb, request.path(), request.getQueryString())) .append(" HTTP/1.1\r\n") .append("Host: ").append(host) .append(sb -> { if (port != 80) sb.append(":").append(port); }).append("\r\n") .append("X-Real-IP: ").append(request.connection().getIp()).append("\r\n") .append("X-Forwarded-for: ").append(request.connection().getServer().getHost()).append("\r\n"); Map<String, MultiValue> headers = request.headers(); for (Map.Entry<String, MultiValue> header : headers.entrySet()) { if (header.getKey().equalsIgnoreCase("Host")) continue; if (header.getValue().size() == 1) requestBuilder.append(header.getKey()).append(": ").append(header.getValue().getValue()).append("\r\n"); else for (String value : header.getValue().getValues()) requestBuilder.append(header.getKey()).append(": ").append(value).append("\r\n"); } requestBuilder.append("\r\n"); //todo: post request // System.out.println("send request: " + requestBuilder); finalConnection.write(AsciiReader.write(requestBuilder.toString()), (ByteBufferProvider) Thread.currentThread()); if (request.getBody() != null) finalConnection.write(request.data(), (ByteBufferProvider) Thread.currentThread()); return null; }); response.async(); return response; } public void rewritePath(ExceptionDrivenStringBuilder requestBuilder, Path path, String query) { requestBuilder.append(sb -> path.toString(sb)).append('?').append(query); } }
package com.wizzardo.http; import com.wizzardo.epoll.ByteBufferProvider; import com.wizzardo.epoll.Connection; import com.wizzardo.epoll.EpollCore; import com.wizzardo.epoll.IOThread; import com.wizzardo.epoll.readable.ReadableByteArray; import com.wizzardo.http.mapping.Path; import com.wizzardo.http.request.Header; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import com.wizzardo.http.response.Status; import com.wizzardo.http.utils.AsciiReader; import com.wizzardo.tools.misc.ExceptionDrivenStringBuilder; import com.wizzardo.tools.misc.Unchecked; import com.wizzardo.tools.misc.pool.Holder; import com.wizzardo.tools.misc.pool.Pool; import com.wizzardo.tools.misc.pool.SoftHolder; import com.wizzardo.tools.misc.pool.ThreadLocalPool; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicReference; public class ProxyHandler implements Handler { protected static final Pool<ExceptionDrivenStringBuilder> BUILDER_POOL = new ThreadLocalPool<ExceptionDrivenStringBuilder>() { @Override public ExceptionDrivenStringBuilder create() { return new ExceptionDrivenStringBuilder(); } @Override protected Holder<ExceptionDrivenStringBuilder> createHolder(ExceptionDrivenStringBuilder builder) { return new SoftHolder<ExceptionDrivenStringBuilder>(this, builder) { @Override public ExceptionDrivenStringBuilder get() { ExceptionDrivenStringBuilder builder = super.get(); builder.setLength(0); return builder; } }; } }; protected Queue<ProxyConnection> connections = new LinkedBlockingQueue<>(); protected EpollCore<ProxyConnection> epoll = new EpollCore<ProxyConnection>() { @Override protected ProxyConnection createConnection(int fd, int ip, int port) { return new ProxyConnection(fd, ip, port); } @Override protected IOThread<ProxyConnection> createIOThread(int number, int divider) { return new IOThread<ProxyConnection>(number, divider) { @Override public void onRead(ProxyConnection connection) { connection.read(this); } }; } }; { epoll.start(); } protected String host; protected int port; public ProxyHandler(String host) { this(host, 80); } public ProxyHandler(String host, int port) { this.host = host; this.port = port; } class ProxyConnection extends Connection { Request srcRequest; Response srcResponse; volatile ResponseReader responseReader; final AtomicReference<Thread> processingBy = new AtomicReference<>(); final byte[] buffer = new byte[16 * 1024]; volatile long limit; public ProxyConnection(int fd, int ip, int port) { super(fd, ip, port); } protected void read(ByteBufferProvider byteBufferProvider) { Thread current = Thread.currentThread(); Thread processing = processingBy.get(); if (processing != current && processing != null) processing = null; if (!processingBy.compareAndSet(processing, current)) return; if (!srcRequest.connection().isAlive()) { processingBy.set(null); end(); return; } try { int r; byte[] buffer = this.buffer; while ((r = read(buffer, byteBufferProvider)) > 0) { int offset = 0; if (!responseReader.isComplete()) { int k = responseReader.read(buffer, 0, r); if (k < 0) continue; srcResponse.headersReset(); for (Map.Entry<String, MultiValue> entry : responseReader.headers.entrySet()) { String name = entry.getKey(); if (entry.getValue().size() > 1) for (String value : entry.getValue().getValues()) { srcResponse.appendHeader(name, value); } else srcResponse.appendHeader(name, entry.getValue().getValue()); } offset = k; MultiValue length = responseReader.getHeaders().get(Header.KEY_CONTENT_LENGTH.value); if (!responseReader.status.equals("200")) srcResponse.setStatus(Status.valueOf(Integer.parseInt(responseReader.getStatus()))); srcResponse.commit(srcRequest.connection()); if (length == null) { processingBy.set(null); end(); return; } limit = Long.valueOf(length.getValue()); } limit -= r - offset; if (limit == 0) proxyWrite(new CustomReadableByteArray(buffer, offset, r - offset), byteBufferProvider); else proxyWrite(new CustomReadableByteArray(Arrays.copyOfRange(buffer, offset, r)), byteBufferProvider); // System.out.println("response: " + new String(buffer, offset, r - offset)); // System.out.println("need to read: " + limit + "; r:" + r + " ,offset:" + offset); if (limit == 0) { processingBy.set(null); end(); return; } break; } } catch (Exception e) { try { close(); } catch (IOException ignored) { } try { srcRequest.connection().close(); } catch (IOException ignored) { } e.printStackTrace(); } // System.out.println("wait "+srcRequest.connection().hasDataToWrite()); processingBy.set(null); } protected void proxyWrite(CustomReadableByteArray readable, ByteBufferProvider bufferProvider) { srcRequest.connection().write(readable, bufferProvider); } protected void end() { srcRequest.connection().onFinishingHandling(); limit = -1; connections.add(this); } private class CustomReadableByteArray extends ReadableByteArray { public CustomReadableByteArray(byte[] bytes) { super(bytes); } public CustomReadableByteArray(byte[] bytes, int offset, int length) { super(bytes, offset, length); } @Override public void onComplete() { Unchecked.run(() -> ProxyConnection.this.read((ByteBufferProvider) Thread.currentThread())); } } } @Override public Response handle(Request request, Response response) throws IOException { ProxyConnection connection = connections.poll(); if (connection == null || !connection.isAlive()) { // System.out.println("create new connection " + (connection == null ? "" : ", not alive")); connection = epoll.connect(host, port); } connection.srcRequest = request; connection.srcResponse = response; connection.responseReader = new ResponseReader(); try (Holder<ExceptionDrivenStringBuilder> holder = BUILDER_POOL.holder()) { ExceptionDrivenStringBuilder requestBuilder = holder.get(); //todo: append params requestBuilder.append(request.method().name()).append(" ").append(rewritePath(request.path())).append(" HTTP/1.1\r\n"); requestBuilder.append("Host: " + host); if (port != 80) requestBuilder.append(":").append(port); requestBuilder.append("\r\n"); requestBuilder.append("X-Real-IP: ").append(request.connection().getIp()).append("\r\n"); requestBuilder.append("X-Forwarded-for: ").append(request.connection().getServer().getHost()).append("\r\n"); Map<String, MultiValue> headers = request.headers(); for (Map.Entry<String, MultiValue> header : headers.entrySet()) { if (header.getKey().equalsIgnoreCase("Host")) continue; if (header.getValue().size() == 1) requestBuilder.append(header.getKey()).append(": ").append(header.getValue().getValue()).append("\r\n"); else for (String value : header.getValue().getValues()) requestBuilder.append(header.getKey()).append(": ").append(value).append("\r\n"); } requestBuilder.append("\r\n"); //todo: post request // System.out.println("send request: " + requestBuilder); connection.write(AsciiReader.write(requestBuilder.toString()), (ByteBufferProvider) Thread.currentThread()); } response.async(); return response; } public String rewritePath(Path path) { return path.toString(); } }
package com.zaxxer.hikari.pool; import static com.zaxxer.hikari.util.UtilityElf.createInstance; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.util.DefaultThreadFactory; import com.zaxxer.hikari.util.DriverDataSource; import com.zaxxer.hikari.util.PropertyElf; public final class PoolElf { private static final Logger LOGGER = LoggerFactory.getLogger(PoolElf.class); private static final int UNINITIALIZED = -1; private static final int TRUE = 1; private static final int FALSE = 0; private int networkTimeout; private int transactionIsolation; private long validationTimeout; private int isNetworkTimeoutSupported; private int isQueryTimeoutSupported; private Executor netTimeoutExecutor; private final HikariConfig config; private final String poolName; private final String catalog; private final boolean isReadOnly; private final boolean isAutoCommit; private final boolean isUseJdbc4Validation; private final boolean isIsolateInternalQueries; private volatile boolean isValidChecked; private volatile boolean isValidSupported; public PoolElf(final HikariConfig configuration) { this.config = configuration; this.networkTimeout = -1; this.catalog = config.getCatalog(); this.isReadOnly = config.isReadOnly(); this.isAutoCommit = config.isAutoCommit(); this.validationTimeout = config.getValidationTimeout(); this.transactionIsolation = getTransactionIsolation(config.getTransactionIsolation()); this.isValidSupported = true; this.isQueryTimeoutSupported = UNINITIALIZED; this.isNetworkTimeoutSupported = UNINITIALIZED; this.isUseJdbc4Validation = config.getConnectionTestQuery() == null; this.isIsolateInternalQueries = config.isIsolateInternalQueries(); this.poolName = config.getPoolName(); } /** * Close connection and eat any exception. * * @param connection the connection to close * @param closureReason the reason the connection was closed (if known) */ public void quietlyCloseConnection(final Connection connection, final String closureReason) { try { if (connection == null || connection.isClosed()) { return; } LOGGER.debug("Closing connection {} in pool {} {}", connection, poolName, closureReason); try { setNetworkTimeout(connection, TimeUnit.SECONDS.toMillis(15)); } finally { // continue with the close even if setNetworkTimeout() throws (due to driver poorly behaving drivers) connection.close(); } } catch (Throwable e) { LOGGER.debug("Exception closing connection {} in pool {} {}", connection, poolName, closureReason, e); } } /** * Get the int value of a transaction isolation level by name. * * @param transactionIsolationName the name of the transaction isolation level * @return the int value of the isolation level or -1 */ public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { Field field = Connection.class.getField(transactionIsolationName); return field.getInt(null); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; } /** * Create/initialize the underlying DataSource. * * @return a DataSource instance */ DataSource initializeDataSource() { final String jdbcUrl = config.getJdbcUrl(); final String username = config.getUsername(); final String password = config.getPassword(); final String dsClassName = config.getDataSourceClassName(); final String driverClassName = config.getDriverClassName(); final Properties dataSourceProperties = config.getDataSourceProperties(); DataSource dataSource = config.getDataSource(); if (dsClassName != null && dataSource == null) { dataSource = createInstance(dsClassName, DataSource.class); PropertyElf.setTargetFromProperties(dataSource, dataSourceProperties); } else if (jdbcUrl != null && dataSource == null) { dataSource = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password); } if (dataSource != null) { setLoginTimeout(dataSource, config.getConnectionTimeout()); createNetworkTimeoutExecutor(dataSource, dsClassName, jdbcUrl); } return dataSource; } /** * Setup a connection initial state. * * @param connection a Connection * @param connectionTimeout * @param initSql * @param isAutoCommit auto-commit state * @param isReadOnly read-only state * @param transactionIsolation transaction isolation * @param catalog default catalog * @throws SQLException thrown from driver */ void setupConnection(final Connection connection, final long connectionTimeout) throws SQLException { if (isUseJdbc4Validation && !isJdbc4ValidationSupported(connection)) { throw new SQLException("JDBC4 Connection.isValid() method not supported, connection test query must be configured"); } networkTimeout = (networkTimeout < 0 ? getAndSetNetworkTimeout(connection, connectionTimeout) : networkTimeout); transactionIsolation = (transactionIsolation < 0 ? connection.getTransactionIsolation() : transactionIsolation); connection.setAutoCommit(isAutoCommit); connection.setReadOnly(isReadOnly); if (transactionIsolation != connection.getTransactionIsolation()) { connection.setTransactionIsolation(transactionIsolation); } if (catalog != null) { connection.setCatalog(catalog); } executeSql(connection, config.getConnectionInitSql(), isAutoCommit); setNetworkTimeout(connection, networkTimeout); } /** * Check whether the connection is alive or not. * * @param connection the connection to test * @return true if the connection is alive, false if it is not alive or we timed out */ boolean isConnectionAlive(final Connection connection) { try { int timeoutSec = (int) TimeUnit.MILLISECONDS.toSeconds(validationTimeout); if (isUseJdbc4Validation) { return connection.isValid(timeoutSec); } final int originalTimeout = getAndSetNetworkTimeout(connection, validationTimeout); try (Statement statement = connection.createStatement()) { setQueryTimeout(statement, timeoutSec); try (ResultSet rs = statement.executeQuery(config.getConnectionTestQuery())) { /* auto close */ } } if (isIsolateInternalQueries && !isAutoCommit) { connection.rollback(); } setNetworkTimeout(connection, originalTimeout); return true; } catch (SQLException e) { LOGGER.warn("Exception during alive check, Connection ({}) declared dead.", connection, e); return false; } } void resetConnectionState(final PoolBagEntry poolEntry) throws SQLException { if (poolEntry.isReadOnly != isReadOnly) { poolEntry.connection.setReadOnly(isReadOnly); } if (poolEntry.isAutoCommit != isAutoCommit) { poolEntry.connection.setAutoCommit(isAutoCommit); } if (poolEntry.transactionIsolation != transactionIsolation) { poolEntry.connection.setTransactionIsolation(transactionIsolation); } final String currentCatalog = poolEntry.catalog; if ((currentCatalog != null && !currentCatalog.equals(catalog)) || (currentCatalog == null && catalog != null)) { poolEntry.connection.setCatalog(catalog); } if (poolEntry.networkTimeout != networkTimeout) { setNetworkTimeout(poolEntry.connection, networkTimeout); } } void resetPoolEntry(final PoolBagEntry poolEntry) { poolEntry.setCatalog(catalog); poolEntry.setReadOnly(isReadOnly); poolEntry.setAutoCommit(isAutoCommit); poolEntry.setNetworkTimeout(networkTimeout); poolEntry.setTransactionIsolation(transactionIsolation); } void setValidationTimeout(final long validationTimeout) { this.validationTimeout = validationTimeout; } /** * Register MBeans for HikariConfig and HikariPool. * * @param configuration a HikariConfig instance * @param pool a HikariPool instance */ void registerMBeans(final HikariPool pool) { if (!config.isRegisterMbeans()) { return; } try { final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")"); final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")"); if (!mBeanServer.isRegistered(beanConfigName)) { mBeanServer.registerMBean(config, beanConfigName); mBeanServer.registerMBean(pool, beanPoolName); } else { LOGGER.error("You cannot use the same pool name for separate pool instances."); } } catch (Exception e) { LOGGER.warn("Unable to register management beans.", e); } } /** * Unregister MBeans for HikariConfig and HikariPool. * * @param configuration a HikariConfig instance */ void unregisterMBeans() { if (!config.isRegisterMbeans()) { return; } try { final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")"); final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")"); if (mBeanServer.isRegistered(beanConfigName)) { mBeanServer.unregisterMBean(beanConfigName); mBeanServer.unregisterMBean(beanPoolName); } } catch (Exception e) { LOGGER.warn("Unable to unregister management beans.", e); } } void shutdownTimeoutExecutor() { if (netTimeoutExecutor != null && netTimeoutExecutor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) netTimeoutExecutor).shutdownNow(); } } /** * Return true if the driver appears to be JDBC 4.0 compliant. * * @param connection a Connection to check * @return true if JDBC 4.1 compliance, false otherwise */ private boolean isJdbc4ValidationSupported(final Connection connection) { if (!isValidChecked) { try { // We don't care how long the wait actually is here, just whether it returns without exception. This // call will throw various exceptions in the case of a non-JDBC 4.0 compliant driver connection.isValid(1); } catch (Throwable e) { isValidSupported = false; LOGGER.debug("{} - JDBC4 Connection.isValid() not supported ({})", poolName, e.getMessage()); } isValidChecked = true; } return isValidSupported; } /** * Set the query timeout, if it is supported by the driver. * * @param statement a statement to set the query timeout on * @param timeoutSec the number of seconds before timeout */ private void setQueryTimeout(final Statement statement, final int timeoutSec) { if (isQueryTimeoutSupported != FALSE) { try { statement.setQueryTimeout(timeoutSec); isQueryTimeoutSupported = TRUE; } catch (Throwable e) { if (isQueryTimeoutSupported == UNINITIALIZED) { isQueryTimeoutSupported = FALSE; LOGGER.debug("{} - Statement.setQueryTimeout() not supported", poolName); } } } } /** * Set the network timeout, if <code>isUseNetworkTimeout</code> is <code>true</code> and the * driver supports it. Return the pre-existing value of the network timeout. * * @param connection the connection to set the network timeout on * @param timeoutMs the number of milliseconds before timeout * @return the pre-existing network timeout value */ private int getAndSetNetworkTimeout(final Connection connection, final long timeoutMs) { if (isNetworkTimeoutSupported != FALSE) { try { final int originalTimeout = connection.getNetworkTimeout(); connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs); isNetworkTimeoutSupported = TRUE; return originalTimeout; } catch (Throwable e) { if (isNetworkTimeoutSupported == UNINITIALIZED) { isNetworkTimeoutSupported = FALSE; } LOGGER.debug("{} - Connection.setNetworkTimeout() not supported", poolName); } } return 0; } /** * Set the network timeout, if <code>isUseNetworkTimeout</code> is <code>true</code> and the * driver supports it. * * @param connection the connection to set the network timeout on * @param timeoutMs the number of milliseconds before timeout * @throws SQLException throw if the connection.setNetworkTimeout() call throws */ private void setNetworkTimeout(final Connection connection, final long timeoutMs) throws SQLException { if (isNetworkTimeoutSupported == TRUE) { connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs); } } /** * Execute the user-specified init SQL. * * @param connection the connection to initialize * @param sql the SQL to execute * @param isAutoCommit whether to commit the SQL after execution or not * @throws SQLException throws if the init SQL execution fails */ private void executeSql(final Connection connection, final String sql, final boolean isAutoCommit) throws SQLException { if (sql != null) { try (Statement statement = connection.createStatement()) { statement.execute(sql); if (!isAutoCommit) { connection.commit(); } } } } private void createNetworkTimeoutExecutor(final DataSource dataSource, final String dsClassName, final String jdbcUrl) { if ((dsClassName != null && dsClassName.contains("Mysql")) || (jdbcUrl != null && jdbcUrl.contains("mysql")) || (dataSource != null && dataSource.getClass().getName().contains("Mysql"))) { netTimeoutExecutor = new SynchronousExecutor(); } else { ThreadFactory threadFactory = config.getThreadFactory() != null ? config.getThreadFactory() : new DefaultThreadFactory("Hikari JDBC-timeout executor", true); ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(threadFactory); executor.allowCoreThreadTimeOut(true); executor.setKeepAliveTime(15, TimeUnit.SECONDS); netTimeoutExecutor = executor; } } private static class SynchronousExecutor implements Executor { /** {@inheritDoc} */ @Override public void execute(Runnable command) { try { command.run(); } catch (Throwable t) { LOGGER.debug("Exception executing {}", command, t); } } } /** * Set the loginTimeout on the specified DataSource. * * @param dataSource the DataSource * @param connectionTimeout the timeout in milliseconds */ private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout) { if (connectionTimeout != Integer.MAX_VALUE) { try { dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout))); } catch (SQLException e) { LOGGER.warn("Unable to set DataSource login timeout", e); } } } }
package hudson.plugins.ec2; import com.amazonaws.services.ec2.model.*; import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.Util; import hudson.model.Node; import hudson.slaves.SlaveComputer; import java.io.IOException; import java.util.Collections; import java.util.logging.Level; import java.util.logging.Logger; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.AmazonEC2; /** * @author Kohsuke Kawaguchi */ public class EC2Computer extends SlaveComputer { private static final Logger LOGGER = Logger.getLogger(EC2Computer.class.getName()); /** * Cached description of this EC2 instance. Lazily fetched. */ private volatile Instance ec2InstanceDescription; private volatile Boolean isNitro; public EC2Computer(EC2AbstractSlave slave) { super(slave); } @Override public EC2AbstractSlave getNode() { return (EC2AbstractSlave) super.getNode(); } @CheckForNull public String getInstanceId() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getInstanceId(); } public String getEc2Type() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getEc2Type(); } public String getSpotInstanceRequestId() { EC2AbstractSlave node = getNode(); if (node instanceof EC2SpotSlave) { return ((EC2SpotSlave) node).getSpotInstanceRequestId(); } return ""; } public EC2Cloud getCloud() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getCloud(); } @CheckForNull public SlaveTemplate getSlaveTemplate() { EC2AbstractSlave node = getNode(); if (node != null) { return node.getCloud().getTemplate(node.templateDescription); } return null; } /** * Gets the EC2 console output. */ public String getConsoleOutput() throws AmazonClientException { try { return getDecodedConsoleOutputResponse().getOutput(); } catch (InterruptedException e) { return null; } } /** * Gets the EC2 decoded console output. * @since TODO */ public String getDecodedConsoleOutput() throws AmazonClientException { try { return getDecodedConsoleOutputResponse().getDecodedOutput(); } catch (InterruptedException e) { return null; } } private GetConsoleOutputResult getDecodedConsoleOutputResponse() throws AmazonClientException, InterruptedException { AmazonEC2 ec2 = getCloud().connect(); GetConsoleOutputRequest request = new GetConsoleOutputRequest(getInstanceId()); if (checkIfNitro()) { //Can only be used if instance has hypervisor Nitro request.setLatest(true); } return ec2.getConsoleOutput(request); } /** * Check if instance has hypervisor Nitro */ private boolean checkIfNitro() throws AmazonClientException, InterruptedException { try { if (isNitro == null) { DescribeInstanceTypesRequest request = new DescribeInstanceTypesRequest(); request.setInstanceTypes(Collections.singletonList(describeInstance().getInstanceType())); AmazonEC2 ec2 = getCloud().connect(); DescribeInstanceTypesResult result = ec2.describeInstanceTypes(request); if (result.getInstanceTypes().size() == 1) { String hypervisor = result.getInstanceTypes().get(0).getHypervisor(); isNitro = hypervisor.equals("nitro"); } else { isNitro = false; } } return isNitro; } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, "Could not describe-instance-types to check if instance is nitro based", e); isNitro = false; return isNitro; } } /** * Obtains the instance state description in EC2. * * <p> * This method returns a cached state, so it's not suitable to check {@link Instance#getState()} from the returned * instance (but all the other fields are valid as it won't change.) * * The cache can be flushed using {@link #updateInstanceDescription()} */ public Instance describeInstance() throws AmazonClientException, InterruptedException { if (ec2InstanceDescription == null) ec2InstanceDescription = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); return ec2InstanceDescription; } /** * This will flush any cached description held by {@link #describeInstance()}. */ public Instance updateInstanceDescription() throws AmazonClientException, InterruptedException { return ec2InstanceDescription = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); } /** * Gets the current state of the instance. * * <p> * Unlike {@link #describeInstance()}, this method always return the current status by calling EC2. */ public InstanceState getState() throws AmazonClientException, InterruptedException { ec2InstanceDescription = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); return InstanceState.find(ec2InstanceDescription.getState().getName()); } /** * Number of milli-secs since the instance was started. */ public long getUptime() throws AmazonClientException, InterruptedException { return System.currentTimeMillis() - describeInstance().getLaunchTime().getTime(); } /** * Returns uptime in the human readable form. */ public String getUptimeString() throws AmazonClientException, InterruptedException { return Util.getTimeSpanString(getUptime()); } /** * Return the time this instance was launched in ms since the epoch. * * @return Time this instance was launched, in ms since the epoch. */ public long getLaunchTime() throws InterruptedException { return this.describeInstance().getLaunchTime().getTime(); } /** * When the agent is deleted, terminate the instance. */ @Override public HttpResponse doDoDelete() throws IOException { checkPermission(DELETE); EC2AbstractSlave node = getNode(); if (node != null) node.terminate(); return new HttpRedirect(".."); } /** * What username to use to run root-like commands * * @return remote admin or {@code null} if the associated {@link Node} is {@code null} */ @CheckForNull public String getRemoteAdmin() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getRemoteAdmin(); } public int getSshPort() { EC2AbstractSlave node = getNode(); return node == null ? 22 : node.getSshPort(); } public String getRootCommandPrefix() { EC2AbstractSlave node = getNode(); return node == null ? "" : node.getRootCommandPrefix(); } public String getSlaveCommandPrefix() { EC2AbstractSlave node = getNode(); return node == null ? "" : node.getSlaveCommandPrefix(); } public String getSlaveCommandSuffix() { EC2AbstractSlave node = getNode(); return node == null ? "" : node.getSlaveCommandSuffix(); } public void onConnected() { EC2AbstractSlave node = getNode(); if (node != null) { node.onConnected(); } } }
package io.github.classgraph; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import io.github.classgraph.Scanner.ClassfileScanWorkUnit; import nonapi.io.github.classgraph.concurrency.WorkQueue; import nonapi.io.github.classgraph.fileslice.reader.ClassfileReader; import nonapi.io.github.classgraph.scanspec.ScanSpec; import nonapi.io.github.classgraph.types.ParseException; import nonapi.io.github.classgraph.utils.CollectionUtils; import nonapi.io.github.classgraph.utils.JarUtils; import nonapi.io.github.classgraph.utils.LogNode; import nonapi.io.github.classgraph.utils.StringUtils; /** * A classfile binary format parser. Implements its own buffering to avoid the overhead of using DataInputStream. * This class should only be used by a single thread at a time, but can be re-used to scan multiple classfiles in * sequence, to avoid re-allocating buffer memory. */ class Classfile { /** The {@link ClassfileReader} for the current classfile. */ private ClassfileReader reader; /** The classpath element that contains this classfile. */ private final ClasspathElement classpathElement; /** The classpath order. */ private final List<ClasspathElement> classpathOrder; /** The relative path to the classfile (should correspond to className). */ private final String relativePath; /** The classfile resource. */ private final Resource classfileResource; /** The string intern map. */ private final ConcurrentHashMap<String, String> stringInternMap; /** The name of the class. */ private String className; /** The minor version of the classfile format. */ private int minorVersion; /** The major version of the classfile format. */ private int majorVersion; /** Whether this is an external class. */ private final boolean isExternalClass; /** The class modifiers. */ private int classModifiers; /** Whether this class is an interface. */ private boolean isInterface; /** Whether this class is a record. */ private boolean isRecord; /** Whether this class is an annotation. */ private boolean isAnnotation; /** The superclass name. (can be null if no superclass, or if superclass is rejected.) */ private String superclassName; /** The implemented interfaces. */ private List<String> implementedInterfaces; /** The class annotations. */ private AnnotationInfoList classAnnotations; /** The fully qualified name of the defining method. */ private String fullyQualifiedDefiningMethodName; /** Class containment entries. */ private List<ClassContainment> classContainmentEntries; /** Annotation default parameter values. */ private AnnotationParameterValueList annotationParamDefaultValues; /** Referenced class names. */ private Set<String> refdClassNames; /** The field info list. */ private FieldInfoList fieldInfoList; /** The method info list. */ private MethodInfoList methodInfoList; /** The type signature. */ private String typeSignatureStr; /** The type annotation decorators for the {@link ClassTypeSignature} instance. */ private List<ClassTypeAnnotationDecorator> classTypeAnnotationDecorators; /** The names of accepted classes found in the classpath while scanning paths within classpath elements. */ private final Set<String> acceptedClassNamesFound; /** * The names of external (non-accepted) classes scheduled for extended scanning (where scanning is extended * upwards to superclasses, interfaces and annotations). */ private final Set<String> classNamesScheduledForExtendedScanning; /** Any additional work units scheduled for scanning. */ private List<ClassfileScanWorkUnit> additionalWorkUnits; /** The scan spec. */ private final ScanSpec scanSpec; /** The number of constant pool entries plus one. */ private int cpCount; /** The byte offset for the beginning of each entry in the constant pool. */ private int[] entryOffset; /** The tag (type) for each entry in the constant pool. */ private int[] entryTag; /** The indirection index for String/Class entries in the constant pool. */ private int[] indirectStringRefs; /** An empty array for the case where there are no annotations. */ private static final AnnotationInfo[] NO_ANNOTATIONS = new AnnotationInfo[0]; /** * Class containment. */ static class ClassContainment { /** The inner class name. */ public final String innerClassName; /** The inner class modifier bits. */ public final int innerClassModifierBits; /** The outer class name. */ public final String outerClassName; /** * Constructor. * * @param innerClassName * the inner class name. * @param innerClassModifierBits * the inner class modifier bits. * @param outerClassName * the outer class name. */ public ClassContainment(final String innerClassName, final int innerClassModifierBits, final String outerClassName) { this.innerClassName = innerClassName; this.innerClassModifierBits = innerClassModifierBits; this.outerClassName = outerClassName; } } /** Thrown when a classfile's contents are not in the correct format. */ static class ClassfileFormatException extends IOException { /** serialVersionUID. */ static final long serialVersionUID = 1L; /** * Constructor. * * @param message * the message */ public ClassfileFormatException(final String message) { super(message); } /** * Constructor. * * @param message * the message * @param cause * the cause */ public ClassfileFormatException(final String message, final Throwable cause) { super(message, cause); } /** * Speed up exception (stack trace is not needed for this exception). * * @return this */ @Override public synchronized Throwable fillInStackTrace() { return this; } } /** Thrown when a classfile needs to be skipped. */ static class SkipClassException extends IOException { /** serialVersionUID. */ static final long serialVersionUID = 1L; /** * Constructor. * * @param message * the message */ public SkipClassException(final String message) { super(message); } /** * Speed up exception (stack trace is not needed for this exception). * * @return this */ @Override public synchronized Throwable fillInStackTrace() { return this; } } /** * Extend scanning to a superclass, interface or annotation. * * @param className * the class name * @param relationship * the relationship type * @param log * the log */ private void scheduleScanningIfExternalClass(final String className, final String relationship, final LogNode log) { // Don't scan Object if (className != null && !className.equals("java.lang.Object") // Don't schedule a class for scanning that was already found to be accepted && !acceptedClassNamesFound.contains(className) // Only schedule each external class once for scanning, across all threads && classNamesScheduledForExtendedScanning.add(className)) { if (scanSpec.classAcceptReject.isRejected(className)) { if (log != null) { log.log("Cannot extend scanning upwards to external " + relationship + " " + className + ", since it is rejected"); } } else { // Search for the named class' classfile among classpath elements, in classpath order (this is O(N) // for each class, but there shouldn't be too many cases of extending scanning upwards) final String classfilePath = JarUtils.classNameToClassfilePath(className); // First check current classpath element, to avoid iterating through other classpath elements Resource classResource = classpathElement.getResource(classfilePath); ClasspathElement foundInClasspathElt = null; if (classResource != null) { // Found the classfile in the current classpath element foundInClasspathElt = classpathElement; } else { // Didn't find the classfile in the current classpath element -- iterate through other elements for (final ClasspathElement classpathOrderElt : classpathOrder) { if (classpathOrderElt != classpathElement) { classResource = classpathOrderElt.getResource(classfilePath); if (classResource != null) { foundInClasspathElt = classpathOrderElt; break; } } } } if (classResource != null) { // Found class resource if (log != null) { // Log the extended scan as a child LogNode of the current class' scan log, since the // external class is not scanned at the regular place in the classpath element hierarchy // traversal classResource.scanLog = log .log("Extending scanning to external " + relationship + (foundInClasspathElt == classpathElement ? " in same classpath element" : " in classpath element " + foundInClasspathElt) + ": " + className); } if (additionalWorkUnits == null) { additionalWorkUnits = new ArrayList<>(); } // Schedule class resource for scanning additionalWorkUnits.add(new ClassfileScanWorkUnit(foundInClasspathElt, classResource, /* isExternalClass = */ true)); } else { if (log != null) { log.log("External " + relationship + " " + className + " was not found in " + "non-rejected packages -- cannot extend scanning to this class"); } } } } } /** * Check if scanning needs to be extended upwards from an annotation parameter value. * * @param annotationParamVal * the {@link AnnotationInfo} object for an annotation, or for an annotation parameter value. * @param log * the log */ private void extendScanningUpwardsFromAnnotationParameterValues(final Object annotationParamVal, final LogNode log) { if (annotationParamVal == null) { // Should not be possible -- ignore } else if (annotationParamVal instanceof AnnotationInfo) { final AnnotationInfo annotationInfo = (AnnotationInfo) annotationParamVal; scheduleScanningIfExternalClass(annotationInfo.getClassName(), "annotation class", log); for (final AnnotationParameterValue apv : annotationInfo.getParameterValues()) { extendScanningUpwardsFromAnnotationParameterValues(apv.getValue(), log); } } else if (annotationParamVal instanceof AnnotationEnumValue) { scheduleScanningIfExternalClass(((AnnotationEnumValue) annotationParamVal).getClassName(), "enum class", log); } else if (annotationParamVal instanceof AnnotationClassRef) { scheduleScanningIfExternalClass(((AnnotationClassRef) annotationParamVal).getClassName(), "class ref", log); } else if (annotationParamVal.getClass().isArray()) { for (int i = 0, n = Array.getLength(annotationParamVal); i < n; i++) { extendScanningUpwardsFromAnnotationParameterValues(Array.get(annotationParamVal, i), log); } } else { // String etc. -- ignore } } /** * Check if scanning needs to be extended upwards to an external superclass, interface or annotation. * * @param log * the log */ private void extendScanningUpwards(final LogNode log) { // Check superclass if (superclassName != null) { scheduleScanningIfExternalClass(superclassName, "superclass", log); } // Check implemented interfaces if (implementedInterfaces != null) { for (final String interfaceName : implementedInterfaces) { scheduleScanningIfExternalClass(interfaceName, "interface", log); } } // Check class annotations if (classAnnotations != null) { for (final AnnotationInfo annotationInfo : classAnnotations) { scheduleScanningIfExternalClass(annotationInfo.getName(), "class annotation", log); extendScanningUpwardsFromAnnotationParameterValues(annotationInfo, log); } } // Check annotation default parameter values if (annotationParamDefaultValues != null) { for (final AnnotationParameterValue apv : annotationParamDefaultValues) { extendScanningUpwardsFromAnnotationParameterValues(apv.getValue(), log); } } // Check method annotations and method parameter annotations if (methodInfoList != null) { for (final MethodInfo methodInfo : methodInfoList) { if (methodInfo.annotationInfo != null) { for (final AnnotationInfo methodAnnotationInfo : methodInfo.annotationInfo) { scheduleScanningIfExternalClass(methodAnnotationInfo.getName(), "method annotation", log); extendScanningUpwardsFromAnnotationParameterValues(methodAnnotationInfo, log); } if (methodInfo.parameterAnnotationInfo != null && methodInfo.parameterAnnotationInfo.length > 0) { for (final AnnotationInfo[] paramAnnInfoArr : methodInfo.parameterAnnotationInfo) { if (paramAnnInfoArr != null && paramAnnInfoArr.length > 0) { for (final AnnotationInfo paramAnnInfo : paramAnnInfoArr) { scheduleScanningIfExternalClass(paramAnnInfo.getName(), "method parameter annotation", log); extendScanningUpwardsFromAnnotationParameterValues(paramAnnInfo, log); } } } } } } } // Check field annotations if (fieldInfoList != null) { for (final FieldInfo fieldInfo : fieldInfoList) { if (fieldInfo.annotationInfo != null) { for (final AnnotationInfo fieldAnnotationInfo : fieldInfo.annotationInfo) { scheduleScanningIfExternalClass(fieldAnnotationInfo.getName(), "field annotation", log); extendScanningUpwardsFromAnnotationParameterValues(fieldAnnotationInfo, log); } } } } // Check if this class is an inner class, and if so, extend scanning to outer class if (classContainmentEntries != null) { for (final ClassContainment classContainmentEntry : classContainmentEntries) { if (classContainmentEntry.innerClassName.equals(className)) { scheduleScanningIfExternalClass(classContainmentEntry.outerClassName, "outer class", log); } } } } /** * Link classes. Not threadsafe, should be run in a single-threaded context. * * @param classNameToClassInfo * map from class name to class info * @param packageNameToPackageInfo * map from package name to package info * @param moduleNameToModuleInfo * map from module name to module info */ void link(final Map<String, ClassInfo> classNameToClassInfo, final Map<String, PackageInfo> packageNameToPackageInfo, final Map<String, ModuleInfo> moduleNameToModuleInfo) { boolean isModuleDescriptor = false; boolean isPackageDescriptor = false; ClassInfo classInfo = null; if (className.equals("module-info")) { isModuleDescriptor = true; } else if (className.equals("package-info") || className.endsWith(".package-info")) { isPackageDescriptor = true; } else { // Handle regular classfile classInfo = ClassInfo.addScannedClass(className, classModifiers, isExternalClass, classNameToClassInfo, classpathElement, classfileResource); classInfo.setClassfileVersion(minorVersion, majorVersion); classInfo.setModifiers(classModifiers); classInfo.setIsInterface(isInterface); classInfo.setIsAnnotation(isAnnotation); classInfo.setIsRecord(isRecord); if (superclassName != null) { classInfo.addSuperclass(superclassName, classNameToClassInfo); } if (implementedInterfaces != null) { for (final String interfaceName : implementedInterfaces) { classInfo.addImplementedInterface(interfaceName, classNameToClassInfo); } } if (classAnnotations != null) { for (final AnnotationInfo classAnnotation : classAnnotations) { classInfo.addClassAnnotation(classAnnotation, classNameToClassInfo); } } if (classContainmentEntries != null) { ClassInfo.addClassContainment(classContainmentEntries, classNameToClassInfo); } if (annotationParamDefaultValues != null) { classInfo.addAnnotationParamDefaultValues(annotationParamDefaultValues); } if (fullyQualifiedDefiningMethodName != null) { classInfo.addFullyQualifiedDefiningMethodName(fullyQualifiedDefiningMethodName); } if (fieldInfoList != null) { classInfo.addFieldInfo(fieldInfoList, classNameToClassInfo); } if (methodInfoList != null) { classInfo.addMethodInfo(methodInfoList, classNameToClassInfo); } if (typeSignatureStr != null) { classInfo.setTypeSignature(typeSignatureStr); } if (refdClassNames != null) { classInfo.addReferencedClassNames(refdClassNames); } if (classTypeAnnotationDecorators != null) { classInfo.addTypeDecorators(classTypeAnnotationDecorators); } } // Get or create PackageInfo, if this is not a module descriptor (the module descriptor's package is "") PackageInfo packageInfo = null; if (!isModuleDescriptor) { // Get package for this class or package descriptor final String packageName = PackageInfo.getParentPackageName(className); packageInfo = PackageInfo.getOrCreatePackage(packageName, packageNameToPackageInfo, scanSpec); if (isPackageDescriptor) { // Add any class annotations on the package-info.class file to the ModuleInfo packageInfo.addAnnotations(classAnnotations); } else if (classInfo != null) { // Add ClassInfo to PackageInfo, and vice versa packageInfo.addClassInfo(classInfo); classInfo.packageInfo = packageInfo; } } // Get or create ModuleInfo, if there is a module name final String moduleName = classpathElement.getModuleName(); if (moduleName != null) { // Get or create a ModuleInfo object for this module ModuleInfo moduleInfo = moduleNameToModuleInfo.get(moduleName); if (moduleInfo == null) { moduleNameToModuleInfo.put(moduleName, moduleInfo = new ModuleInfo(classfileResource.getModuleRef(), classpathElement)); } if (isModuleDescriptor) { // Add any class annotations on the module-info.class file to the ModuleInfo moduleInfo.addAnnotations(classAnnotations); } if (classInfo != null) { // Add ClassInfo to ModuleInfo, and vice versa moduleInfo.addClassInfo(classInfo); classInfo.moduleInfo = moduleInfo; } if (packageInfo != null) { // Add PackageInfo to ModuleInfo moduleInfo.addPackageInfo(packageInfo); } } } /** * Intern a string. * * @param str * the str * @return the string */ private String intern(final String str) { if (str == null) { return null; } final String interned = stringInternMap.putIfAbsent(str, str); if (interned != null) { return interned; } return str; } /** * Get the byte offset within the buffer of a string from the constant pool, or 0 for a null string. * * @param cpIdx * the constant pool index * @param subFieldIdx * should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for * CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1. * @return the constant pool string offset * @throws ClassfileFormatException * If a problem is detected */ private int getConstantPoolStringOffset(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final int t = entryTag[cpIdx]; if ((t != 12 && subFieldIdx != 0) || (t == 12 && subFieldIdx != 0 && subFieldIdx != 1)) { throw new ClassfileFormatException( "Bad subfield index " + subFieldIdx + " for tag " + t + ", cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } int cpIdxToUse; if (t == 0) { // Assume this means null return 0; } else if (t == 1) { // CONSTANT_Utf8 cpIdxToUse = cpIdx; } else if (t == 7 || t == 8 || t == 19) { // t == 7 => CONSTANT_Class, e.g. "[[I", "[Ljava/lang/Thread;"; t == 8 => CONSTANT_String; // t == 19 => CONSTANT_Method_Info final int indirIdx = indirectStringRefs[cpIdx]; if (indirIdx == -1) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } if (indirIdx == 0) { // I assume this represents a null string, since the zeroeth entry is unused return 0; } cpIdxToUse = indirIdx; } else if (t == 12) { // CONSTANT_NameAndType_info final int compoundIndirIdx = indirectStringRefs[cpIdx]; if (compoundIndirIdx == -1) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final int indirIdx = (subFieldIdx == 0 ? (compoundIndirIdx >> 16) : compoundIndirIdx) & 0xffff; if (indirIdx == 0) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } cpIdxToUse = indirIdx; } else { throw new ClassfileFormatException("Wrong tag number " + t + " at constant pool index " + cpIdx + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); } if (cpIdxToUse < 1 || cpIdxToUse >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return entryOffset[cpIdxToUse]; } /** * Get a string from the constant pool, optionally replacing '/' with '.'. * * @param cpIdx * the constant pool index * @param replaceSlashWithDot * if true, replace slash with dot in the result. * @param stripLSemicolon * if true, strip 'L' from the beginning and ';' from the end before returning (for class reference * constants) * @return the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolString(final int cpIdx, final boolean replaceSlashWithDot, final boolean stripLSemicolon) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (constantPoolStringOffset == 0) { return null; } final int utfLen = reader.readUnsignedShort(constantPoolStringOffset); if (utfLen == 0) { return ""; } return intern( reader.readString(constantPoolStringOffset + 2L, utfLen, replaceSlashWithDot, stripLSemicolon)); } /** * Get a string from the constant pool. * * @param cpIdx * the constant pool index * @param subFieldIdx * should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for * CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1. * @return the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolString(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, subFieldIdx); if (constantPoolStringOffset == 0) { return null; } final int utfLen = reader.readUnsignedShort(constantPoolStringOffset); if (utfLen == 0) { return ""; } return intern(reader.readString(constantPoolStringOffset + 2L, utfLen, /* replaceSlashWithDot = */ false, /* stripLSemicolon = */ false)); } /** * Get a string from the constant pool. * * @param cpIdx * the constant pool index * @return the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolString(final int cpIdx) throws ClassfileFormatException, IOException { return getConstantPoolString(cpIdx, /* subFieldIdx = */ 0); } /** * Get the first UTF8 byte of a string in the constant pool, or '\0' if the string is null or empty. * * @param cpIdx * the constant pool index * @return the first byte of the constant pool string * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private byte getConstantPoolStringFirstByte(final int cpIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (constantPoolStringOffset == 0) { return '\0'; } final int utfLen = reader.readUnsignedShort(constantPoolStringOffset); if (utfLen == 0) { return '\0'; } return reader.readByte(constantPoolStringOffset + 2L); } /** * Get a string from the constant pool, and interpret it as a class name by replacing '/' with '.'. * * @param cpIdx * the constant pool index * @return the constant pool class name * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolClassName(final int cpIdx) throws ClassfileFormatException, IOException { return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ false); } /** * Get a string from the constant pool representing an internal string descriptor for a class name * ("Lcom/xyz/MyClass;"), and interpret it as a class name by replacing '/' with '.', and removing the leading * "L" and the trailing ";". * * @param cpIdx * the constant pool index * @return the constant pool class descriptor * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private String getConstantPoolClassDescriptor(final int cpIdx) throws ClassfileFormatException, IOException { return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ true); } /** * Compare a string in the constant pool with a given ASCII string, without constructing the constant pool * String object. * * @param cpIdx * the constant pool index * @param asciiStr * the ASCII string to compare to * @return true, if successful * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private boolean constantPoolStringEquals(final int cpIdx, final String asciiStr) throws ClassfileFormatException, IOException { final int cpStrOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (cpStrOffset == 0) { return asciiStr == null; } else if (asciiStr == null) { return false; } final int cpStrLen = reader.readUnsignedShort(cpStrOffset); final int asciiStrLen = asciiStr.length(); if (cpStrLen != asciiStrLen) { return false; } final int cpStrStart = cpStrOffset + 2; reader.bufferTo(cpStrStart + cpStrLen); final byte[] buf = reader.buf(); for (int i = 0; i < cpStrLen; i++) { if ((char) (buf[cpStrStart + i] & 0xff) != asciiStr.charAt(i)) { return false; } } return true; } /** * Read an unsigned short from the constant pool. * * @param cpIdx * the constant pool index. * @return the unsigned short * @throws IOException * If an I/O exception occurred. */ private int cpReadUnsignedShort(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return reader.readUnsignedShort(entryOffset[cpIdx]); } /** * Read an int from the constant pool. * * @param cpIdx * the constant pool index. * @return the int * @throws IOException * If an I/O exception occurred. */ private int cpReadInt(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return reader.readInt(entryOffset[cpIdx]); } /** * Read a long from the constant pool. * * @param cpIdx * the constant pool index. * @return the long * @throws IOException * If an I/O exception occurred. */ private long cpReadLong(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return reader.readLong(entryOffset[cpIdx]); } /** * Get a field constant from the constant pool. * * @param tag * the tag * @param fieldTypeDescriptorFirstChar * the first char of the field type descriptor * @param cpIdx * the constant pool index * @return the field constant pool value * @throws ClassfileFormatException * If a problem occurs. * @throws IOException * If an IO exception occurs. */ private Object getFieldConstantPoolValue(final int tag, final char fieldTypeDescriptorFirstChar, final int cpIdx) throws ClassfileFormatException, IOException { switch (tag) { case 1: // Modified UTF8 case 7: // Class -- N.B. Unused? Class references do not seem to actually be stored as constant initalizers case 8: // String // Forward or backward indirect reference to a modified UTF8 entry return getConstantPoolString(cpIdx); case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER final int intVal = cpReadInt(cpIdx); switch (fieldTypeDescriptorFirstChar) { case 'I': return intVal; case 'S': return (short) intVal; case 'C': return (char) intVal; case 'B': return (byte) intVal; case 'Z': return intVal != 0; default: // Fall through } throw new ClassfileFormatException("Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); case 4: // float return Float.intBitsToFloat(cpReadInt(cpIdx)); case 5: // long return cpReadLong(cpIdx); case 6: // double return Double.longBitsToDouble(cpReadLong(cpIdx)); default: // ClassGraph doesn't expect other types // (N.B. in particular, enum values are not stored in the constant pool, so don't need to be handled) throw new ClassfileFormatException("Unknown field constant pool tag " + tag + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); } } /** * Read annotation entry from classfile. * * @return the annotation, as an {@link AnnotationInfo} object. * @throws IOException * If an IO exception occurs. */ private AnnotationInfo readAnnotation() throws IOException { // Lcom/xyz/Annotation; -> Lcom.xyz.Annotation; final String annotationClassName = getConstantPoolClassDescriptor(reader.readUnsignedShort()); final int numElementValuePairs = reader.readUnsignedShort(); AnnotationParameterValueList paramVals = null; if (numElementValuePairs > 0) { paramVals = new AnnotationParameterValueList(numElementValuePairs); for (int i = 0; i < numElementValuePairs; i++) { final String paramName = getConstantPoolString(reader.readUnsignedShort()); final Object paramValue = readAnnotationElementValue(); paramVals.add(new AnnotationParameterValue(paramName, paramValue)); } } return new AnnotationInfo(annotationClassName, paramVals); } /** * Read annotation element value from classfile. * * @return the annotation element value * @throws IOException * If an IO exception occurs. */ private Object readAnnotationElementValue() throws IOException { final int tag = (char) reader.readUnsignedByte(); switch (tag) { case 'B': return (byte) cpReadInt(reader.readUnsignedShort()); case 'C': return (char) cpReadInt(reader.readUnsignedShort()); case 'D': return Double.longBitsToDouble(cpReadLong(reader.readUnsignedShort())); case 'F': return Float.intBitsToFloat(cpReadInt(reader.readUnsignedShort())); case 'I': return cpReadInt(reader.readUnsignedShort()); case 'J': return cpReadLong(reader.readUnsignedShort()); case 'S': return (short) cpReadUnsignedShort(reader.readUnsignedShort()); case 'Z': return cpReadInt(reader.readUnsignedShort()) != 0; case 's': return getConstantPoolString(reader.readUnsignedShort()); case 'e': { // Return type is AnnotationEnumVal. final String annotationClassName = getConstantPoolClassDescriptor(reader.readUnsignedShort()); final String annotationConstName = getConstantPoolString(reader.readUnsignedShort()); return new AnnotationEnumValue(annotationClassName, annotationConstName); } case 'c': // Return type is AnnotationClassRef (for class references in annotations) final String classRefTypeDescriptor = getConstantPoolString(reader.readUnsignedShort()); return new AnnotationClassRef(classRefTypeDescriptor); case '@': // Complex (nested) annotation. Return type is AnnotationInfo. return readAnnotation(); case '[': // Return type is Object[] (of nested annotation element values) final int count = reader.readUnsignedShort(); final Object[] arr = new Object[count]; for (int i = 0; i < count; ++i) { // Nested annotation element value arr[i] = readAnnotationElementValue(); } return arr; default: throw new ClassfileFormatException("Class " + className + " has unknown annotation element type tag '" + ((char) tag) + "': element size unknown, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } } static interface ClassTypeAnnotationDecorator { void decorate(ClassTypeSignature classTypeSignature); } static interface MethodTypeAnnotationDecorator { void decorate(MethodTypeSignature methodTypeSignature); } static interface TypeAnnotationDecorator { void decorate(TypeSignature typeSignature); } static class TypePathNode { short typePathKind; short typeArgumentIdx; public TypePathNode(final int typePathKind, final int typeArgumentIdx) { this.typePathKind = (short) typePathKind; this.typeArgumentIdx = (short) typeArgumentIdx; } @Override public String toString() { return "(" + typePathKind + "," + typeArgumentIdx + ")"; } } private List<TypePathNode> readTypePath() throws IOException { final int typePathLength = reader.readUnsignedByte(); if (typePathLength == 0) { return Collections.emptyList(); } else { final List<TypePathNode> list = new ArrayList<>(typePathLength); for (int i = 0; i < typePathLength; i++) { final int typePathKind = reader.readUnsignedByte(); final int typeArgumentIdx = reader.readUnsignedByte(); list.add(new TypePathNode(typePathKind, typeArgumentIdx)); } return list; } } /** * Read constant pool entries. * * @throws IOException * Signals that an I/O exception has occurred. */ private void readConstantPoolEntries() throws IOException { // Only record class dependency info if inter-class dependencies are enabled List<Integer> classNameCpIdxs = null; List<Integer> typeSignatureIdxs = null; if (scanSpec.enableInterClassDependencies) { classNameCpIdxs = new ArrayList<Integer>(); typeSignatureIdxs = new ArrayList<Integer>(); } // Read size of constant pool cpCount = reader.readUnsignedShort(); // Allocate storage for constant pool entryOffset = new int[cpCount]; entryTag = new int[cpCount]; indirectStringRefs = new int[cpCount]; Arrays.fill(indirectStringRefs, 0, cpCount, -1); // Read constant pool entries for (int i = 1, skipSlot = 0; i < cpCount; i++) { if (skipSlot == 1) { // Skip a slot (keeps Scrutinizer happy -- it doesn't like i++ in case 6) skipSlot = 0; continue; } entryTag[i] = reader.readUnsignedByte(); entryOffset[i] = reader.currPos(); switch (entryTag[i]) { case 0: // Impossible, probably buffer underflow throw new ClassfileFormatException("Invalid constant pool tag 0 in classfile " + relativePath + " (possible buffer underflow issue). Please report this at " + "https://github.com/classgraph/classgraph/issues"); case 1: // Modified UTF8 final int strLen = reader.readUnsignedShort(); reader.skip(strLen); break; // There is no constant pool tag type 2 case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER case 4: // float reader.skip(4); break; case 5: // long case 6: // double reader.skip(8); skipSlot = 1; // double slot break; case 7: // Class reference (format is e.g. "java/lang/String") // Forward or backward indirect reference to a modified UTF8 entry indirectStringRefs[i] = reader.readUnsignedShort(); if (classNameCpIdxs != null) { // If this is a class ref, and inter-class dependencies are enabled, record the dependency classNameCpIdxs.add(indirectStringRefs[i]); } break; case 8: // String // Forward or backward indirect reference to a modified UTF8 entry indirectStringRefs[i] = reader.readUnsignedShort(); break; case 9: // field ref // Refers to a class ref (case 7) and then a name and type (case 12) reader.skip(4); break; case 10: // method ref // Refers to a class ref (case 7) and then a name and type (case 12) reader.skip(4); break; case 11: // interface method ref // Refers to a class ref (case 7) and then a name and type (case 12) reader.skip(4); break; case 12: // name and type final int nameRef = reader.readUnsignedShort(); final int typeRef = reader.readUnsignedShort(); if (typeSignatureIdxs != null) { typeSignatureIdxs.add(typeRef); } indirectStringRefs[i] = (nameRef << 16) | typeRef; break; // There is no constant pool tag type 13 or 14 case 15: // method handle reader.skip(3); break; case 16: // method type reader.skip(2); break; case 17: // dynamic reader.skip(4); break; case 18: // invoke dynamic reader.skip(4); break; case 19: // module (for module-info.class in JDK9+) // see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4 indirectStringRefs[i] = reader.readUnsignedShort(); break; case 20: // package (for module-info.class in JDK9+) // see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4 reader.skip(2); break; default: throw new ClassfileFormatException("Unknown constant pool tag " + entryTag[i] + " (element size unknown, cannot continue reading class). Please report this at " + "https://github.com/classgraph/classgraph/issues"); } } // Find classes referenced in the constant pool. Note that there are some class refs that will not be // found this way, e.g. enum classes and class refs in annotation parameter values, since they are // referenced as strings (tag 1) rather than classes (tag 7) or type signatures (part of tag 12). // Therefore, a hybrid approach needs to be applied of extracting these other class refs from // the ClassInfo graph, and combining them with class names extracted from the constant pool here. if (classNameCpIdxs != null) { refdClassNames = new HashSet<>(); // Get class names from direct class references in constant pool for (final int cpIdx : classNameCpIdxs) { final String refdClassName = getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ false); if (refdClassName != null) { if (refdClassName.startsWith("[")) { // Parse array type signature, e.g. "[Ljava.lang.String;" -- uses '.' rather than '/' try { final TypeSignature typeSig = TypeSignature.parse(refdClassName.replace('.', '/'), /* definingClass = */ null); typeSig.findReferencedClassNames(refdClassNames); } catch (final ParseException e) { // Should not happen throw new ClassfileFormatException("Could not parse class name: " + refdClassName, e); } } else { refdClassNames.add(refdClassName); } } } } if (typeSignatureIdxs != null) { // Get class names from type signatures in "name and type" entries in constant pool for (final int cpIdx : typeSignatureIdxs) { final String typeSigStr = getConstantPoolString(cpIdx); if (typeSigStr != null) { try { if (typeSigStr.indexOf('(') >= 0 || "<init>".equals(typeSigStr)) { // Parse the type signature final MethodTypeSignature typeSig = MethodTypeSignature.parse(typeSigStr, /* definingClassName = */ null); // Extract class names from type signature typeSig.findReferencedClassNames(refdClassNames); } else { // Parse the type signature final TypeSignature typeSig = TypeSignature.parse(typeSigStr, /* definingClassName = */ null); // Extract class names from type signature typeSig.findReferencedClassNames(refdClassNames); } } catch (final ParseException e) { throw new ClassfileFormatException("Could not parse type signature: " + typeSigStr, e); } } } } } /** * Read basic class information. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. * @throws SkipClassException * if the classfile needs to be skipped (e.g. the class is non-public, and ignoreClassVisibility is * false) */ private void readBasicClassInfo() throws IOException, ClassfileFormatException, SkipClassException { // Modifier flags classModifiers = reader.readUnsignedShort(); isInterface = (classModifiers & 0x0200) != 0; isAnnotation = (classModifiers & 0x2000) != 0; // The fully-qualified class name of this class, with slashes replaced with dots final String classNamePath = getConstantPoolString(reader.readUnsignedShort()); if (classNamePath == null) { throw new ClassfileFormatException("Class name is null"); } className = classNamePath.replace('/', '.'); if ("java.lang.Object".equals(className)) { // Don't process java.lang.Object (it has a null superclass), though you can still search for classes // that are subclasses of java.lang.Object (as an external class). throw new SkipClassException("No need to scan java.lang.Object"); } // Check class visibility modifiers final boolean isModule = (classModifiers & 0x8000) != 0; // Equivalently filename is "module-info.class" final boolean isPackage = relativePath.regionMatches(relativePath.lastIndexOf('/') + 1, "package-info.class", 0, 18); if (!scanSpec.ignoreClassVisibility && !Modifier.isPublic(classModifiers) && !isModule && !isPackage) { throw new SkipClassException("Class is not public, and ignoreClassVisibility() was not called"); } // Make sure classname matches relative path if (!relativePath.endsWith(".class")) { // Should not happen throw new SkipClassException("Classfile filename " + relativePath + " does not end in \".class\""); } final int len = classNamePath.length(); if (relativePath.length() != len + 6 || !classNamePath.regionMatches(0, relativePath, 0, len)) { throw new SkipClassException( "Relative path " + relativePath + " does not match class name " + className); } // Superclass name, with slashes replaced with dots final int superclassNameCpIdx = reader.readUnsignedShort(); if (superclassNameCpIdx > 0) { superclassName = getConstantPoolClassName(superclassNameCpIdx); } } /** * Read the class' interfaces. * * @throws IOException * if an I/O exception occurs. */ private void readInterfaces() throws IOException { // Interfaces final int interfaceCount = reader.readUnsignedShort(); for (int i = 0; i < interfaceCount; i++) { final String interfaceName = getConstantPoolClassName(reader.readUnsignedShort()); if (implementedInterfaces == null) { implementedInterfaces = new ArrayList<>(); } implementedInterfaces.add(interfaceName); } } /** * Read the class' fields. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. */ private void readFields() throws IOException, ClassfileFormatException { // Fields final int fieldCount = reader.readUnsignedShort(); for (int i = 0; i < fieldCount; i++) { // Info on modifier flags: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.5 final int fieldModifierFlags = reader.readUnsignedShort(); final boolean isPublicField = ((fieldModifierFlags & 0x0001) == 0x0001); final boolean fieldIsVisible = isPublicField || scanSpec.ignoreFieldVisibility; final boolean getStaticFinalFieldConstValue = scanSpec.enableStaticFinalFieldConstantInitializerValues && fieldIsVisible; List<TypeAnnotationDecorator> fieldTypeAnnotationDecorators = null; if (!fieldIsVisible || (!scanSpec.enableFieldInfo && !getStaticFinalFieldConstValue)) { // Skip field reader.readUnsignedShort(); // fieldNameCpIdx reader.readUnsignedShort(); // fieldTypeDescriptorCpIdx final int attributesCount = reader.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { reader.readUnsignedShort(); // attributeNameCpIdx final int attributeLength = reader.readInt(); reader.skip(attributeLength); } } else { final int fieldNameCpIdx = reader.readUnsignedShort(); final String fieldName = getConstantPoolString(fieldNameCpIdx); final int fieldTypeDescriptorCpIdx = reader.readUnsignedShort(); final char fieldTypeDescriptorFirstChar = (char) getConstantPoolStringFirstByte( fieldTypeDescriptorCpIdx); String fieldTypeDescriptor; String fieldTypeSignatureStr = null; fieldTypeDescriptor = getConstantPoolString(fieldTypeDescriptorCpIdx); Object fieldConstValue = null; AnnotationInfoList fieldAnnotationInfo = null; final int attributesCount = reader.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { final int attributeNameCpIdx = reader.readUnsignedShort(); final int attributeLength = reader.readInt(); // See if field name matches one of the requested names for this class, and if it does, // check if it is initialized with a constant value if ((getStaticFinalFieldConstValue) && constantPoolStringEquals(attributeNameCpIdx, "ConstantValue")) { // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2 final int cpIdx = reader.readUnsignedShort(); if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } fieldConstValue = getFieldConstantPoolValue(entryTag[cpIdx], fieldTypeDescriptorFirstChar, cpIdx); } else if (fieldIsVisible && constantPoolStringEquals(attributeNameCpIdx, "Signature")) { fieldTypeSignatureStr = getConstantPoolString(reader.readUnsignedShort()); } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { // Read annotation names final int fieldAnnotationCount = reader.readUnsignedShort(); if (fieldAnnotationCount > 0) { if (fieldAnnotationInfo == null) { fieldAnnotationInfo = new AnnotationInfoList(1); } for (int k = 0; k < fieldAnnotationCount; k++) { final AnnotationInfo fieldAnnotation = readAnnotation(); fieldAnnotationInfo.add(fieldAnnotation); } } } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleTypeAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleTypeAnnotations")))) { final int annotationCount = reader.readUnsignedShort(); if (annotationCount > 0) { fieldTypeAnnotationDecorators = new ArrayList<>(); for (int m = 0; m < annotationCount; m++) { final int targetType = reader.readUnsignedByte(); if (targetType != 0x13) { throw new ClassfileFormatException( "Class " + className + " has unknown field type annotation target 0x" + Integer.toHexString(targetType) + ": element size unknown, cannot continue reading class. " + "Please report this at " + "https://github.com/classgraph/classgraph/issues"); } final List<TypePathNode> typePath = readTypePath(); final AnnotationInfo annotationInfo = readAnnotation(); fieldTypeAnnotationDecorators.add(new TypeAnnotationDecorator() { @Override public void decorate(final TypeSignature typeSignature) { typeSignature.addTypeAnnotation(typePath, annotationInfo); } }); } } } else { // No match, just skip attribute reader.skip(attributeLength); } } if (scanSpec.enableFieldInfo && fieldIsVisible) { if (fieldInfoList == null) { fieldInfoList = new FieldInfoList(); } fieldInfoList.add(new FieldInfo(className, fieldName, fieldModifierFlags, fieldTypeDescriptor, fieldTypeSignatureStr, fieldConstValue, fieldAnnotationInfo, fieldTypeAnnotationDecorators)); } } } } /** * Read the class' methods. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. */ private void readMethods() throws IOException, ClassfileFormatException { // Methods final int methodCount = reader.readUnsignedShort(); for (int i = 0; i < methodCount; i++) { // Info on modifier flags: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.6 final int methodModifierFlags = reader.readUnsignedShort(); final boolean isPublicMethod = ((methodModifierFlags & 0x0001) == 0x0001); final boolean methodIsVisible = isPublicMethod || scanSpec.ignoreMethodVisibility; List<MethodTypeAnnotationDecorator> methodTypeAnnotationDecorators = null; String methodName = null; String methodTypeDescriptor = null; String methodTypeSignatureStr = null; // Always enable MethodInfo for annotations (this is how annotation constants are defined) final boolean enableMethodInfo = scanSpec.enableMethodInfo || isAnnotation; if (enableMethodInfo || isAnnotation) { // Annotations store defaults in method_info final int methodNameCpIdx = reader.readUnsignedShort(); methodName = getConstantPoolString(methodNameCpIdx); final int methodTypeDescriptorCpIdx = reader.readUnsignedShort(); methodTypeDescriptor = getConstantPoolString(methodTypeDescriptorCpIdx); } else { reader.skip(4); // name_index, descriptor_index } final int attributesCount = reader.readUnsignedShort(); String[] methodParameterNames = null; int[] methodParameterModifiers = null; AnnotationInfo[][] methodParameterAnnotations = null; AnnotationInfoList methodAnnotationInfo = null; boolean methodHasBody = false; if (!methodIsVisible || (!enableMethodInfo && !isAnnotation)) { // Skip method attributes for (int j = 0; j < attributesCount; j++) { reader.skip(2); // attribute_name_index final int attributeLength = reader.readInt(); reader.skip(attributeLength); } } else { // Look for method annotations for (int j = 0; j < attributesCount; j++) { final int attributeNameCpIdx = reader.readUnsignedShort(); final int attributeLength = reader.readInt(); if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { final int methodAnnotationCount = reader.readUnsignedShort(); if (methodAnnotationCount > 0) { if (methodAnnotationInfo == null) { methodAnnotationInfo = new AnnotationInfoList(1); } for (int k = 0; k < methodAnnotationCount; k++) { final AnnotationInfo annotationInfo = readAnnotation(); methodAnnotationInfo.add(annotationInfo); } } } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleParameterAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleParameterAnnotations")))) { // Merge together runtime visible and runtime invisible annotations into a single array // of annotations for each method parameter (runtime visible and runtime invisible // annotations are given in separate attributes, so if both attributes are present, // have to make the parameter annotation arrays larger when the second attribute is // encountered). final int numParams = reader.readUnsignedByte(); if (methodParameterAnnotations == null) { methodParameterAnnotations = new AnnotationInfo[numParams][]; } else if (methodParameterAnnotations.length != numParams) { throw new ClassfileFormatException( "Mismatch in number of parameters between RuntimeVisibleParameterAnnotations " + "and RuntimeInvisibleParameterAnnotations"); } for (int paramIdx = 0; paramIdx < numParams; paramIdx++) { final int numAnnotations = reader.readUnsignedShort(); if (numAnnotations > 0) { int annStartIdx = 0; if (methodParameterAnnotations[paramIdx] != null) { annStartIdx = methodParameterAnnotations[paramIdx].length; methodParameterAnnotations[paramIdx] = Arrays.copyOf( methodParameterAnnotations[paramIdx], annStartIdx + numAnnotations); } else { methodParameterAnnotations[paramIdx] = new AnnotationInfo[numAnnotations]; } for (int annIdx = 0; annIdx < numAnnotations; annIdx++) { methodParameterAnnotations[paramIdx][annStartIdx + annIdx] = readAnnotation(); } } else if (methodParameterAnnotations[paramIdx] == null) { methodParameterAnnotations[paramIdx] = NO_ANNOTATIONS; } } } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleTypeAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleTypeAnnotations")))) { final int annotationCount = reader.readUnsignedShort(); if (annotationCount > 0) { methodTypeAnnotationDecorators = new ArrayList<>(annotationCount); for (int m = 0; m < annotationCount; m++) { final int targetType = reader.readUnsignedByte(); final int typeParameterIndex; final int boundIndex; final int formalParameterIndex; final int throwsTypeIndex; if (targetType == 0x01) { typeParameterIndex = reader.readUnsignedByte(); boundIndex = -1; formalParameterIndex = -1; throwsTypeIndex = -1; } else if (targetType == 0x12) { typeParameterIndex = reader.readUnsignedByte(); boundIndex = reader.readUnsignedByte(); formalParameterIndex = -1; throwsTypeIndex = -1; } else if (targetType == 0x14) { typeParameterIndex = -1; boundIndex = -1; formalParameterIndex = -1; throwsTypeIndex = -1; } else if (targetType == 0x15) { typeParameterIndex = -1; boundIndex = -1; formalParameterIndex = -1; throwsTypeIndex = -1; } else if (targetType == 0x16) { formalParameterIndex = reader.readUnsignedByte(); typeParameterIndex = -1; boundIndex = -1; throwsTypeIndex = -1; } else if (targetType == 0x17) { throwsTypeIndex = reader.readUnsignedShort(); typeParameterIndex = -1; boundIndex = -1; formalParameterIndex = -1; } else { throw new ClassfileFormatException( "Class " + className + " has unknown method type annotation target 0x" + Integer.toHexString(targetType) + ": element size unknown, cannot continue reading class. " + "Please report this at " + "https://github.com/classgraph/classgraph/issues"); } final List<TypePathNode> typePath = readTypePath(); final AnnotationInfo annotationInfo = readAnnotation(); methodTypeAnnotationDecorators.add(new MethodTypeAnnotationDecorator() { @Override public void decorate(final MethodTypeSignature methodTypeSignature) { if (targetType == 0x01) { // Type parameter declaration of generic method or constructor final List<TypeParameter> typeParameters = methodTypeSignature .getTypeParameters(); if (typeParameters != null && typeParameterIndex < typeParameters.size()) { typeParameters.get(typeParameterIndex).addTypeAnnotation(typePath, annotationInfo); } // else this is a method type descriptor, not a method type signature, // so there are no type parameters } else if (targetType == 0x12) { // Type in bound of type parameter declaration of generic method or // constructor final List<TypeParameter> typeParameters = methodTypeSignature .getTypeParameters(); if (typeParameters != null && typeParameterIndex < typeParameters.size()) { final TypeParameter typeParameter = typeParameters .get(typeParameterIndex); // boundIndex == 0 => class bound; boundIndex > 0 => interface bound if (boundIndex == 0) { final ReferenceTypeSignature classBound = typeParameter .getClassBound(); if (classBound != null) { classBound.addTypeAnnotation(typePath, annotationInfo); } } else { final List<ReferenceTypeSignature> interfaceBounds = typeParameter.getInterfaceBounds(); if (interfaceBounds != null && boundIndex - 1 < interfaceBounds.size()) { interfaceBounds.get(boundIndex - 1) .addTypeAnnotation(typePath, annotationInfo); } } } // else this is a method type descriptor, not a method type signature, // so there are no type parameters } else if (targetType == 0x14) { // Return type of method, or type of newly constructed object methodTypeSignature.getResultType().addTypeAnnotation(typePath, annotationInfo); } else if (targetType == 0x15) { // Receiver type of method or constructor (explicit receiver parameter) methodTypeSignature.addRecieverTypeAnnotation(annotationInfo); } else if (targetType == 0x16) { // Type in formal parameter declaration of method, constructor, // or lambda expression // N.B. formal parameter indices are dodgy, because not all compilers // index parameters the same way -- so be robust here final List<TypeSignature> parameterTypeSignatures = methodTypeSignature .getParameterTypeSignatures(); if (formalParameterIndex < parameterTypeSignatures.size()) { parameterTypeSignatures.get(formalParameterIndex) .addTypeAnnotation(typePath, annotationInfo); } } else if (targetType == 0x17) { // Type in throws clause of method or constructor final List<ClassRefOrTypeVariableSignature> throwsSignatures = methodTypeSignature.getThrowsSignatures(); if (throwsSignatures != null && throwsTypeIndex < throwsSignatures.size()) { throwsSignatures.get(throwsTypeIndex).addTypeAnnotation(typePath, annotationInfo); } } } }); } } } else if (constantPoolStringEquals(attributeNameCpIdx, "MethodParameters")) { // Read method parameters. For Java, these are only produced in JDK8+, and only if the // commandline switch `-parameters` is provided at compiletime. final int paramCount = reader.readUnsignedByte(); methodParameterNames = new String[paramCount]; methodParameterModifiers = new int[paramCount]; for (int k = 0; k < paramCount; k++) { final int cpIdx = reader.readUnsignedShort(); // If the constant pool index is zero, then the parameter is unnamed => use null methodParameterNames[k] = cpIdx == 0 ? null : getConstantPoolString(cpIdx); methodParameterModifiers[k] = reader.readUnsignedShort(); } } else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) { // Add type params to method type signature methodTypeSignatureStr = getConstantPoolString(reader.readUnsignedShort()); } else if (constantPoolStringEquals(attributeNameCpIdx, "AnnotationDefault")) { if (annotationParamDefaultValues == null) { annotationParamDefaultValues = new AnnotationParameterValueList(); } this.annotationParamDefaultValues.add(new AnnotationParameterValue(methodName, // Get annotation parameter default value readAnnotationElementValue())); } else if (constantPoolStringEquals(attributeNameCpIdx, "Code")) { methodHasBody = true; reader.skip(attributeLength); } else { reader.skip(attributeLength); } } // Create MethodInfo if (enableMethodInfo) { if (methodInfoList == null) { methodInfoList = new MethodInfoList(); } methodInfoList.add(new MethodInfo(className, methodName, methodAnnotationInfo, methodModifierFlags, methodTypeDescriptor, methodTypeSignatureStr, methodParameterNames, methodParameterModifiers, methodParameterAnnotations, methodHasBody, methodTypeAnnotationDecorators)); } } } } /** * Read class attributes. * * @throws IOException * if an I/O exception occurs. * @throws ClassfileFormatException * if the classfile is incorrectly formatted. */ private void readClassAttributes() throws IOException, ClassfileFormatException { // Class attributes (including class annotations, class type variables, module info, etc.) final int attributesCount = reader.readUnsignedShort(); for (int i = 0; i < attributesCount; i++) { final int attributeNameCpIdx = reader.readUnsignedShort(); final int attributeLength = reader.readInt(); if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { final int annotationCount = reader.readUnsignedShort(); if (annotationCount > 0) { if (classAnnotations == null) { classAnnotations = new AnnotationInfoList(); } for (int m = 0; m < annotationCount; m++) { classAnnotations.add(readAnnotation()); } } } else if (scanSpec.enableAnnotationInfo && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleTypeAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleTypeAnnotations")))) { final int annotationCount = reader.readUnsignedShort(); if (annotationCount > 0) { classTypeAnnotationDecorators = new ArrayList<>(annotationCount); for (int m = 0; m < annotationCount; m++) { final int targetType = reader.readUnsignedByte(); final int typeParameterIndex; final int supertypeIndex; final int boundIndex; if (targetType == 0x00) { typeParameterIndex = reader.readUnsignedByte(); supertypeIndex = -1; boundIndex = -1; } else if (targetType == 0x10) { supertypeIndex = reader.readUnsignedShort(); typeParameterIndex = -1; boundIndex = -1; } else if (targetType == 0x11) { typeParameterIndex = reader.readUnsignedByte(); boundIndex = reader.readUnsignedByte(); supertypeIndex = -1; } else { throw new ClassfileFormatException("Class " + className + " has unknown class type annotation target 0x" + Integer.toHexString(targetType) + ": element size unknown, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final List<TypePathNode> typePath = readTypePath(); final AnnotationInfo annotationInfo = readAnnotation(); classTypeAnnotationDecorators.add(new ClassTypeAnnotationDecorator() { @Override public void decorate(final ClassTypeSignature classTypeSignature) { if (targetType == 0x00) { // Type parameter declaration of generic class or interface final List<TypeParameter> typeParameters = classTypeSignature .getTypeParameters(); if (typeParameters != null && typeParameterIndex < typeParameters.size()) { typeParameters.get(typeParameterIndex).addTypeAnnotation(typePath, annotationInfo); } } else if (targetType == 0x10) { if (supertypeIndex == 65535) { // Type in extends clause of class declaration classTypeSignature.getSuperclassSignature().addTypeAnnotation(typePath, annotationInfo); } else { // Type in implements clause of interface declaration classTypeSignature.getSuperinterfaceSignatures().get(supertypeIndex) .addTypeAnnotation(typePath, annotationInfo); } } else if (targetType == 0x11) { // Type in bound of type parameter declaration of generic class or interface final List<TypeParameter> typeParameters = classTypeSignature .getTypeParameters(); if (typeParameters != null && typeParameterIndex < typeParameters.size()) { final TypeParameter typeParameter = typeParameters.get(typeParameterIndex); // boundIndex == 0 => class bound; boundIndex > 0 => interface bound if (boundIndex == 0) { final ReferenceTypeSignature classBound = typeParameter.getClassBound(); if (classBound != null) { classBound.addTypeAnnotation(typePath, annotationInfo); } } else { final List<ReferenceTypeSignature> interfaceBounds = typeParameter .getInterfaceBounds(); if (interfaceBounds != null && boundIndex - 1 < interfaceBounds.size()) { typeParameter.getInterfaceBounds().get(boundIndex - 1) .addTypeAnnotation(typePath, annotationInfo); } } } } } }); } } } else if (constantPoolStringEquals(attributeNameCpIdx, "Record")) { isRecord = true; // No need to read record_components_info entries -- there is a 1:1 correspondence between // record components and fields/methods of the same name and type as the record component, // so we can just rely on the field and method reading code to work correctly with records. reader.skip(attributeLength); } else if (constantPoolStringEquals(attributeNameCpIdx, "InnerClasses")) { final int numInnerClasses = reader.readUnsignedShort(); for (int j = 0; j < numInnerClasses; j++) { final int innerClassInfoCpIdx = reader.readUnsignedShort(); final int outerClassInfoCpIdx = reader.readUnsignedShort(); reader.skip(2); // inner_name_idx final int innerClassAccessFlags = reader.readUnsignedShort(); if (innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0) { final String innerClassName = getConstantPoolClassName(innerClassInfoCpIdx); final String outerClassName = getConstantPoolClassName(outerClassInfoCpIdx); if (innerClassName == null || outerClassName == null) { // Should not happen (fix static analyzer warning) throw new ClassfileFormatException("Inner and/or outer class name is null"); } if (innerClassName.equals(outerClassName)) { // Invalid according to spec throw new ClassfileFormatException("Inner and outer class name cannot be the same"); } // Record types have a Lookup inner class for boostrap methods in JDK 14 -- drop this if (!("java.lang.invoke.MethodHandles$Lookup".equals(innerClassName) && "java.lang.invoke.MethodHandles".equals(outerClassName))) { // Store relationship between inner class and outer class if (classContainmentEntries == null) { classContainmentEntries = new ArrayList<>(); } classContainmentEntries.add( new ClassContainment(innerClassName, innerClassAccessFlags, outerClassName)); } } } } else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) { // Get class type signature, including type variables typeSignatureStr = getConstantPoolString(reader.readUnsignedShort()); } else if (constantPoolStringEquals(attributeNameCpIdx, "EnclosingMethod")) { final String innermostEnclosingClassName = getConstantPoolClassName(reader.readUnsignedShort()); final int enclosingMethodCpIdx = reader.readUnsignedShort(); String definingMethodName; if (enclosingMethodCpIdx == 0) { // A cpIdx of 0 (which is an invalid value) is used for anonymous inner classes declared in // class initializer code, e.g. assigned to a class field. definingMethodName = "<clinit>"; } else { definingMethodName = getConstantPoolString(enclosingMethodCpIdx, /* subFieldIdx = */ 0); // Could also fetch method type signature using subFieldIdx = 1, if needed } // Link anonymous inner classes into the class with their containing method if (classContainmentEntries == null) { classContainmentEntries = new ArrayList<>(); } classContainmentEntries .add(new ClassContainment(className, classModifiers, innermostEnclosingClassName)); // Also store the fully-qualified name of the enclosing method, to mark this as an anonymous inner // class this.fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName; } else if (constantPoolStringEquals(attributeNameCpIdx, "Module")) { final int moduleNameCpIdx = reader.readUnsignedShort(); classpathElement.moduleNameFromModuleDescriptor = getConstantPoolString(moduleNameCpIdx); // (Future work): parse the rest of the module descriptor fields, and add to ModuleInfo: // https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25 reader.skip(attributeLength - 2); } else { reader.skip(attributeLength); } } } /** * Directly examine contents of classfile binary header to determine annotations, implemented interfaces, the * super-class etc. Creates a new ClassInfo object, and adds it to classNameToClassInfoOut. Assumes classpath * masking has already been performed, so that only one class of a given name will be added. * * @param classpathElement * the classpath element * @param classpathOrder * the classpath order * @param acceptedClassNamesFound * the names of accepted classes found in the classpath while scanning paths within classpath * elements. * @param classNamesScheduledForExtendedScanning * the names of external (non-accepted) classes scheduled for extended scanning (where scanning is * extended upwards to superclasses, interfaces and annotations). * @param relativePath * the relative path * @param classfileResource * the classfile resource * @param isExternalClass * if this is an external class * @param stringInternMap * the string intern map * @param workQueue * the work queue * @param scanSpec * the scan spec * @param log * the log * @throws IOException * If an IO exception occurs. * @throws ClassfileFormatException * If a problem occurs while parsing the classfile. * @throws SkipClassException * if the classfile needs to be skipped (e.g. the class is non-public, and ignoreClassVisibility is * false) */ Classfile(final ClasspathElement classpathElement, final List<ClasspathElement> classpathOrder, final Set<String> acceptedClassNamesFound, final Set<String> classNamesScheduledForExtendedScanning, final String relativePath, final Resource classfileResource, final boolean isExternalClass, final ConcurrentHashMap<String, String> stringInternMap, final WorkQueue<ClassfileScanWorkUnit> workQueue, final ScanSpec scanSpec, final LogNode log) throws IOException, ClassfileFormatException, SkipClassException { this.classpathElement = classpathElement; this.classpathOrder = classpathOrder; this.relativePath = relativePath; this.acceptedClassNamesFound = acceptedClassNamesFound; this.classNamesScheduledForExtendedScanning = classNamesScheduledForExtendedScanning; this.classfileResource = classfileResource; this.isExternalClass = isExternalClass; this.stringInternMap = stringInternMap; this.scanSpec = scanSpec; try { // Open a BufferedSequentialReader for the classfile reader = classfileResource.openClassfile(); // Check magic number if (reader.readInt() != 0xCAFEBABE) { throw new ClassfileFormatException("Classfile does not have correct magic number"); } // Read classfile minor and major version minorVersion = reader.readUnsignedShort(); majorVersion = reader.readUnsignedShort(); // Read the constant pool readConstantPoolEntries(); // Read basic class info ( readBasicClassInfo(); // Read interfaces readInterfaces(); // Read fields readFields(); // Read methods readMethods(); // Read class attributes readClassAttributes(); } finally { // Close BufferedSequentialReader classfileResource.close(); reader = null; } // Write class info to log final LogNode subLog = log == null ? null : log.log("Found " + (isAnnotation ? "annotation class" : isInterface ? "interface class" : "class") + " " + className); if (subLog != null) { if (superclassName != null) { subLog.log( "Super" + (isInterface && !isAnnotation ? "interface" : "class") + ": " + superclassName); } if (implementedInterfaces != null) { subLog.log("Interfaces: " + StringUtils.join(", ", implementedInterfaces)); } if (classAnnotations != null) { subLog.log("Class annotations: " + StringUtils.join(", ", classAnnotations)); } if (annotationParamDefaultValues != null) { for (final AnnotationParameterValue apv : annotationParamDefaultValues) { subLog.log("Annotation default param value: " + apv); } } if (fieldInfoList != null) { for (final FieldInfo fieldInfo : fieldInfoList) { final String modifierStr = fieldInfo.getModifiersStr(); subLog.log("Field: " + modifierStr + (modifierStr.isEmpty() ? "" : " ") + fieldInfo.getName()); } } if (methodInfoList != null) { for (final MethodInfo methodInfo : methodInfoList) { final String modifierStr = methodInfo.getModifiersStr(); subLog.log( "Method: " + modifierStr + (modifierStr.isEmpty() ? "" : " ") + methodInfo.getName()); } } if (typeSignatureStr != null) { subLog.log("Class type signature: " + typeSignatureStr); } if (refdClassNames != null) { final List<String> refdClassNamesSorted = new ArrayList<>(refdClassNames); CollectionUtils.sortIfNotEmpty(refdClassNamesSorted); subLog.log("Additional referenced class names: " + StringUtils.join(", ", refdClassNamesSorted)); } } // Check if any superclasses, interfaces or annotations are external (non-accepted) classes // that need to be scheduled for scanning, so that all of the "upwards" direction of the class // graph is scanned for any accepted class, even if the superclasses / interfaces / annotations // are not themselves accepted. if (scanSpec.extendScanningUpwardsToExternalClasses) { extendScanningUpwards(subLog); // If any external classes were found, schedule them for scanning if (additionalWorkUnits != null) { workQueue.addWorkUnits(additionalWorkUnits); } } } }
package gov.nih.nci.cananolab.util; import java.util.HashMap; import java.util.Map; public class Constants { public static final String DOMAIN_MODEL_NAME = "caNanoLab"; public static final String SDK_BEAN_JAR = "caNanoLabSDK-beans.jar"; public static final String CSM_APP_NAME = "caNanoLab"; public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy"; // File upload public static final String FILEUPLOAD_PROPERTY = "caNanoLab.properties"; public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles"; public static final String EMPTY = "N/A"; // caNanoLab property file public static final String CANANOLAB_PROPERTY = "caNanoLab.properties"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String DEFAULT_SAMPLE_PREFIX = "NANO-"; public static final String DEFAULT_APP_OWNER = "NCICB"; public static final String APP_OWNER; public static final String VIEW_COL_DELIMITER = "~~~"; public static final String VIEW_CLASSNAME_DELIMITER = "!!!"; static { String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY, "applicationOwner").trim(); if (appOwner == null || appOwner.length() == 0) appOwner = DEFAULT_APP_OWNER; APP_OWNER = appOwner; } public static final String SAMPLE_PREFIX; static { String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY, "samplePrefix"); if (samplePrefix == null || samplePrefix.length() == 0) samplePrefix = DEFAULT_SAMPLE_PREFIX; SAMPLE_PREFIX = samplePrefix; } public static final String GRID_INDEX_SERVICE_URL; static { String gridIndexServiceURL = PropertyReader.getProperty( CANANOLAB_PROPERTY, "gridIndexServiceURL").trim(); GRID_INDEX_SERVICE_URL = gridIndexServiceURL; } /* * The following Strings are nano specific * */ public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER }; public static final String ASSOCIATED_FILE = "Other Associated File"; public static final String PROTOCOL_FILE = "Protocol File"; public static final String FOLDER_PARTICLE = "particles"; // public static final String FOLDER_REPORT = "reports"; public static final String FOLDER_PUBLICATION = "publications"; public static final String FOLDER_PROTOCOL = "protocols"; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final int MAX_VIEW_TITLE_LENGTH = 23; public static final String CSM_DATA_CURATOR = APP_OWNER + "_DataCurator"; public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher"; public static final String CSM_ADMIN = APP_OWNER + "_Administrator"; public static final String CSM_PUBLIC_GROUP = "Public"; public static final String[] VISIBLE_GROUPS = new String[] { CSM_DATA_CURATOR, CSM_RESEARCHER }; public static final String AUTO_COPY_ANNOTATION_PREFIX = "COPY"; public static final String AUTO_COPY_ANNNOTATION_VIEW_COLOR = "red"; public static final String CSM_READ_ROLE = "R"; public static final String CSM_DELETE_ROLE = "D"; public static final String CSM_EXECUTE_ROLE = "E"; public static final String CSM_CURD_ROLE = "CURD"; public static final String CSM_CUR_ROLE = "CUR"; public static final String CSM_READ_PRIVILEGE = "READ"; public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE"; public static final String CSM_DELETE_PRIVILEGE = "DELETE"; public static final String CSM_CREATE_PRIVILEGE = "CREATE"; public static final String CSM_PG_PROTOCOL = "protocol"; public static final String CSM_PG_PARTICLE = "nanoparticle"; public static final String CSM_PG_PUBLICATION = "publication"; public static final String PHYSICAL_CHARACTERIZATION_CLASS_NAME = "Physical Characterization"; public static final String IN_VITRO_CHARACTERIZATION_CLASS_NAME = "In Vitro Characterization"; public static final short CHARACTERIZATION_ROOT_DISPLAY_ORDER = 0; public static final Map<String, Integer> CHARACTERIZATION_ORDER_MAP = new HashMap<String, Integer>(); static { CHARACTERIZATION_ORDER_MAP.put(new String("Physical Characterization"), new Integer(0)); CHARACTERIZATION_ORDER_MAP.put(new String("In Vitro Characterization"), new Integer(1)); CHARACTERIZATION_ORDER_MAP.put(new String("Toxicity"), new Integer(2)); CHARACTERIZATION_ORDER_MAP.put(new String("Cytotoxicity"), new Integer( 3)); CHARACTERIZATION_ORDER_MAP.put(new String("Immunotoxicity"), new Integer(4)); CHARACTERIZATION_ORDER_MAP.put(new String("Blood Contact"), new Integer(5)); CHARACTERIZATION_ORDER_MAP.put(new String("Immune Cell Function"), new Integer(6)); } /* image file name extension */ public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN", "DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE", "JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD", "PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD", "RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM", "YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG", "STD", "SVG", "SXD", "WMF" }; public static final String[] PRIVATE_DISPATCHES = { "create", "delete", "setupUpdate", "setupDeleteAll", "add", "remove" }; public static final String PHYSICOCHEMICAL_ASSAY_PROTOCOL = "physico-chemical assay"; public static final String INVITRO_ASSAY_PROTOCOL = "in vitro assay"; public static final String NODE_UNAVAILABLE = "Unable to connect to the grid location that you selected"; // default discovery internal for grid index server public static final int DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS = 20; public static final String DOMAIN_MODEL_VERSION = "1.4"; public static final String GRID_SERVICE_PATH = "wsrf-canano/services/cagrid/CaNanoLabService"; // Default date format for exported file name. public static final String EXPORT_FILE_DATE_FORMAT = "yyyyMMdd_HH-mm-ss-SSS"; // String for local search. public static final String LOCAL = "local"; }
package io.sigpipe.sing.stat; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import org.ejml.simple.SimpleMatrix; import de.tuhh.luethke.okde.model.SampleModel; public class OnlineKDE { public static void main(String[] args) throws Exception { OnlineKDE test = new OnlineKDE(); } public OnlineKDE() throws Exception { List<Double> temperatures = new ArrayList<>(); BufferedReader br = new BufferedReader( new FileReader("temperatures.txt")); String line; while ((line = br.readLine()) != null) { temperatures.add(Double.parseDouble(line)); } System.out.println("Samples: " + temperatures.size()); // disable the forgetting factor double forgettingFactor = 1; // set the compression threshold double compressionThreshold = 0.02; // sample model object used for sample distribution estimation SampleModel sampleDistribution = new SampleModel( forgettingFactor, compressionThreshold); double[][] c = { { 0 } }; SimpleMatrix[] samples = new SimpleMatrix[temperatures.size()]; for (int i = 0; i < temperatures.size(); ++i) { SimpleMatrix sample = new SimpleMatrix( new double[][] {{ temperatures.get(i) }}); samples[i] = sample; } /* * Now the sample model is updated using the generated sample data. */ try { // Add three samples at once to initialize the sample model ArrayList<SimpleMatrix> initSamples = new ArrayList<SimpleMatrix>(); initSamples.add(samples[0]); initSamples.add(samples[1]); initSamples.add(samples[2]); double[] w = { 1, 1, 1 }; SimpleMatrix[] cov = { new SimpleMatrix(c), new SimpleMatrix(c), new SimpleMatrix(c) }; sampleDistribution.updateDistribution( initSamples.toArray(new SimpleMatrix[3]), cov, w); // Update the sample model with all generated samples one by one. for (int i = 3; i < temperatures.size(); i++) { SimpleMatrix pos = samples[i]; sampleDistribution.updateDistribution(pos, new SimpleMatrix(c), 1d); } } catch (Exception e) { e.printStackTrace(); } for (int i = 270; i < 320; ++i) { double[][] point = {{ (double) i }}; SimpleMatrix pointVector = new SimpleMatrix(point); System.out.println(i + "\t" + sampleDistribution.evaluate(pointVector)); } } }
package com.redhat.ceylon.eclipse.core.model; import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.isInCeylonClassesOutputFolder; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.WeakHashMap; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.WorkingCopyOwner; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.env.AccessRestriction; import org.eclipse.jdt.internal.compiler.env.IBinaryAnnotation; import org.eclipse.jdt.internal.compiler.env.IBinaryMethod; import org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.env.ISourceType; import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding; import org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.MissingTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.PackageBinding; import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons; import org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter; import org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.core.BasicCompilationUnit; import org.eclipse.jdt.internal.core.BinaryType; import org.eclipse.jdt.internal.core.ClassFile; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jdt.internal.core.JavaElementRequestor; import org.eclipse.jdt.internal.core.JavaModelManager; import org.eclipse.jdt.internal.core.JavaProject; import org.eclipse.jdt.internal.core.NameLookup; import org.eclipse.jdt.internal.core.SearchableEnvironment; import org.eclipse.jdt.internal.core.SourceType; import org.eclipse.jdt.internal.core.SourceTypeElementInfo; import org.eclipse.jdt.internal.core.search.BasicSearchEngine; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.compiler.java.codegen.Naming; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.util.Timer; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.loader.ModelResolutionException; import com.redhat.ceylon.compiler.loader.SourceDeclarationVisitor; import com.redhat.ceylon.compiler.loader.TypeParser; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.mirror.MethodMirror; import com.redhat.ceylon.compiler.loader.model.LazyClass; import com.redhat.ceylon.compiler.loader.model.LazyInterface; import com.redhat.ceylon.compiler.loader.model.LazyMethod; import com.redhat.ceylon.compiler.loader.model.LazyModule; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.loader.model.LazyValue; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ModuleDescriptor; import com.redhat.ceylon.compiler.typechecker.tree.Tree.PackageDescriptor; import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder; import com.redhat.ceylon.eclipse.core.builder.CeylonProjectConfig; import com.redhat.ceylon.eclipse.core.classpath.CeylonClasspathUtil; import com.redhat.ceylon.eclipse.core.classpath.CeylonProjectModulesContainer; import com.redhat.ceylon.eclipse.core.model.mirror.JDTClass; import com.redhat.ceylon.eclipse.core.model.mirror.JDTMethod; import com.redhat.ceylon.eclipse.core.model.mirror.SourceClass; import com.redhat.ceylon.eclipse.core.model.mirror.SourceDeclarationHolder; /** * A model loader which uses the JDT model. * * @author David Festal <david.festal@serli.com> */ public class JDTModelLoader extends AbstractModelLoader { private IJavaProject javaProject; private CompilerOptions compilerOptions; private ProblemReporter problemReporter; private LookupEnvironment lookupEnvironment; private MissingTypeBinding missingTypeBinding; private final Object lookupEnvironmentMutex = new Object(); private boolean mustResetLookupEnvironment = false; private Set<Module> modulesInClassPath = new HashSet<Module>(); public JDTModelLoader(final JDTModuleManager moduleManager, final Modules modules){ this.moduleManager = moduleManager; this.modules = modules; javaProject = moduleManager.getJavaProject(); if (javaProject != null) { compilerOptions = new CompilerOptions(javaProject.getOptions(true)); compilerOptions.ignoreMethodBodies = true; compilerOptions.storeAnnotations = true; problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()); } this.timer = new Timer(false); internalCreate(); if (javaProject != null) { modelLoaders.put(javaProject.getProject(), new WeakReference<JDTModelLoader>(this)); } } public JDTModuleManager getModuleManager() { return (JDTModuleManager) moduleManager; } private void internalCreate() { this.typeFactory = new GlobalTypeFactory(); this.typeParser = new TypeParser(this); this.timer = new Timer(false); createLookupEnvironment(); } public void createLookupEnvironment() { if (javaProject == null) { return; } try { ModelLoaderTypeRequestor requestor = new ModelLoaderTypeRequestor(); lookupEnvironment = new LookupEnvironment(requestor, compilerOptions, problemReporter, createSearchableEnvironment()); requestor.initialize(lookupEnvironment); lookupEnvironment.mayTolerateMissingType = true; missingTypeBinding = new MissingTypeBinding(lookupEnvironment.defaultPackage, new char[][] {"unknown".toCharArray()}, lookupEnvironment); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public LookupEnvironment createLookupEnvironmentForGeneratedCode() { if (javaProject == null) { return null; } try { ModelLoaderTypeRequestor requestor = new ModelLoaderTypeRequestor(); LookupEnvironment lookupEnvironmentForGeneratedCode = new LookupEnvironment(requestor, compilerOptions, problemReporter, ((JavaProject)javaProject).newSearchableNameEnvironment((WorkingCopyOwner)null)); requestor.initialize(lookupEnvironmentForGeneratedCode); lookupEnvironmentForGeneratedCode.mayTolerateMissingType = true; return lookupEnvironmentForGeneratedCode; } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // TODO : remove when the bug in the AbstractModelLoader is corrected @Override public synchronized LazyPackage findOrCreatePackage(Module module, String pkgName) { LazyPackage pkg = super.findOrCreatePackage(module, pkgName); if (pkg.getModule() != null && pkg.getModule().isJava()){ pkg.setShared(true); } Module currentModule = pkg.getModule(); if (currentModule.equals(modules.getDefaultModule()) && ! currentModule.equals(module)) { currentModule.getPackages().remove(pkg); pkg.setModule(null); if (module != null) { module.getPackages().add(pkg); pkg.setModule(module); } } return pkg; } @Override protected Module loadLanguageModuleAndPackage() { Module languageModule = getLanguageModule(); if (getModuleManager().isLoadDependenciesFromModelLoaderFirst() && !isBootstrap) { findOrCreatePackage(languageModule, CEYLON_LANGUAGE); } return languageModule; } private String getToplevelQualifiedName(final String pkgName, String name) { if (! Util.isInitialLowerCase(name)) { name = Util.quoteIfJavaKeyword(name); } String className = pkgName.isEmpty() ? name : Util.quoteJavaKeywords(pkgName) + "." + name; return className; } private String getToplevelQualifiedName(String fullyQualifiedName) { String pkgName = ""; String name = fullyQualifiedName; int lastDot = fullyQualifiedName.lastIndexOf('.'); if (lastDot > 0 && lastDot < fullyQualifiedName.length()-1) { pkgName = fullyQualifiedName.substring(0, lastDot); name = fullyQualifiedName.substring(lastDot+1, fullyQualifiedName.length()); } return getToplevelQualifiedName(pkgName, name); } @Override public boolean loadPackage(Module module, String packageName, boolean loadDeclarations) { synchronized (getLock()) { packageName = Util.quoteJavaKeywords(packageName); if(loadDeclarations && !loadedPackages.add(cacheKeyByModule(module, packageName))){ return true; } if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots(); IPackageFragment packageFragment = null; for (IPackageFragmentRoot root : roots) { // skip packages that are not present if(! root.exists() || ! javaProject.isOnClasspath(root)) continue; try { IClasspathEntry entry = root.getRawClasspathEntry(); //TODO: is the following really necessary? //Note that getContentKind() returns an undefined //value for a classpath container or variable if (entry.getEntryKind()!=IClasspathEntry.CPE_CONTAINER && entry.getEntryKind()!=IClasspathEntry.CPE_VARIABLE && entry.getContentKind()==IPackageFragmentRoot.K_SOURCE && !CeylonBuilder.isCeylonSourceEntry(entry)) { continue; } packageFragment = root.getPackageFragment(packageName); if(! packageFragment.exists()){ continue; } } catch (JavaModelException e) { if (! e.isDoesNotExist()) { e.printStackTrace(); } continue; } if(!loadDeclarations) { // we found the package return true; } // we have a few virtual types in java.lang that we need to load but they are not listed from class files if(module.getNameAsString().equals(JAVA_BASE_MODULE_NAME) && packageName.equals("java.lang")) { loadJavaBaseArrays(); } IClassFile[] classFiles = new IClassFile[] {}; org.eclipse.jdt.core.ICompilationUnit[] compilationUnits = new org.eclipse.jdt.core.ICompilationUnit[] {}; try { classFiles = packageFragment.getClassFiles(); } catch (JavaModelException e) { e.printStackTrace(); } try { compilationUnits = packageFragment.getCompilationUnits(); } catch (JavaModelException e) { e.printStackTrace(); } List<IType> typesToLoad = new LinkedList<>(); for (IClassFile classFile : classFiles) { IType type = classFile.getType(); typesToLoad.add(type); } for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : compilationUnits) { // skip removed CUs if(!compilationUnit.exists()) continue; try { for (IType type : compilationUnit.getTypes()) { typesToLoad.add(type); } } catch (JavaModelException e) { e.printStackTrace(); } } for (IType type : typesToLoad) { String typeFullyQualifiedName = type.getFullyQualifiedName(); String[] nameParts = typeFullyQualifiedName.split("\\."); String typeQualifiedName = nameParts[nameParts.length - 1]; // only top-levels are added in source declarations if (typeQualifiedName.indexOf('$') > 0) { continue; } if (type.exists() && !sourceDeclarations.containsKey(getToplevelQualifiedName(type.getPackageFragment().getElementName(), typeFullyQualifiedName)) && ! isTypeHidden(module, typeFullyQualifiedName)) { convertToDeclaration(module, typeFullyQualifiedName, DeclarationType.VALUE); } } } } return false; } } public void refreshNameEnvironment() { synchronized (getLock()) { try { lookupEnvironment.nameEnvironment = createSearchableEnvironment(); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public final class ModelLoaderTypeRequestor implements ITypeRequestor { private Parser basicParser; private LookupEnvironment lookupEnvironment; public void initialize(LookupEnvironment lookupEnvironment) { this.lookupEnvironment = lookupEnvironment; } @Override public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { // case of SearchableEnvironment of an IJavaProject is used ISourceType sourceType = sourceTypes[0]; while (sourceType.getEnclosingType() != null) sourceType = sourceType.getEnclosingType(); if (sourceType instanceof SourceTypeElementInfo) { // get source SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType; IType type = elementInfo.getHandle(); ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit(); accept(sourceUnit, accessRestriction); } else { CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0); CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit( sourceTypes, SourceTypeConverter.FIELD_AND_METHOD // need field and methods | SourceTypeConverter.MEMBER_TYPE, // need member types // no need for field initialization lookupEnvironment.problemReporter, result); lookupEnvironment.buildTypeBindings(unit, accessRestriction); lookupEnvironment.completeTypeBindings(unit, true); } } @Override public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { BinaryTypeBinding btb = lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction); if (btb.isNestedType() && !btb.isStatic()) { for (MethodBinding method : btb.methods()) { if (method.isConstructor() && method.parameters.length > 0) { char[] signature = method.signature(); for (IBinaryMethod methodInfo : binaryType.getMethods()) { if (methodInfo.isConstructor()) { char[] methodInfoSignature = methodInfo.getMethodDescriptor(); if (new String(signature).equals(new String(methodInfoSignature))) { IBinaryAnnotation[] binaryAnnotation = methodInfo.getParameterAnnotations(0); if (binaryAnnotation == null) { if (methodInfo.getAnnotatedParametersCount() == method.parameters.length + 1) { AnnotationBinding[][] newParameterAnnotations = new AnnotationBinding[method.parameters.length][]; for (int i=0; i<method.parameters.length; i++) { IBinaryAnnotation[] goodAnnotations = null; try { goodAnnotations = methodInfo.getParameterAnnotations(i + 1); } catch(IndexOutOfBoundsException e) { break; } if (goodAnnotations != null) { AnnotationBinding[] parameterAnnotations = BinaryTypeBinding.createAnnotations(goodAnnotations, lookupEnvironment, new char[][][] {}); newParameterAnnotations[i] = parameterAnnotations; } } method.setParameterAnnotations(newParameterAnnotations); } } } } } } } } } @Override public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { // Switch the current policy and compilation result for this unit to the requested one. CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, compilerOptions.maxProblemsPerUnit); try { CompilationUnitDeclaration parsedUnit = basicParser().dietParse(sourceUnit, unitResult); lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction); lookupEnvironment.completeTypeBindings(parsedUnit, true); } catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } } // Display unit error in debug mode if (BasicSearchEngine.VERBOSE) { if (unitResult.problemCount > 0) { System.out.println(unitResult); } } } private Parser basicParser() { if (this.basicParser == null) { ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()); this.basicParser = new Parser(problemReporter, false); this.basicParser.reportOnlyOneSyntaxError = true; } return this.basicParser; } } public static class ModelLoaderNameEnvironment extends SearchableEnvironment { public ModelLoaderNameEnvironment(IJavaProject javaProject) throws JavaModelException { super((JavaProject)javaProject, (WorkingCopyOwner) null); } public IJavaProject getJavaProject() { return project; } public IType findTypeInNameLookup(char[][] compoundTypeName) { if (compoundTypeName == null) return null; int length = compoundTypeName.length; if (length <= 1) { if (length == 0) return null; return findTypeInNameLookup(new String(compoundTypeName[0]), IPackageFragment.DEFAULT_PACKAGE_NAME); } int lengthM1 = length - 1; char[][] packageName = new char[lengthM1][]; System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1); return findTypeInNameLookup( new String(compoundTypeName[lengthM1]), CharOperation.toString(packageName)); } public IType findTypeInNameLookup(String typeName, String packageName) { JavaElementRequestor packageRequestor = new JavaElementRequestor(); nameLookup.seekPackageFragments(packageName, false, packageRequestor); LinkedList<IPackageFragment> packagesToSearchIn = new LinkedList<>(); for (IPackageFragment pf : packageRequestor.getPackageFragments()) { IPackageFragmentRoot packageRoot = (IPackageFragmentRoot) pf.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); try { if (packageRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { packagesToSearchIn.addFirst(pf); continue; } if (isInCeylonClassesOutputFolder(packageRoot.getPath())) { continue; } packagesToSearchIn.addLast(pf); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } IType type = null; for (IPackageFragment pf : packagesToSearchIn) { // We use considerSecondTypes = false because we will do it explicitly afterwards, in order to use waitForIndexes=true // TODO : when migrating to Luna only (removing Kepler support), we will be able to simply call : // nameLookup.findType(typeName, pf, false, NameLookup.ACCEPT_ALL, // true /* waitForIndices */, // true /* considerSecondaryTypes */) // But unfortunately, Kepler doesn't provide the ability to set the 'waitForIndexes' parameter to true. type = nameLookup.findType(typeName, pf, false, NameLookup.ACCEPT_ALL); if (type == null) { JavaModelManager manager = JavaModelManager.getJavaModelManager(); try { // This is a Copy / Paste from : // org.eclipse.jdt.internal.core.NameLookup.findSecondaryType(...), in order to be able to call it with waitForIndexes = true: // type = nameLookup.findSecondaryType(pf.getElementName(), typeName, pf.getJavaProject(), true, null); IJavaProject javaProject = pf.getJavaProject(); @SuppressWarnings("rawtypes") Map secondaryTypePaths = manager.secondaryTypes(javaProject, true, null); if (secondaryTypePaths.size() > 0) { @SuppressWarnings("rawtypes") Map types = (Map) secondaryTypePaths.get(packageName==null?"":packageName); //$NON-NLS-1$ if (types != null && types.size() > 0) { boolean startsWithDollar = false; if(typeName.startsWith("$")) { startsWithDollar = true; typeName = typeName.substring(1); } String[] parts = typeName.split("(\\.|\\$)"); if (startsWithDollar) { parts[0] = "$" + parts[0]; } int index = 0; String topLevelClassName = parts[index++]; IType currentClass = (IType) types.get(topLevelClassName); IType result = currentClass; while (index < parts.length) { result = null; String nestedClassName = parts[index++]; if (currentClass != null && currentClass.exists()) { currentClass = currentClass.getType(nestedClassName); result = currentClass; } else { break; } } type = result; } } } catch (JavaModelException jme) { // give up } } if (type != null) { break; } } return type; } @Override protected NameEnvironmentAnswer find(String typeName, String packageName) { if (packageName == null) packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; if (this.owner != null) { String source = this.owner.findSource(typeName, packageName); if (source != null) { ICompilationUnit cu = new BasicCompilationUnit(source.toCharArray(), CharOperation.splitOn('.', packageName.toCharArray()), typeName + org.eclipse.jdt.internal.core.util.Util.defaultJavaExtension()); return new NameEnvironmentAnswer(cu, null); } } IType type = findTypeInNameLookup(typeName, packageName); if (type != null) { // construct name env answer if (type instanceof BinaryType) { // BinaryType try { return new NameEnvironmentAnswer((IBinaryType) ((BinaryType) type).getElementInfo(), null); } catch (JavaModelException npe) { // fall back to using owner } } else { //SourceType try { // retrieve the requested type SourceTypeElementInfo sourceType = (SourceTypeElementInfo)((SourceType) type).getElementInfo(); ISourceType topLevelType = sourceType; while (topLevelType.getEnclosingType() != null) { topLevelType = topLevelType.getEnclosingType(); } // find all siblings (other types declared in same unit, since may be used for name resolution) IType[] types = sourceType.getHandle().getCompilationUnit().getTypes(); ISourceType[] sourceTypes = new ISourceType[types.length]; // in the resulting collection, ensure the requested type is the first one sourceTypes[0] = sourceType; int length = types.length; for (int i = 0, index = 1; i < length; i++) { ISourceType otherType = (ISourceType) ((JavaElement) types[i]).getElementInfo(); if (!otherType.equals(topLevelType) && index < length) sourceTypes[index++] = otherType; } return new NameEnvironmentAnswer(sourceTypes, null); } catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)type.getParent(), null); } // no usable answer } } } return null; } } private INameEnvironment createSearchableEnvironment() throws JavaModelException { return new ModelLoaderNameEnvironment(javaProject); } synchronized private LookupEnvironment getLookupEnvironment() { if (mustResetLookupEnvironment) { synchronized (lookupEnvironment) { createLookupEnvironment(); } mustResetLookupEnvironment = false; } return lookupEnvironment; } @Override public boolean searchAgain(Module module, String name) { if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (jdtModule.isCeylonBinaryArchive() || jdtModule.isJavaBinaryArchive()) { String classRelativePath = name.replace('.', '/'); return jdtModule.containsClass(classRelativePath + ".class") || jdtModule.containsClass(classRelativePath + "_.class"); } else if (jdtModule.isProjectModule()) { int nameLength = name.length(); int packageEnd = name.lastIndexOf('.'); int classNameStart = packageEnd + 1; String packageName = packageEnd > 0 ? name.substring(0, packageEnd) : ""; String className = classNameStart < nameLength ? name.substring(classNameStart) : ""; boolean moduleContainsJava = false; for (IPackageFragmentRoot root : jdtModule.getPackageFragmentRoots()) { try { IPackageFragment pf = root.getPackageFragment(packageName); if (pf.exists() && javaProject.isOnClasspath(pf)) { if (((IPackageFragment)pf).containsJavaResources()) { moduleContainsJava = true; break; } } } catch (JavaModelException e) { e.printStackTrace(); moduleContainsJava = true; // Just in case ... } } if (moduleContainsJava) { ModelLoaderNameEnvironment nameEnvironment = getNameEnvironment(); if (nameEnvironment.findTypeInNameLookup(className, packageName) != null || nameEnvironment.findTypeInNameLookup(className + "_", packageName) != null) { return true; } } return false; } } return false; } @Override public boolean searchAgain(LazyPackage lazyPackage, String name) { return searchAgain(lazyPackage.getModule(), lazyPackage.getQualifiedName(lazyPackage.getQualifiedNameString(), name)); } @Override public ClassMirror lookupNewClassMirror(Module module, String name) { synchronized(getLock()){ String topLevelPartiallyQuotedName = getToplevelQualifiedName(name); if (sourceDeclarations.containsKey(topLevelPartiallyQuotedName)) { return new SourceClass(sourceDeclarations.get(topLevelPartiallyQuotedName)); } ClassMirror classMirror = buildClassMirror(Util.quoteJavaKeywords(name)); if (classMirror == null && lastPartHasLowerInitial(name) && !name.endsWith("_")) { // We have to try the unmunged name first, so that we find the symbol // from the source in preference to the symbol from any // pre-existing .class file classMirror = buildClassMirror(Util.quoteJavaKeywords(name + "_")); } if(classMirror == null) return null; Module classMirrorModule = findModuleForClassMirror(classMirror); if(classMirrorModule == null){ logVerbose("Found a class mirror with no module"); return null; } // make sure it's imported if(isImported(module, classMirrorModule)){ return classMirror; } logVerbose("Found a class mirror that is not imported: "+name); return null; } } public MissingTypeBinding getMissingTypeBinding() { synchronized (getLock()) { return missingTypeBinding; } } public static interface ActionOnResolvedType { void doWithBinding(ReferenceBinding referenceBinding); } private static WeakHashMap<IProject, WeakReference<JDTModelLoader>> modelLoaders = new WeakHashMap<>(); public static JDTModelLoader getModelLoader(IProject project) { WeakReference<JDTModelLoader> modelLoaderRef = modelLoaders.get(project); if (modelLoaderRef != null) { return modelLoaderRef.get(); } return null; } public static JDTModelLoader getModelLoader(IJavaProject javaProject) { return getModelLoader(javaProject.getProject()); } public static JDTModelLoader getModelLoader(IType type) { return type == null ? null : getModelLoader(type.getJavaProject()); } public static interface ActionOnMethodBinding { void doWithBinding(IType declaringClassModel, ReferenceBinding declaringClassBinding, MethodBinding methodBinding); } public static interface ActionOnClassBinding { void doWithBinding(IType classModel, ReferenceBinding classBinding); } public static boolean doWithReferenceBinding(final IType typeModel, final ReferenceBinding binding, final ActionOnClassBinding action) { if (typeModel == null) { throw new ModelResolutionException("Resolving action requested on a missing declaration"); } if (binding == null) { return false; } PackageBinding packageBinding = binding.getPackage(); if (packageBinding == null) { return false; } LookupEnvironment lookupEnvironment = packageBinding.environment; if (lookupEnvironment == null) { return false; } JDTModelLoader modelLoader = getModelLoader(typeModel); if (modelLoader == null) { throw new ModelResolutionException("The Model Loader corresponding the type '" + typeModel.getFullyQualifiedName() + "' was not available"); } synchronized (modelLoader.lookupEnvironmentMutex) { if (modelLoader.lookupEnvironment != lookupEnvironment) { return false; } action.doWithBinding(typeModel, binding); return true; } } public static boolean doWithMethodBinding(final IType declaringClassModel, final MethodBinding binding, final ActionOnMethodBinding action) { if (declaringClassModel == null) { throw new ModelResolutionException("Resolving action requested on a missing declaration"); } if (binding == null) { return false; } ReferenceBinding declaringClassBinding = binding.declaringClass; if (declaringClassBinding == null) { return false; } PackageBinding packageBinding = declaringClassBinding.getPackage(); if (packageBinding == null) { return false; } LookupEnvironment lookupEnvironment = packageBinding.environment; if (lookupEnvironment == null) { return false; } JDTModelLoader modelLoader = getModelLoader(declaringClassModel); if (modelLoader == null) { throw new ModelResolutionException("The Model Loader corresponding the type '" + declaringClassModel.getFullyQualifiedName() + "' doesn't exist"); } synchronized (modelLoader.lookupEnvironmentMutex) { if (modelLoader.lookupEnvironment != lookupEnvironment) { return false; } action.doWithBinding(declaringClassModel, declaringClassBinding, binding); return true; } } public static interface ActionOnResolvedGeneratedType { void doWithBinding(IType classModel, ReferenceBinding classBinding, IBinaryType binaryType); } public static void doOnResolvedGeneratedType(IType typeModel, ActionOnResolvedGeneratedType action) { if (typeModel == null || ! typeModel.exists()) { throw new ModelResolutionException("Resolving action requested on a missing declaration"); } JDTModelLoader modelLoader = getModelLoader(typeModel); if (modelLoader == null) { throw new ModelResolutionException("The Model Loader is not available to resolve type '" + typeModel.getFullyQualifiedName() + "'"); } char[][] compoundName = CharOperation.splitOn('.', typeModel.getFullyQualifiedName().toCharArray()); LookupEnvironment lookupEnvironment = modelLoader.createLookupEnvironmentForGeneratedCode(); ReferenceBinding binding = null; IBinaryType binaryType = null; try { ITypeRoot typeRoot = typeModel.getTypeRoot(); if (typeRoot instanceof IClassFile) { ClassFile classFile = (ClassFile) typeRoot; IFile classFileRsrc = (IFile) classFile.getCorrespondingResource(); if (classFileRsrc!=null && !classFileRsrc.exists()) { //the .class file has been deleted return; } BinaryTypeBinding binaryTypeBinding = null; try { binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true); binaryTypeBinding = lookupEnvironment.cacheBinaryType(binaryType, null); } catch(JavaModelException e) { if (! e.isDoesNotExist()) { throw e; } } if (binaryTypeBinding == null) { ReferenceBinding existingType = lookupEnvironment.getCachedType(compoundName); if (existingType == null || ! (existingType instanceof BinaryTypeBinding)) { return; } binaryTypeBinding = (BinaryTypeBinding) existingType; } binding = binaryTypeBinding; } } catch (JavaModelException e) { throw new ModelResolutionException(e); } if (binaryType != null && binding != null) { action.doWithBinding(typeModel, binding, binaryType); } } public static void doWithResolvedType(IType typeModel, ActionOnResolvedType action) { if (typeModel == null || ! typeModel.exists()) { throw new ModelResolutionException("Resolving action requested on a missing declaration"); } JDTModelLoader modelLoader = getModelLoader(typeModel); if (modelLoader == null) { throw new ModelResolutionException("The Model Loader is not available to resolve type '" + typeModel.getFullyQualifiedName() + "'"); } char[][] compoundName = CharOperation.splitOn('.', typeModel.getFullyQualifiedName().toCharArray()); LookupEnvironment lookupEnvironment = modelLoader.getLookupEnvironment(); synchronized (modelLoader.lookupEnvironmentMutex) { ReferenceBinding binding; try { binding = toBinding(typeModel, lookupEnvironment, compoundName); } catch (JavaModelException e) { throw new ModelResolutionException(e); } if (binding == null) { throw new ModelResolutionException("Binding not found for type : '" + typeModel.getFullyQualifiedName() + "'"); } action.doWithBinding(binding); } } public static IType toType(ReferenceBinding binding) { ModelLoaderNameEnvironment nameEnvironment = (ModelLoaderNameEnvironment) binding.getPackage().environment.nameEnvironment; char[][] compoundName = ((ReferenceBinding) binding).compoundName; IType typeModel = nameEnvironment.findTypeInNameLookup(compoundName); if (typeModel == null && ! (binding instanceof MissingTypeBinding)) { throw new ModelResolutionException("JDT reference binding without a JDT IType element !"); } return typeModel; } private JDTClass buildClassMirror(String name) { if (javaProject == null) { return null; } try { LookupEnvironment theLookupEnvironment = getLookupEnvironment(); char[][] uncertainCompoundName = CharOperation.splitOn('.', name.toCharArray()); int numberOfParts = uncertainCompoundName.length; char[][] compoundName = null; IType type = null; for (int i=numberOfParts-1; i>=0; i char[][] triedPackageName = new char[0][]; for (int j=0; j<i; j++) { triedPackageName = CharOperation.arrayConcat(triedPackageName, uncertainCompoundName[j]); } char[] triedClassName = new char[0]; for (int k=i; k<numberOfParts; k++) { triedClassName = CharOperation.concat(triedClassName, uncertainCompoundName[k], '$'); } ModelLoaderNameEnvironment nameEnvironment = getNameEnvironment(); type = nameEnvironment.findTypeInNameLookup(CharOperation.charToString(triedClassName), CharOperation.toString(triedPackageName)); if (type != null) { compoundName = CharOperation.arrayConcat(triedPackageName, triedClassName); break; } } if (type == null) { return null; } ReferenceBinding binding = toBinding(type, theLookupEnvironment, compoundName); if (binding != null) { return new JDTClass(binding, type); } } catch (JavaModelException e) { e.printStackTrace(); } return null; } private static ReferenceBinding toBinding(IType type, LookupEnvironment theLookupEnvironment, char[][] compoundName) throws JavaModelException { ITypeRoot typeRoot = type.getTypeRoot(); if (typeRoot instanceof IClassFile) { ClassFile classFile = (ClassFile) typeRoot; IFile classFileRsrc = (IFile) classFile.getCorrespondingResource(); if (classFileRsrc!=null && !classFileRsrc.exists()) { //the .class file has been deleted return null; } BinaryTypeBinding binaryTypeBinding = null; try { IBinaryType binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true); binaryTypeBinding = theLookupEnvironment.cacheBinaryType(binaryType, null); } catch(JavaModelException e) { if (! e.isDoesNotExist()) { throw e; } } if (binaryTypeBinding == null) { ReferenceBinding existingType = theLookupEnvironment.getCachedType(compoundName); if (existingType == null || ! (existingType instanceof BinaryTypeBinding)) { return null; } binaryTypeBinding = (BinaryTypeBinding) existingType; } return binaryTypeBinding; } else { ReferenceBinding referenceBinding = theLookupEnvironment.getType(compoundName); if (referenceBinding != null && ! (referenceBinding instanceof BinaryTypeBinding)) { if (referenceBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding problemReferenceBinding = (ProblemReferenceBinding) referenceBinding; if (problemReferenceBinding.problemId() == ProblemReasons.InternalNameProvided) { referenceBinding = problemReferenceBinding.closestReferenceMatch(); } else { System.out.println(ProblemReferenceBinding.problemReasonString(problemReferenceBinding.problemId())); return null; } } return referenceBinding; } return null; } } private ModelLoaderNameEnvironment getNameEnvironment() { ModelLoaderNameEnvironment searchableEnvironment = (ModelLoaderNameEnvironment)getLookupEnvironment().nameEnvironment; return searchableEnvironment; } @Override public Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) { synchronized (getLock()) { String fqn = getToplevelQualifiedName(typeName); if (sourceDeclarations.containsKey(fqn)) { return sourceDeclarations.get(fqn).getModelDeclaration(); } try { return super.convertToDeclaration(module, typeName, declarationType); } catch(RuntimeException e) { // FIXME: pretty sure this is plain wrong as it ignores problems and especially ModelResolutionException and just plain hides them return null; } } } @Override public void addModuleToClassPath(Module module, ArtifactResult artifact) { if(artifact != null && module instanceof LazyModule) ((LazyModule)module).loadPackageList(artifact); if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (! jdtModule.equals(getLanguageModule()) && (jdtModule.isCeylonBinaryArchive() || jdtModule.isJavaBinaryArchive())) { CeylonProjectModulesContainer container = CeylonClasspathUtil.getCeylonProjectModulesClasspathContainer(javaProject); if (container != null) { IPath modulePath = new Path(artifact.artifact().getPath()); IClasspathEntry newEntry = container.addNewClasspathEntryIfNecessary(modulePath); if (newEntry!=null) { try { JavaCore.setClasspathContainer(container.getPath(), new IJavaProject[] { javaProject }, new IClasspathContainer[] {new CeylonProjectModulesContainer(container)}, null); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } refreshNameEnvironment(); } } } } modulesInClassPath.add(module); } @Override protected boolean isOverridingMethod(MethodMirror methodSymbol) { return ((JDTMethod)methodSymbol).isOverridingMethod(); } @Override protected boolean isOverloadingMethod(MethodMirror methodSymbol) { return ((JDTMethod)methodSymbol).isOverloadingMethod(); } @Override protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { Unit unit = null; if (classMirror != null && classMirror instanceof JDTClass) { JDTClass jdtClass = (JDTClass) classMirror; String unitName = jdtClass.getFileName(); if (!jdtClass.isBinary()) { // This search is for source Java classes since several classes might have the same file name // and live inside the same Java source file => into the same Unit for (Unit unitToTest : pkg.getUnits()) { if (unitToTest.getFilename().equals(unitName)) { return unitToTest; } } } unit = newCompiledUnit(pkg, jdtClass); } if (unit == null) { unit = unitsByPackage.get(pkg); if(unit == null){ unit = new PackageTypeFactory(pkg); unit.setPackage(pkg); unitsByPackage.put(pkg, unit); } } return unit; } public void setModuleAndPackageUnits() { Context context = getModuleManager().getContext(); for (Module module : context.getModules().getListOfModules()) { if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (jdtModule.isCeylonBinaryArchive()) { for (Package p : jdtModule.getPackages()) { if (p.getUnit() == null) { ClassMirror packageClassMirror = lookupClassMirror(jdtModule, p.getQualifiedNameString() + "." + Naming.PACKAGE_DESCRIPTOR_CLASS_NAME); if (packageClassMirror == null) { packageClassMirror = lookupClassMirror(jdtModule, p.getQualifiedNameString() + "." + Naming.PACKAGE_DESCRIPTOR_CLASS_NAME.substring(1)); } // some modules do not declare their main package, because they don't have any declaration to share // there, for example, so this can be null if(packageClassMirror != null) p.setUnit(newCompiledUnit((LazyPackage) p, packageClassMirror)); } if (p.getNameAsString().equals(jdtModule.getNameAsString())) { if (jdtModule.getUnit() == null) { ClassMirror moduleClassMirror = lookupClassMirror(jdtModule, p.getQualifiedNameString() + "." + Naming.MODULE_DESCRIPTOR_CLASS_NAME); if (moduleClassMirror == null) { moduleClassMirror = lookupClassMirror(jdtModule, p.getQualifiedNameString() + "." + Naming.OLD_MODULE_DESCRIPTOR_CLASS_NAME); } if (moduleClassMirror != null) { jdtModule.setUnit(newCompiledUnit((LazyPackage) p, moduleClassMirror)); } } } } } } } } private Unit newCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { Unit unit; JDTClass jdtClass = (JDTClass) classMirror; IType type = jdtClass.getType(); if (type == null) { return null; } ITypeRoot typeRoot = type.getTypeRoot(); StringBuilder sb = new StringBuilder(); List<String> parts = pkg.getName(); for (int i = 0; i < parts.size(); i++) { String part = parts.get(i); if (! part.isEmpty()) { sb.append(part); sb.append('/'); } } sb.append(jdtClass.getFileName()); String relativePath = sb.toString(); String fileName = jdtClass.getFileName(); String fullPath = jdtClass.getFullPath(); if (!jdtClass.isBinary()) { unit = new JavaCompilationUnit((org.eclipse.jdt.core.ICompilationUnit)typeRoot, fileName, relativePath, fullPath, pkg); } else { if (jdtClass.isCeylon()) { if (pkg.getModule() instanceof JDTModule) { JDTModule module = (JDTModule) pkg.getModule(); IProject originalProject = module.getOriginalProject(); if (originalProject != null) { unit = new CrossProjectBinaryUnit((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } else { unit = new CeylonBinaryUnit((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } } else { unit = new CeylonBinaryUnit((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } } else { unit = new JavaClassFile((IClassFile)typeRoot, fileName, relativePath, fullPath, pkg); } } return unit; } @Override protected void logError(String message) { //System.err.println("ERROR: "+message); } @Override protected void logWarning(String message) { //System.err.println("WARNING: "+message); } @Override protected void logVerbose(String message) { //System.err.println("NOTE: "+message); } @Override public synchronized void removeDeclarations(List<Declaration> declarations) { List<Declaration> allDeclarations = new ArrayList<Declaration>(declarations.size()); Set<Package> changedPackages = new HashSet<Package>(); allDeclarations.addAll(declarations); for (Declaration declaration : declarations) { Unit unit = declaration.getUnit(); if (unit != null) { changedPackages.add(unit.getPackage()); } retrieveInnerDeclarations(declaration, allDeclarations); } for (Declaration decl : allDeclarations) { String fqn = getToplevelQualifiedName(decl.getContainer().getQualifiedNameString(), decl.getName()); sourceDeclarations.remove(fqn); } super.removeDeclarations(allDeclarations); for (Package changedPackage : changedPackages) { loadedPackages.remove(cacheKeyByModule(changedPackage.getModule(), changedPackage.getNameAsString())); } mustResetLookupEnvironment = true; } private void retrieveInnerDeclarations(Declaration declaration, List<Declaration> allDeclarations) { List<Declaration> members; try { members = declaration.getMembers(); } catch(Exception e) { members = Collections.emptyList(); } allDeclarations.addAll(members); for (Declaration member : members) { retrieveInnerDeclarations(member, allDeclarations); } } private final Map<String, SourceDeclarationHolder> sourceDeclarations = new TreeMap<String, SourceDeclarationHolder>(); public synchronized Set<String> getSourceDeclarations() { Set<String> declarations = new HashSet<String>(); declarations.addAll(sourceDeclarations.keySet()); return declarations; } public synchronized SourceDeclarationHolder getSourceDeclaration(String declarationName) { return sourceDeclarations.get(declarationName); } public class PackageTypeFactory extends TypeFactory { public PackageTypeFactory(Package pkg) { super(moduleManager.getContext()); assert (pkg != null); setPackage(pkg); } } public class GlobalTypeFactory extends TypeFactory { public GlobalTypeFactory() { super(moduleManager.getContext()); } @Override public Package getPackage() { synchronized (JDTModelLoader.this) { if(super.getPackage() == null){ super.setPackage(modules.getLanguageModule() .getDirectPackage(Module.LANGUAGE_MODULE_NAME)); } return super.getPackage(); } } } public static interface SourceFileObjectManager { void setupSourceFileObjects(List<?> treeHolders); } public void setupSourceFileObjects(List<?> treeHolders) { synchronized (getLock()) { addSourcePhasedUnits(treeHolders, true); } } public void addSourcePhasedUnits(List<?> treeHolders, final boolean isSourceToCompile) { synchronized (getLock()) { for (Object treeHolder : treeHolders) { if (treeHolder instanceof PhasedUnit) { final PhasedUnit unit = (PhasedUnit) treeHolder; final String pkgName = unit.getPackage().getQualifiedNameString(); unit.getCompilationUnit().visit(new SourceDeclarationVisitor(){ @Override public void loadFromSource(Tree.Declaration decl) { if (decl.getIdentifier()!=null) { String fqn = getToplevelQualifiedName(pkgName, decl.getIdentifier().getText()); if (! sourceDeclarations.containsKey(fqn)) { sourceDeclarations.put(fqn, new SourceDeclarationHolder(unit, decl, isSourceToCompile)); } } } @Override public void loadFromSource(ModuleDescriptor that) { } @Override public void loadFromSource(PackageDescriptor that) { } }); } } } } public void addSourceArchivePhasedUnits(List<PhasedUnit> sourceArchivePhasedUnits) { addSourcePhasedUnits(sourceArchivePhasedUnits, false); } public void clearCachesOnPackage(String packageName) { synchronized (getLock()) { List<String> keysToRemove = new ArrayList<String>(classMirrorCache.size()); for (Entry<String, ClassMirror> element : classMirrorCache.entrySet()) { if (element.getValue() == null) { String className = element.getKey(); if (className != null) { String classPackageName =className.replaceAll("\\.[^\\.]+$", ""); if (classPackageName.equals(packageName)) { keysToRemove.add(className); } } } } for (String keyToRemove : keysToRemove) { classMirrorCache.remove(keyToRemove); } Package pkg = findPackage(packageName); loadedPackages.remove(cacheKeyByModule(pkg.getModule(), packageName)); mustResetLookupEnvironment = true; } } public void clearClassMirrorCacheForClass(JDTModule module, String classNameToRemove) { synchronized (getLock()) { classMirrorCache.remove(cacheKeyByModule(module, classNameToRemove)); mustResetLookupEnvironment = true; } } @Override protected LazyValue makeToplevelAttribute(ClassMirror classMirror) { if (classMirror instanceof SourceClass) { return (LazyValue) (((SourceClass) classMirror).getModelDeclaration()); } return super.makeToplevelAttribute(classMirror); } @Override protected LazyMethod makeToplevelMethod(ClassMirror classMirror) { if (classMirror instanceof SourceClass) { return (LazyMethod) (((SourceClass) classMirror).getModelDeclaration()); } return super.makeToplevelMethod(classMirror); } @Override protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror constructor) { if (classMirror instanceof SourceClass) { return (LazyClass) (((SourceClass) classMirror).getModelDeclaration()); } return super.makeLazyClass(classMirror, superClass, constructor); } @Override protected LazyInterface makeLazyInterface(ClassMirror classMirror) { if (classMirror instanceof SourceClass) { return (LazyInterface) ((SourceClass) classMirror).getModelDeclaration(); } return super.makeLazyInterface(classMirror); } public TypeFactory getTypeFactory() { return (TypeFactory) typeFactory; } @Override protected Module findModuleForClassMirror(ClassMirror classMirror) { String pkgName = getPackageNameForQualifiedClassName(classMirror); return lookupModuleByPackageName(pkgName); } public void loadJDKModules() { super.loadJDKModules(); } @Override public LazyPackage findOrCreateModulelessPackage(String pkgName) { synchronized(getLock()){ return (LazyPackage) findPackage(pkgName); } } @Override public boolean isModuleInClassPath(Module module) { return modulesInClassPath.contains(module) || ((module instanceof JDTModule) && ((JDTModule) module).isProjectModule()) || ((module instanceof JDTModule) && ((JDTModule) module).getOriginalModule() != null && ((JDTModule) module).getOriginalModule().isProjectModule()) ; } @Override protected boolean needsLocalDeclarations() { return false; } void addJDKModuleToClassPath(Module module) { modulesInClassPath.add(module); } @Override protected boolean isAutoExportMavenDependencies() { if (javaProject != null) { return CeylonProjectConfig.get(javaProject.getProject()).isAutoExportMavenDependencies(); } else { return false; } } @Override protected boolean isFlatClasspath() { if (javaProject != null) { return CeylonProjectConfig.get(javaProject.getProject()).isFlatClasspath(); } else { return false; } } }
package io.sigpipe.sing.stat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class Reservoir<T> { private long count; private int size; private List<Entry> reservoir; private Random random = new Random(); private class Entry implements Comparable<Entry> { public double key; public T value; public Entry(double key, T value) { this.key = key; this.value = value; } @Override public int compareTo(Entry that) { return Double.compare(this.key, that.key); } @Override public String toString() { return "[" + key + "] -> " + value; } } public Reservoir(int size) { this.size = size; reservoir = new ArrayList<>(size); } public void put(Iterable<T> items) { for (T item : items) { put(item); } } public void put(T item) { double key = random.nextDouble(); Entry e = new Entry(key, item); if (count < this.size()) { /* The reservoir has not been filled yet; add the item immediately. * Note: we can cast the count to an integer here because the size * of the reservoir is limited to the capacity of a single int. */ reservoir.add((int) count, e); } else { if (key < ((double) this.size() / (count + 1))) { int position = random.nextInt(this.size()); reservoir.set(position, e); } } count++; } public void merge(Reservoir<T> that, int size) { List<Entry> combinedEntries = new ArrayList<>(size); combinedEntries.addAll(this.reservoir); combinedEntries.addAll(that.reservoir); Collections.sort(combinedEntries); this.reservoir = new ArrayList<>(size); for (int i = 0; i < size; ++i) { this.reservoir.add(combinedEntries.get(i)); } } public void merge(Reservoir<T> that) { merge(that, this.size()); } /** * Retrieves the total number of items observed by the reservoir. Note that * this is different from the size of the reservoir, which represents the * number of items in the sample. * * @return the total number of items observed by this reservoir instance. */ public long count() { return this.count; } /** * Retrieves the size of the reservoir, which is the number of items * contained in the sample. * * @return reservoir sample size. */ public int size() { return this.size; } public List<Entry> entries() { return new ArrayList<>(this.reservoir); } public List<T> samples() { List<T> l = new ArrayList<>(this.size()); for (Entry e : this.reservoir) { l.add(e.value); } return l; } public double[] keys() { double[] k = new double[this.size()]; for (int i = 0; i < this.size(); ++i) { k[i] = this.reservoir.get(i).key; } return k; } public static void main(String[] args) { Reservoir<Double> rs = new Reservoir<>(20); Reservoir<Double> r2 = new Reservoir<>(20); Random r = new Random(); r.doubles(10000).filter(val -> val < 0.5).forEach(rs::put); r.doubles(10000).filter(val -> val < 0.10).forEach(r2::put); RunningStatistics stats = new RunningStatistics(); for (Reservoir<Double>.Entry e : rs.entries()) { System.out.println(e); stats.put(e.value); } System.out.println(stats); rs.merge(r2); stats = new RunningStatistics(); for (Reservoir<Double>.Entry e : rs.entries()) { System.out.println(e); stats.put(e.value); } System.out.println(stats); } }
package hudson.maven.reporters; import hudson.Util; import hudson.Extension; import hudson.maven.MavenBuild; import hudson.maven.MavenBuildProxy; import hudson.maven.MavenBuildProxy.BuildCallable; import hudson.maven.MavenBuilder; import hudson.maven.MavenModule; import hudson.maven.MavenProjectActionBuilder; import hudson.maven.MavenReporter; import hudson.maven.MavenReporterDescriptor; import hudson.maven.MojoInfo; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.junit.TestResult; import hudson.tasks.test.TestResultProjectAction; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.types.FileSet; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ListIterator; /** * Records the surefire test result. * @author Kohsuke Kawaguchi */ public class SurefireArchiver extends MavenReporter { private TestResult result; public boolean preExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException { if (isSurefireTest(mojo)) { // tell surefire:test to keep going even if there was a failure, // so that we can record this as yellow. // note that because of the way Maven works, just updating system property at this point is too late XmlPlexusConfiguration c = (XmlPlexusConfiguration) mojo.configuration.getChild("testFailureIgnore"); if(c!=null && c.getValue().equals("${maven.test.failure.ignore}") && System.getProperty("maven.test.failure.ignore")==null) c.setValue("true"); } return true; } public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException { if (!isSurefireTest(mojo)) return true; listener.getLogger().println(Messages.SurefireArchiver_Recording()); File reportsDir; if (mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")) { try { reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class); } catch (ComponentConfigurationException e) { e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir())); build.setResult(Result.FAILURE); return true; } } else { reportsDir = new File(pom.getBasedir(), "target/surefire-reports"); } if(reportsDir.exists()) { // surefire:test just skips itself when the current project is not a java project FileSet fs = Util.createFileSet(reportsDir,"*.xml","testng-results.xml,testng-failed.xml"); DirectoryScanner ds = fs.getDirectoryScanner(); if(ds.getIncludedFiles().length==0) // no test in this module return true; if(result==null) result = new TestResult(); result.parse(System.currentTimeMillis() - build.getMilliSecsSinceBuildStart(), ds); int failCount = build.execute(new BuildCallable<Integer, IOException>() { public Integer call(MavenBuild build) throws IOException, InterruptedException { SurefireReport sr = build.getAction(SurefireReport.class); if(sr==null) build.getActions().add(new SurefireReport(build, result, listener)); else sr.setResult(result,listener); if(result.getFailCount()>0) build.setResult(Result.UNSTABLE); build.registerAsProjectAction(new FactoryImpl()); return result.getFailCount(); } }); // if surefire plugin is going to kill maven because of a test failure, // intercept that (or otherwise build will be marked as failure) if(failCount>0 && error instanceof MojoFailureException) { MavenBuilder.markAsSuccess = true; } } return true; } /** * Up to 1.372, there was a bug that causes Hudson to persist {@link SurefireArchiver} with the entire test result * in it. If we are loading those, fix it up in memory to reduce the memory footprint. * * It'd be nice we can save the record to remove problematic portion, but that might have * additional side effect. */ public static void fixUp(List<MavenProjectActionBuilder> builders) { if (builders==null) return; for (ListIterator<MavenProjectActionBuilder> itr = builders.listIterator(); itr.hasNext();) { MavenProjectActionBuilder b = itr.next(); if (b instanceof SurefireArchiver) itr.set(new FactoryImpl()); } } /** * Part of the serialization data attached to {@link MavenBuild}. */ static final class FactoryImpl implements MavenProjectActionBuilder { public Collection<? extends Action> getProjectActions(MavenModule module) { return Collections.singleton(new TestResultProjectAction(module)); } } private boolean isSurefireTest(MojoInfo mojo) { if ((!mojo.is("com.sun.maven", "maven-junit-plugin", "test")) && (!mojo.is("org.sonatype.flexmojos", "flexmojos-maven-plugin", "test-run")) && (!mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test"))) return false; try { if (mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")) { Boolean skip = mojo.getConfigurationValue("skip", Boolean.class); if (((skip != null) && (skip))) { return false; } if (mojo.pluginName.version.compareTo("2.3") >= 0) { Boolean skipExec = mojo.getConfigurationValue("skipExec", Boolean.class); if (((skipExec != null) && (skipExec))) { return false; } } if (mojo.pluginName.version.compareTo("2.4") >= 0) { Boolean skipTests = mojo.getConfigurationValue("skipTests", Boolean.class); if (((skipTests != null) && (skipTests))) { return false; } } } else if (mojo.is("com.sun.maven", "maven-junit-plugin", "test")) { Boolean skipTests = mojo.getConfigurationValue("skipTests", Boolean.class); if (((skipTests != null) && (skipTests))) { return false; } } else if (mojo.is("org.sonatype.flexmojos", "flexmojos-maven-plugin", "test-run")) { Boolean skipTests = mojo.getConfigurationValue("skipTest", Boolean.class); if (((skipTests != null) && (skipTests))) { return false; } } } catch (ComponentConfigurationException e) { return false; } return true; } @Extension public static final class DescriptorImpl extends MavenReporterDescriptor { public String getDisplayName() { return Messages.SurefireArchiver_DisplayName(); } public SurefireArchiver newAutoInstance(MavenModule module) { return new SurefireArchiver(); } } private static final long serialVersionUID = 1L; }
package com.redhat.ceylon.eclipse.core.model.loader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.lang.model.type.TypeKind; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.eclipse.jdt.internal.compiler.lookup.BaseTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeParameterMirror; public class JDTType implements TypeMirror { private TypeBinding type; private String qualifiedName; private List<TypeMirror> typeArguments; private TypeKind typeKind; private TypeMirror componentType; private boolean upperBoundSet = false; private boolean lowerBoundSet = false; private TypeMirror upperBound; private TypeMirror lowerBound; private boolean declaredClassSet; private LookupEnvironment lookupEnvironment; private JDTClass declaredClass; private boolean typeParameterSet; private JDTTypeParameter typeParameter; public JDTType(TypeBinding type, LookupEnvironment lookupEnvironment) { this.type = type; this.lookupEnvironment = lookupEnvironment; } @Override public String getQualifiedName() { if (qualifiedName == null) { // type params are not qualified if(type instanceof TypeVariableBinding) qualifiedName = new String(type.qualifiedSourceName()); else qualifiedName = JDTUtils.getFullyQualifiedName(type); } return qualifiedName; } @Override public List<TypeMirror> getTypeArguments() { if (typeArguments == null) { if(type instanceof ParameterizedTypeBinding && ! (type instanceof RawTypeBinding)){ TypeBinding[] javaTypeArguments = ((ParameterizedTypeBinding)type).arguments; if (javaTypeArguments == null) { javaTypeArguments = new TypeBinding[0]; } typeArguments = new ArrayList<TypeMirror>(javaTypeArguments.length); for(TypeBinding typeArgument : javaTypeArguments) typeArguments.add(typeArgument != type ? new JDTType(typeArgument, lookupEnvironment) : this); } else { return Collections.emptyList(); } } return typeArguments; } @Override public TypeKind getKind() { if (typeKind == null) { return findKind(); } return typeKind; } private TypeKind findKind() { if(type instanceof ArrayBinding) return TypeKind.ARRAY; if(type instanceof TypeVariableBinding) return TypeKind.TYPEVAR; if(type instanceof WildcardBinding) return TypeKind.WILDCARD; if(type instanceof BaseTypeBinding){ switch(type.id) { case TypeIds.T_boolean : return TypeKind.BOOLEAN; case TypeIds.T_byte : return TypeKind.BYTE; case TypeIds.T_char : return TypeKind.CHAR; case TypeIds.T_short : return TypeKind.SHORT; case TypeIds.T_int : return TypeKind.INT; case TypeIds.T_long : return TypeKind.LONG; case TypeIds.T_float : return TypeKind.FLOAT; case TypeIds.T_double : return TypeKind.DOUBLE; case TypeIds.T_void : return TypeKind.VOID; } } if(type instanceof ReferenceBinding) return TypeKind.DECLARED; throw new RuntimeException("Unknown type: "+type); } @Override public TypeMirror getComponentType() { if (componentType == null) { TypeBinding jdtComponentType = ((ArrayBinding)type).leafComponentType; componentType = new JDTType(jdtComponentType, lookupEnvironment); } return componentType; } @Override public boolean isPrimitive() { return type.isBaseType(); } @Override public TypeMirror getUpperBound() { if (!upperBoundSet) { if (type.isWildcard()) { WildcardBinding wildcardBinding = (WildcardBinding) type; if (wildcardBinding.boundKind == Wildcard.EXTENDS) { TypeBinding upperBoundBinding = wildcardBinding.bound; if (upperBoundBinding != null) { upperBound = new JDTType(upperBoundBinding, lookupEnvironment); } } } upperBoundSet = true; } return upperBound; } @Override public TypeMirror getLowerBound() { if (!lowerBoundSet) { if (type.isWildcard()) { WildcardBinding wildcardBinding = (WildcardBinding) type; if (wildcardBinding.boundKind == Wildcard.SUPER) { TypeBinding lowerBoundBinding = wildcardBinding.bound; if (lowerBoundBinding != null) { lowerBound = new JDTType(lowerBoundBinding, lookupEnvironment); } } } lowerBoundSet = true; } return lowerBound; } @Override public boolean isRaw() { return type.isRawType(); } @Override public ClassMirror getDeclaredClass() { if(!declaredClassSet){ if(type instanceof ReferenceBinding){ declaredClass = new JDTClass((ReferenceBinding) type, lookupEnvironment); } declaredClassSet = true; } return declaredClass; } @Override public TypeParameterMirror getTypeParameter() { if(!typeParameterSet){ if(type instanceof TypeVariableBinding){ typeParameter = new JDTTypeParameter((TypeVariableBinding) type, lookupEnvironment); } typeParameterSet = true; } return typeParameter; } }
package joshie.harvestmoon; import java.util.HashMap; import java.util.Map; import java.util.UUID; import joshie.harvestmoon.animals.AnimalTrackerServer; import joshie.harvestmoon.calendar.CalendarServer; import joshie.harvestmoon.crops.CropTrackerServer; import joshie.harvestmoon.mining.MineTrackerServer; import joshie.harvestmoon.player.PlayerDataServer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.WorldSavedData; import net.minecraftforge.common.UsernameCache; public class HMSavedData extends WorldSavedData { public static final String DATA_NAME = "HM-Data"; private CalendarServer calendar = new CalendarServer(); private AnimalTrackerServer animals = new AnimalTrackerServer(); private CropTrackerServer crops = new CropTrackerServer(); private MineTrackerServer mines = new MineTrackerServer(); private HashMap<UUID, PlayerDataServer> players = new HashMap(); public HMSavedData(String string) { super(string); } public AnimalTrackerServer getAnimalTracker() { return animals; } public CalendarServer getCalendar() { return calendar; } public CropTrackerServer getCropTracker() { return crops; } public MineTrackerServer getMineTracker() { return mines; } public PlayerDataServer getPlayerData(EntityPlayerMP player) { UUID uuid = player.getPersistentID(); if (players.containsKey(uuid)) { return players.get(uuid); } else { //If this UUID was not found, Search the username cache for this players username String name = player.getCommandSenderName(); for (Map.Entry<UUID, String> entry : UsernameCache.getMap().entrySet()) { if (entry.getValue().equals(name)) { uuid = entry.getKey(); break; } } if (players.containsKey(uuid)) { return players.get(uuid); } else { PlayerDataServer data = new PlayerDataServer(player); players.put(uuid, data); markDirty(); return players.get(uuid); } } } @Override public void readFromNBT(NBTTagCompound nbt) { calendar.readFromNBT(nbt.getCompoundTag("Calendar")); animals.readFromNBT(nbt.getCompoundTag("AnimalTracker")); crops.readFromNBT(nbt.getCompoundTag("CropTracker")); mines.readFromNBT(nbt.getCompoundTag("MineTracker")); NBTTagList tag_list_players = nbt.getTagList("PlayerTracker", 10); for (int i = 0; i < tag_list_players.tagCount(); i++) { NBTTagCompound tag = tag_list_players.getCompoundTagAt(i); PlayerDataServer data = new PlayerDataServer(); data.readFromNBT(tag); UUID uuid = new UUID(tag.getLong("UUIDMost"), tag.getLong("UUIDLeast")); players.put(uuid, data); } } @Override public void writeToNBT(NBTTagCompound nbt) { NBTTagCompound tag_calendar = new NBTTagCompound(); calendar.writeToNBT(tag_calendar); nbt.setTag("Calendar", tag_calendar); NBTTagCompound tag_animals = new NBTTagCompound(); animals.writeToNBT(tag_animals); nbt.setTag("AnimalTracker", tag_animals); NBTTagCompound tag_crops = new NBTTagCompound(); crops.writeToNBT(tag_crops); nbt.setTag("CropTracker", tag_crops); NBTTagCompound tag_mines = new NBTTagCompound(); mines.writeToNBT(tag_mines); nbt.setTag("MineTracker", tag_mines); NBTTagList tag_list_players = new NBTTagList(); for (Map.Entry<UUID, PlayerDataServer> entry : players.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { NBTTagCompound tag = new NBTTagCompound(); entry.getValue().writeToNBT(tag); tag_list_players.appendTag(tag); } } nbt.setTag("PlayerTracker", tag_list_players); } }
package VASSAL.build.module.turn; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingConstants; import VASSAL.build.AutoConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.Chatter; import VASSAL.build.module.GameComponent; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.properties.MutablePropertiesContainer; import VASSAL.build.module.properties.MutableProperty; import VASSAL.command.Command; import VASSAL.command.CommandEncoder; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.Configurer; import VASSAL.configure.ConfigurerFactory; import VASSAL.configure.FormattedStringConfigurer; import VASSAL.configure.IconConfigurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.PlayerIdFormattedStringConfigurer; import VASSAL.configure.StringEnum; import VASSAL.configure.StringEnumConfigurer; import VASSAL.configure.VisibilityCondition; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatableConfigurerFactory; import VASSAL.tools.FormattedString; import VASSAL.tools.IconButton; import VASSAL.tools.LaunchButton; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.NamedKeyStrokeListener; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.UniqueIdManager; /** * Generic Turn Counter */ public class TurnTracker extends TurnComponent implements CommandEncoder, GameComponent, ActionListener, UniqueIdManager.Identifyable { protected static UniqueIdManager idMgr = new UniqueIdManager("TurnTracker"); //$NON-NLS-1$ protected static final String COMMAND_PREFIX = "TURN"; //$NON-NLS-1$ public static final String NAME = "name"; //$NON-NLS-1$ public static final String HOT_KEY = "hotkey"; //$NON-NLS-1$ public static final String NEXT_HOT_KEY = "nexthotkey"; //$NON-NLS-1$ public static final String PREV_HOT_KEY = "prevhotkey"; //$NON-NLS-1$ public static final String ICON = "icon"; //$NON-NLS-1$ public static final String BUTTON_TEXT = "buttonText"; //$NON-NLS-1$ public static final String BUTTON_TOOLTIP = "buttonTooltip"; //$NON-NLS-1$ public static final String TURN_FORMAT = "turnFormat"; //$NON-NLS-1$ public static final String REPORT_FORMAT = "reportFormat"; //$NON-NLS-1$ public static final String TOOLTIP = "tooltip"; //$NON-NLS-1$ public static final String LENGTH = "length"; //$NON-NLS-1$ public static final String LENGTH_STYLE = "lengthStyle"; //$NON-NLS-1$ protected static final String FONT_SIZE = "turnFontSize"; //$NON-NLS-1$ protected static final String FONT_BOLD = "turnFontBold"; //$NON-NLS-1$ protected static final String DOCKED = "turnDocked"; //$NON-NLS-1$ /** Variable name for reporting format */ protected static final String OLD_TURN = "oldTurn"; //$NON-NLS-1$ protected static final String NEW_TURN = "newTurn"; //$NON-NLS-1$ protected static final String LEVEL = "level"; //$NON-NLS-1$ protected static final String TURN_FONT = "Dialog"; protected static String SET_COMMAND; protected static String DOCK_COMMAND; protected static String UNDOCK_COMMAND; protected static final String NEXT = "Next"; protected static final String PREV = "Prev"; protected static final String SET = "Set"; protected static final String PROP_VALUE = "_value"; //$NON-NLS-1$ protected static final String PROP_COMMAND = "_command"; //$NON-NLS-1$ protected static final String[] FONT_FAMILYS = new String[] { "Dialog", "DialogInput", "Monospaced", "SanSerif", "Serif"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ protected static final String LENGTH_VARIABLE = "Variable"; protected static final String LENGTH_MAXIMUM = "Maximum"; protected static final String LENGTH_FIXED = "Fixed"; protected FormattedString turnFormat = new FormattedString("$"+LEVEL+"1$ $"+LEVEL+"2$ $"+LEVEL+"3$ $"+LEVEL+"4$"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ protected FormattedString reportFormat = new FormattedString("* <$" + GlobalOptions.PLAYER_ID //$NON-NLS-1$ + "$> Turn Updated from $"+OLD_TURN+"$ to $"+NEW_TURN+"$"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ protected TurnWindow turnWindow; protected TurnWidget turnWidget; protected JPanel launchWidget; protected SetDialog setDialog; protected LaunchButton launch; protected NamedKeyStrokeListener nextListener; protected NamedKeyStrokeListener prevListener; protected String savedState = ""; //$NON-NLS-1$ protected String savedSetState = ""; //$NON-NLS-1$ protected String savedTurn = ""; //$NON-NLS-1$ protected JPopupMenu popup; protected int currentLevel = 0; protected String id; protected int width = -1; protected String lengthStyle = LENGTH_MAXIMUM; protected MutableProperty.Impl lastCommand = new MutableProperty.Impl(SET,this); protected MutableProperty.Impl lastTurn = new MutableProperty.Impl("",this); public TurnTracker() { ActionListener al = new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (!isDocked()) { turnWindow.setControls(); turnWindow.setVisible(!turnWindow.isShowing()); turnWindow.setFocusable(true); } } }; setConfigureName(Resources.getString("TurnTracker.turn")); //$NON-NLS-1$ launch = new LaunchButton(Resources.getString("TurnTracker.turn"), BUTTON_TOOLTIP, BUTTON_TEXT, HOT_KEY, ICON, al); //$NON-NLS-1$ launch.setToolTipText(Resources.getString("TurnTracker.turn_tracker")); //$NON-NLS-1$ SET_COMMAND = Resources.getString("TurnTracker.set_turn"); //$NON-NLS-1$ DOCK_COMMAND = Resources.getString("General.dock"); //$NON-NLS-1$ UNDOCK_COMMAND = Resources.getString("General.undock"); //$NON-NLS-1$ // Create preferences final IntConfigurer size = new IntConfigurer(FONT_SIZE, Resources.getString("TurnTracker.size_pref"), 14); //$NON-NLS-1$ final BooleanConfigurer bold = new BooleanConfigurer(FONT_BOLD, Resources.getString("TurnTracker.bold_pref"), Boolean.FALSE); //$NON-NLS-1$ final BooleanConfigurer docked = new BooleanConfigurer(DOCKED, Resources.getString("TurnTracker.docked_pref"), Boolean.FALSE); //$NON-NLS-1$ String prefTab = Resources.getString("TurnTracker.turn_counter"); //$NON-NLS-1$ GameModule.getGameModule().getPrefs().addOption(prefTab, size); GameModule.getGameModule().getPrefs().addOption(prefTab, bold); GameModule.getGameModule().getPrefs().addOption(prefTab, docked); size.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { setDisplayFont(); }}); bold.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { setDisplayFont(); }}); docked.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { setDocked(isDocked()); }}); // Set up listeners for prev/next hotkeys nextListener = new NamedKeyStrokeListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turnWidget.doNext(); } }); GameModule.getGameModule().addKeyStrokeListener(nextListener); prevListener = new NamedKeyStrokeListener(new ActionListener() { public void actionPerformed(ActionEvent e) { turnWidget.doPrev(); } }); GameModule.getGameModule().addKeyStrokeListener(prevListener); // Create the displayable widget turnWidget = new TurnWidget(); } public String getState() { final SequenceEncoder se = new SequenceEncoder('|'); se.append(currentLevel); final Iterator<TurnLevel> i = getTurnLevels(); while (i.hasNext()) { final TurnLevel level = i.next(); se.append(level.getState()); } return se.getValue(); } public void setState(String newState) { final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(newState, '|'); currentLevel = sd.nextInt(0); final Iterator<TurnLevel> i = getTurnLevels(); while (i.hasNext()) { final TurnLevel level = i.next(); level.setState(sd.nextToken("")); //$NON-NLS-1$ } setLaunchToolTip(); updateTurnDisplay(SET); } protected void setLaunchToolTip() { launch.setToolTipText(getTurnString()); } /* * Module level Configuration stuff */ public String[] getAttributeNames() { return new String[] { NAME, BUTTON_TEXT, ICON, BUTTON_TOOLTIP, HOT_KEY, NEXT_HOT_KEY, PREV_HOT_KEY, TURN_FORMAT, REPORT_FORMAT, TOOLTIP, LENGTH_STYLE, LENGTH }; } public void setAttribute(String key, Object value) { if (NAME.equals(key)) { clearGlobalProperties(); setConfigureName((String) value); lastCommand.setPropertyName(getConfigureName()+PROP_COMMAND); lastTurn.setPropertyName(getConfigureName()+PROP_VALUE); } else if (REPORT_FORMAT.equals(key)) { reportFormat.setFormat((String) value); } else if (TURN_FORMAT.equals(key)) { turnFormat.setFormat((String) value); } else if (TOOLTIP.equals(key)) { turnWidget.setLabelToolTipText((String) value); } else if (LENGTH.equals(key)) { if (value instanceof String) { value = Integer.valueOf((String) value); } width = ((Integer) value).intValue(); } else if (LENGTH_STYLE.equals(key)) { lengthStyle = (String) value; if (LENGTH_VARIABLE.equals(lengthStyle)) { width = 0; } else if (LENGTH_MAXIMUM.equals(lengthStyle)) { width = -1; } } else if (NEXT_HOT_KEY.equals(key)) { if (value instanceof String) { value = NamedHotKeyConfigurer.decode((String) value); } nextListener.setKeyStroke((NamedKeyStroke) value); turnWidget.setNextStroke((NamedKeyStroke) value); } else if (PREV_HOT_KEY.equals(key)) { if (value instanceof String) { value = NamedHotKeyConfigurer.decode((String) value); } prevListener.setKeyStroke((NamedKeyStroke) value); turnWidget.setPrevStroke((NamedKeyStroke) value); } else { launch.setAttribute(key, value); } } protected void setWidgetWidth() { if (LENGTH_FIXED.equals(lengthStyle)) { turnWidget.setWidth(width); } else if (LENGTH_MAXIMUM.equals(lengthStyle)) { turnWidget.setWidth(getMaximumWidth()); } else { turnWidget.setWidth(0); } } /** * Calculate the maximum width for the turnWidget to display * any item. * * First calculate the maximum string that can be displayed, then * convert this to a width based on the display font. * * @return Maximum Width */ protected int getMaximumWidth() { String maxString = getMaximumTurnString(); int max = turnWidget.getWidth(maxString); return max+2; } protected void setDisplayFont() { turnWidget.setLabelFont(getDisplayFont()); if (!isDocked() && turnWindow != null) { turnWindow.pack(); } } protected Font getDisplayFont() { int style = getFontStyle(); int size = getFontSize(); return new Font(TURN_FONT, style, size); } protected void setFontSize() { setDisplayFont(); } protected int getFontSize() { return ((Integer) GameModule.getGameModule().getPrefs().getValue(FONT_SIZE)).intValue(); } protected int getFontStyle() { return ((Boolean) GameModule.getGameModule().getPrefs().getValue(FONT_BOLD)).booleanValue() ? 1 : 0; } protected boolean isDocked() { return ((Boolean) GameModule.getGameModule().getPrefs().getValue(DOCKED)).booleanValue(); } protected void setDocked(boolean dock) { final GameModule g = GameModule.getGameModule(); g.getPrefs().setValue(DOCKED, Boolean.valueOf(dock)); launch.setVisible( !dock && ( getAttributeValueString(BUTTON_TEXT).length() > 0 || getAttributeValueString(ICON).length() > 0 ) ); if (dock) { turnWindow.setWidget(null); turnWindow.setVisible(false); launchWidget.add(turnWidget, BorderLayout.CENTER); launchWidget.setVisible(g.getGameState().isGameStarted()); } else { launchWidget.setVisible(false); launchWidget.remove(turnWidget); turnWindow.setWidget(turnWidget); turnWindow.setVisible(g.getGameState().isGameStarted()); turnWindow.setFocusable(true); } } public String getAttributeValueString(String key) { if (NAME.equals(key)) { return getConfigureName() + ""; //$NON-NLS-1$ } else if (REPORT_FORMAT.equals(key)) { return reportFormat.getFormat(); } else if (TURN_FORMAT.equals(key)) { return turnFormat.getFormat(); } else if (TOOLTIP.equals(key)) { return turnWidget.getLabelToolTipText(); } else if (LENGTH.equals(key)) { return String.valueOf(width); } else if (LENGTH_STYLE.equals(key)) { return lengthStyle; } else if (NEXT_HOT_KEY.equals(key)) { return NamedHotKeyConfigurer.encode(nextListener.getNamedKeyStroke()); } else if (PREV_HOT_KEY.equals(key)) { return NamedHotKeyConfigurer.encode(prevListener.getNamedKeyStroke()); } else { return launch.getAttributeValueString(key); } } public String[] getAttributeDescriptions() { return new String[] { "Name: ", "Button text: ", "Button Icon: ", "Button Tooltip: ", "Show/hide Hotkey: ", "Next Turn Hotkey: ", "Previous Turn Hotkey: ", "Turn Name Format: ", "Report Format: ", "Turn Label Tooltip Text: ", "Turn Label Length: ", "Turn label Display length: " }; } public Class<?>[] getAttributeTypes() { return new Class<?>[] { String.class, String.class, IconConfig.class, String.class, NamedKeyStroke.class, NamedKeyStroke.class, NamedKeyStroke.class, TurnFormatConfig.class, ReportFormatConfig.class, String.class, LengthStyleConfig.class, Integer.class }; } public static class IconConfig implements ConfigurerFactory { public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new IconConfigurer(key, name, ((TurnTracker) c).launch.getAttributeValueString(ICON)); } } public static class TurnFormatConfig implements TranslatableConfigurerFactory { public Configurer getConfigurer(AutoConfigurable c, String key, String name) { TurnTracker t = (TurnTracker) c; String s[] = new String[t.getLevelCount()]; for (int i = 0; i < s.length; i++) { s[i] = LEVEL+(i+1); } return new FormattedStringConfigurer(key, name, s); } } public static class ReportFormatConfig implements TranslatableConfigurerFactory { public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new PlayerIdFormattedStringConfigurer(key, name, new String[] {OLD_TURN, NEW_TURN } ); } } public static class LengthStyleConfig extends StringEnum { public String[] getValidValues(AutoConfigurable target) { return new String[]{LENGTH_VARIABLE, LENGTH_FIXED, LENGTH_MAXIMUM}; } } public VisibilityCondition getAttributeVisibility(String name) { if (LENGTH.equals(name)) { return new VisibilityCondition() { public boolean shouldBeVisible() { return LENGTH_FIXED.equals(lengthStyle); } }; } else { return null; } } public Class<?>[] getAllowableConfigureComponents() { return new Class<?>[] { CounterTurnLevel.class, ListTurnLevel.class, TurnGlobalHotkey.class }; } public static String getConfigureTypeName() { return "Turn Counter"; } public void addTo(Buildable b) { //Create the turn window turnWindow = new TurnWindow(); turnWindow.pack(); turnWindow.setVisible(false); launchWidget = new JPanel(); launchWidget.setLayout(new BorderLayout()); launchWidget.setBorder(BorderFactory.createEtchedBorder()); GameModule.getGameModule().getToolBar().add(launchWidget); launchWidget.setAlignmentY(0.0F); launchWidget.setVisible(false); GameModule.getGameModule().getToolBar().add(launch); launch.setAlignmentY(0.0F); launch.setEnabled(false); setDocked(isDocked()); GameModule.getGameModule().addCommandEncoder(this); GameModule.getGameModule().getGameState().addGameComponent(this); idMgr.add(this); //Global Property support lastCommand.addTo((MutablePropertiesContainer) b); lastTurn.addTo((MutablePropertiesContainer) b); } public void removeFrom(Buildable b) { GameModule.getGameModule().getToolBar().remove(launch); GameModule.getGameModule().getToolBar().remove(launchWidget); GameModule.getGameModule().removeCommandEncoder(this); GameModule.getGameModule().getGameState().removeGameComponent(this); lastCommand.removeFromContainer(); lastTurn.removeFromContainer(); clearGlobalProperties(); } public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("TurnTracker.htm"); //$NON-NLS-1$ //$NON-NLS-2$ } public void setId(String id) { this.id = id; } public String getId() { return id; } protected void captureState() { savedState = getState(); savedTurn = getTurnString(); } protected void save() { if (!savedState.equals(getState())) { reportFormat.setProperty(OLD_TURN, savedTurn); reportFormat.setProperty(NEW_TURN, getTurnString()); String s = updateString(reportFormat.getText(), new String[] { "\\n", "\\t" }, new String[] { " - ", " " }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ Command c = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), "* "+s); c.execute(); c.append(new SetTurn(this, savedState)); GameModule.getGameModule().sendAndLog(c); setLaunchToolTip(); } captureState(); } /** * Calculate the maximum sized turn string that can be generated * by any turn combination. * * @return maximum turn string */ protected String getMaximumTurnString() { List<String> levels = new ArrayList<String>(); for (Buildable b : getBuildables()) { if (b instanceof TurnLevel) { ((TurnLevel) b).findMaximumStrings(levels, 0); } } turnFormat.clearProperties(); for (int i = 0; i < levels.size(); i++) { turnFormat.setProperty(LEVEL+(i+1), levels.get(i)); } return turnFormat.getText(GameModule.getGameModule()); } /** * Build the turn string to be displayed from the currently * active Child TurnLevel's * @return Turn String */ protected String getTurnString() { turnFormat.clearProperties(); List<TurnLevel> turnDesc = getActiveChildLevels(); for (int i = 0; i < 15; i++) { turnFormat.setProperty(LEVEL+(i+1), i < turnDesc.size() ? turnDesc.get(i).getTurnString() : ""); } return turnFormat.getText(GameModule.getGameModule()); } /** * A list of all active TurnLevels within the TurnTracker * @return */ protected List<TurnLevel> getActiveChildLevels() { ArrayList<TurnLevel> levels = new ArrayList<TurnLevel>(); TurnLevel level = getTurnLevel(currentLevel); if (level != null) { levels.add(level); levels.addAll(level.getActiveChildLevels()); } return levels; } protected int getLevelCount() { return getActiveChildLevels().size(); } protected void next() { if (getTurnLevelCount() == 0) { return; } TurnLevel level = getTurnLevel(currentLevel); level.advance(); if (level.hasRolledOver()) { currentLevel++; if (currentLevel >= getTurnLevelCount()) { currentLevel = 0; } getTurnLevel(currentLevel).setLow(); } updateTurnDisplay(NEXT); doGlobalkeys(); } protected void prev() { if (getTurnLevelCount() == 0) { return; } TurnLevel level = getTurnLevel(currentLevel); level.retreat(); if (level.hasRolledOver()) { currentLevel if (currentLevel < 0) { currentLevel = getTurnLevelCount()-1; } getTurnLevel(currentLevel).setHigh(); } updateTurnDisplay(PREV); doGlobalkeys(); } protected void doGlobalkeys() { for (TurnGlobalHotkey key : getComponentsOf(TurnGlobalHotkey.class)) { key.apply(); } } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals(SET_COMMAND)) { set(); } else if (command.equals(DOCK_COMMAND)) { setDocked(true); } else if (command.equals(UNDOCK_COMMAND)) { setDocked(false); } } protected void set() { savedSetState = getState(); if (setDialog == null) { setDialog = new SetDialog(); setDialog.setTitle(Resources.getString("TurnTracker.set_turn2", getConfigureName())); //$NON-NLS-1$ } setDialog.setControls(this); setDialog.setVisible(true); } protected void updateTurnDisplay(String command) { lastCommand.setPropertyValue(command); lastTurn.setPropertyValue(getTurnString()); turnWidget.setControls(); turnWidget.repaint(); turnWindow.pack(); turnWindow.setFocusable(true); turnWindow.requestFocus(); } protected void clearGlobalProperties() { lastCommand.setPropertyValue(null); lastTurn.setPropertyValue(null); } public Command decode(String command) { Command comm = null; if (command.startsWith(COMMAND_PREFIX+getId())) { SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(command, '\t'); sd.nextToken(""); //$NON-NLS-1$ comm = new SetTurn(sd.nextToken(""), this); //$NON-NLS-1$ } return comm; } public String encode(Command c) { String s = null; if (c instanceof SetTurn) { SetTurn com = (SetTurn) c; SequenceEncoder se = new SequenceEncoder('\t'); se.append(COMMAND_PREFIX + com.getTurn().getId()); se.append(com.newState); return se.getValue(); } return s; } public void setup(boolean gameStarting) { launch.setEnabled(gameStarting); turnWindow.setVisible(false); launchWidget.setVisible(isDocked() && gameStarting); if (gameStarting) { lastCommand.setPropertyValue(SET); lastTurn.setPropertyValue(""); turnWidget.setControls(); setWidgetWidth(); } else { reset(); } } protected void reset() { for (int i = 0; i < getTurnLevelCount(); i++) { (getTurnLevel(i)).reset(); } currentLevel = 0; setLaunchToolTip(); clearGlobalProperties(); } public String updateString(String str, String[] from, String[] to) { final StringBuilder s = new StringBuilder(str); for (int i = 0; i < from.length; i++) { replace(s, from[i], to[i]); } return s.toString(); } public void replace(StringBuilder s, String from, String to) { int i = s.indexOf(from); while (i >= 0) { s = s.replace(i, i+2, to); i = s.indexOf(from); } } /** @deprecated Use {@link #replace(StringBuilder,String,String)} instead. */ @Deprecated public void replace(StringBuffer s, String from, String to) { int i = s.indexOf(from); while (i >= 0) { s = s.replace(i, i+2, to); i = s.indexOf(from); } } public Command getRestoreCommand() { return new SetTurn(getState(), this); } protected class TurnWindow extends JDialog { private static final long serialVersionUID = 1L; protected TurnWidget widget; protected TurnWindow() { super(GameModule.getGameModule().getFrame()); setTitle(getConfigureName()); pack(); setLocation(100, 100); setFocusable(true); } protected void setWidget(TurnWidget t) { if (t == null) { if (widget != null) { remove(widget); } } else { add(t); } pack(); } protected void setControls() { if (widget != null) { widget.setControls(); } pack(); } } protected class TurnWidget extends JPanel implements MouseListener { private static final long serialVersionUID = 1L; private IconButton nextButton; private IconButton prevButton; protected final int BUTTON_SIZE = 22; protected JLabel turnLabel = new JLabel(); protected TurnWidget() { super(); initComponents(); } public void setLabelFont(Font displayFont) { turnLabel.setFont(displayFont); } public void setWidth(int length) { if (length > 0) { turnLabel.setMinimumSize(new Dimension(length, BUTTON_SIZE)); turnLabel.setPreferredSize(new Dimension(length, BUTTON_SIZE)); } else { turnLabel.setMinimumSize(null); turnLabel.setPreferredSize(null); } } public void setLabelToolTipText(String tooltip) { turnLabel.setToolTipText(tooltip); } public String getLabelToolTipText() { return turnLabel.getToolTipText(); } public Color getColor() { return turnLabel.getBackground(); } public int getWidth(String text) { return turnLabel.getGraphics().getFontMetrics().stringWidth(text); } protected void doNext() { captureState(); next(); save(); } protected void doPrev() { captureState(); prev(); save(); } protected void initComponents() { setLayout(new BorderLayout(5, 5)); nextButton = new IconButton(IconButton.PLUS_ICON, BUTTON_SIZE); setNextStroke(nextListener.getNamedKeyStroke()); nextButton.setAlignmentY(Component.TOP_ALIGNMENT); nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doNext(); }}); prevButton = new IconButton(IconButton.MINUS_ICON, BUTTON_SIZE); setPrevStroke(prevListener.getNamedKeyStroke()); prevButton.setAlignmentY(Component.TOP_ALIGNMENT); prevButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doPrev(); }}); // Next, the Label containing the Turn Text turnLabel.setFont(getDisplayFont()); turnLabel.setFocusable(false); turnLabel.setHorizontalTextPosition(JLabel.CENTER); turnLabel.setHorizontalAlignment(SwingConstants.CENTER); turnLabel.addMouseListener(this); turnLabel.setBackground(Color.WHITE); turnLabel.setToolTipText(Resources.getString("TurnTracker.click_to_configure")); //$NON-NLS-1$ add(prevButton, BorderLayout.LINE_START); add(turnLabel, BorderLayout.CENTER); add(nextButton, BorderLayout.LINE_END); addMouseListener(this); } public void setNextStroke(NamedKeyStroke key) { final String tooltip = Resources.getString("TurnTracker.next_turn") + (key == null ? "" : " " + NamedHotKeyConfigurer.getFancyString(key)); nextButton.setToolTipText(tooltip); } public void setPrevStroke(NamedKeyStroke key) { final String tooltip = Resources.getString("TurnTracker.prev_turn") + //$NON-NLS-1$ (key == null ? "" : " " + NamedHotKeyConfigurer.getFancyString(key)); //$NON-NLS-1$ //$NON-NLS-2$ prevButton.setToolTipText(tooltip); } public void setControls() { String s = updateString(getTurnString(), new String[] { "\\n", "\\t" }, new String[] { "\n", " " }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ turnLabel.setText(s); } public void mouseClicked(MouseEvent e) { if (e.isMetaDown()) { doPopup(e.getPoint()); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void doPopup(Point p) { buildPopup(); if (isShowing()) { popup.show(this, p.x, p.y); } } } protected void buildPopup() { popup = new JPopupMenu(); popup.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { turnWidget.repaint(); } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { turnWidget.repaint(); } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { } }); JMenuItem item; // Dock/Undock if (isDocked()) { item = new JMenuItem(UNDOCK_COMMAND); } else { item = new JMenuItem(DOCK_COMMAND); } item.addActionListener(this); popup.add(item); // Set Current Turn directly item = new JMenuItem(SET_COMMAND); item.addActionListener(this); popup.add(item); // Configure List Items JMenu config = new JMenu(Resources.getString("TurnTracker.configure")); //$NON-NLS-1$ for (int i = 0; i < getTurnLevelCount(); i++) { getTurnLevel(i).buildConfigMenu(config); } if (config.getItemCount() > 0) { popup.add(config); } } protected void addItem(JMenu menu, String command) { JMenuItem item = new JMenuItem(command); item.addActionListener(this); menu.add(item); } private static final Dimension FILLER = new Dimension(0, 3); protected class SetDialog extends JDialog { private static final long serialVersionUID = 1L; protected JPanel panel; protected JPanel controls = null; protected JPanel levelControls = null; protected Component childControls = null; protected TurnTracker turn; protected JDialog me; protected SetDialog() { super(GameModule.getGameModule().getFrame()); initComponents(); setLocation(100, 100); me = this; } protected void initComponents() { setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { cancelSet(); setVisible(false); } }); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); add(panel); JPanel p = new JPanel(); JButton saveButton = new JButton(Resources.getString(Resources.SAVE)); saveButton.setToolTipText(Resources.getString("TurnTracker.save_changes")); //$NON-NLS-1$ p.add(saveButton); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSet(); setVisible(false); } }); JButton cancelButton = new JButton(Resources.getString(Resources.CANCEL)); cancelButton.setToolTipText(Resources.getString("TurnTracker.discard_changes")); //$NON-NLS-1$ cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancelSet(); setVisible(false); } }); p.add(cancelButton); add(p); } public void setControls(TurnTracker turn) { this.turn = turn; if (controls != null) { panel.remove(controls); } controls = new JPanel(); controls.setLayout(new BoxLayout(controls, BoxLayout.Y_AXIS)); levelControls = new JPanel(); levelControls.setLayout(new BoxLayout(levelControls, BoxLayout.Y_AXIS)); if (getTurnLevelCount() > 1) { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.setBorder(BorderFactory.createLineBorder(Color.black)); String s[] = new String[getTurnLevelCount()]; for (int i = 0; i < s.length; i++) { s[i] = getTurnLevel(i).getConfigureName(); } StringEnumConfigurer e = new StringEnumConfigurer(null, Resources.getString("TurnTracker.select"), s); //$NON-NLS-1$ e.setValue(getTurnLevel(currentLevel).getConfigureName()); e.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { String option = ((StringEnumConfigurer) e.getSource()).getValueString(); for (int i = 0; i < getTurnLevelCount(); i++) { if (option.equals(getTurnLevel(i).getConfigureName())) { currentLevel = i; updateTurnDisplay(SET); addChildControls(); } } }}); p.add(Box.createRigidArea(FILLER)); p.add(e.getControls()); p.add(Box.createRigidArea(FILLER)); levelControls.add(p); levelControls.add(Box.createRigidArea(FILLER)); } addChildControls(); controls.add(levelControls); panel.add(controls); pack(); } protected void addChildControls () { if (childControls != null) { levelControls.remove(childControls); } childControls = getTurnLevel(currentLevel).getSetControls(me, turn); levelControls.add(childControls); pack(); } } protected void cancelSet() { setState(savedSetState); turnWindow.setVisible(true); turnWindow.setFocusable(true); } protected void saveSet() { save(); updateTurnDisplay(SET); doGlobalkeys(); } public static class SetTurn extends Command { private String oldState; private String newState; private TurnTracker turn; public SetTurn(String newState, TurnTracker t) { this.newState = newState; oldState = t.getState(); turn = t; } public SetTurn(TurnTracker t, String oldState) { newState = t.getState(); this.oldState = oldState; turn = t; } public TurnTracker getTurn() { return turn; } protected void executeCommand() { turn.setState(newState); } protected Command myUndoCommand() { return new SetTurn(oldState, turn); } } }
package com.redhat.ceylon.eclipse.imp.builder; import static com.redhat.ceylon.compiler.typechecker.model.Util.formatPath; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.tools.JavaFileObject; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.io.ZipInputStream; import net.lingala.zip4j.model.FileHeader; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.Token; import org.eclipse.core.resources.IBuildConfiguration; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ProjectScope; 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.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.imp.builder.MarkerCreator; import org.eclipse.imp.core.ErrorHandler; import org.eclipse.imp.language.Language; import org.eclipse.imp.language.LanguageRegistry; import org.eclipse.imp.model.ISourceProject; import org.eclipse.imp.model.ModelFactory; import org.eclipse.imp.model.ModelFactory.ModelException; import org.eclipse.imp.parser.IMessageHandler; import org.eclipse.imp.preferences.IPreferencesService; import org.eclipse.imp.preferences.PreferenceConstants; import org.eclipse.imp.preferences.PreferencesService; import org.eclipse.imp.runtime.PluginBase; import org.eclipse.imp.runtime.RuntimePlugin; import org.eclipse.jdt.core.IClasspathAttribute; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.console.IConsoleManager; import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.console.MessageConsoleStream; import org.eclipse.ui.progress.UIJob; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.compiler.java.codegen.CeylonCompilationUnit; import com.redhat.ceylon.compiler.java.loader.CeylonClassReader; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.loader.mirror.JavacClass; import com.redhat.ceylon.compiler.java.tools.CeylonLog; import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager; import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl; import com.redhat.ceylon.compiler.java.tools.CeyloncTool; import com.redhat.ceylon.compiler.java.tools.LanguageCompiler; import com.redhat.ceylon.compiler.java.util.RepositoryLister; import com.redhat.ceylon.compiler.java.util.ShaSigner; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.loader.ModelLoaderFactory; import com.redhat.ceylon.compiler.loader.SourceDeclarationVisitor; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.ExternalUnit; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.parser.CeylonParser; import com.redhat.ceylon.compiler.typechecker.parser.LexError; import com.redhat.ceylon.compiler.typechecker.parser.ParseError; import com.redhat.ceylon.compiler.typechecker.tree.Message; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory; import com.redhat.ceylon.eclipse.core.cpcontainer.CeylonClasspathContainer; import com.redhat.ceylon.eclipse.core.cpcontainer.CeylonClasspathUtil; import com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader; import com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader.SourceFileObjectManager; import com.redhat.ceylon.eclipse.core.model.loader.mirror.JDTClass; import com.redhat.ceylon.eclipse.core.model.loader.mirror.SourceClass; import com.redhat.ceylon.eclipse.core.model.loader.model.JDTModuleManager; import com.redhat.ceylon.eclipse.imp.core.CeylonReferenceResolver; import com.redhat.ceylon.eclipse.imp.editor.CeylonEditor; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.util.EclipseLogger; import com.redhat.ceylon.eclipse.util.ErrorVisitor; import com.redhat.ceylon.eclipse.vfs.IFileVirtualFile; import com.redhat.ceylon.eclipse.vfs.IFolderVirtualFile; import com.redhat.ceylon.eclipse.vfs.ResourceVirtualFile; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Names; import com.sun.tools.javac.util.Options; /** * A builder may be activated on a file containing ceylon code every time it has * changed (when "Build automatically" is on), or when the programmer chooses to * "Build" a project. * * TODO This default implementation was generated from a template, it needs to * be completed manually. */ public class CeylonBuilder extends IncrementalProjectBuilder{ public static boolean compileWithJDTModelLoader = true; /** * Extension ID of the Ceylon builder, which matches the ID in the * corresponding extension definition in plugin.xml. */ public static final String BUILDER_ID = CeylonPlugin.PLUGIN_ID + ".ceylonBuilder"; /** * A marker ID that identifies problems detected by the builder */ public static final String PROBLEM_MARKER_ID = CeylonPlugin.PLUGIN_ID + ".ceylonProblem"; /*public static final String TASK_MARKER_ID = CeylonPlugin.PLUGIN_ID + ".ceylonTask";*/ public static final String LANGUAGE_NAME = "ceylon"; public static final Language LANGUAGE = LanguageRegistry .findLanguage(LANGUAGE_NAME); private final static Map<IProject, TypeChecker> typeCheckers = new HashMap<IProject, TypeChecker>(); private final static Map<IProject, List<IPath>> sourceFolders = new HashMap<IProject, List<IPath>>(); private final static Map<IProject, List<IFile>> projectSources = new HashMap<IProject, List<IFile>>(); public static final String CEYLON_CONSOLE= "Ceylon"; private long startTime; private IPreferencesService fPrefService; private final Collection<IFile> fSourcesToCompile= new HashSet<IFile>(); public static List<PhasedUnit> getUnits(IProject project) { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); TypeChecker tc = typeCheckers.get(project); if (tc!=null) { for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } return result; } public static List<PhasedUnit> getUnits() { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); for (TypeChecker tc: typeCheckers.values()) { for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } return result; } public static List<PhasedUnit> getUnits(String[] projects) { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); if (projects!=null) { for (Map.Entry<IProject, TypeChecker> me: typeCheckers.entrySet()) { for (String pname: projects) { if (me.getKey().getName().equals(pname)) { result.addAll(me.getValue().getPhasedUnits().getPhasedUnits()); } } } } return result; } protected PluginBase getPlugin() { return CeylonPlugin.getInstance(); } public String getBuilderID() { return BUILDER_ID; } protected String getErrorMarkerID() { return PROBLEM_MARKER_ID; } protected String getWarningMarkerID() { return PROBLEM_MARKER_ID; } protected String getInfoMarkerID() { return PROBLEM_MARKER_ID; } private ISourceProject getSourceProject() { ISourceProject sourceProject = null; try { sourceProject = ModelFactory.open(getProject()); } catch (ModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sourceProject; } public static boolean isCeylon(IFile file) { return LANGUAGE.hasExtension(file.getFileExtension()); } public static boolean isJava(IFile file) { return JavaCore.isJavaLikeFileName(file.getName()); } public static boolean isCeylonOrJava(IFile file) { return isCeylon(file) || isJava(file); } /** * Decide whether a file needs to be build using this builder. Note that * <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should * never return true for the same file. * * @return true iff an arbitrary file is a ceylon source file. */ protected boolean isSourceFile(IFile file) { IPath path = file.getFullPath(); //getProjectRelativePath(); if (path == null) return false; if (!isCeylonOrJava(file)) { return false; } IProject project = file.getProject(); if (project != null) { for (IPath sourceFolder: getSourceFolders(project)) { if (sourceFolder.isPrefixOf(path)) { return true; } } } return false; } public static JDTModelLoader getProjectModelLoader(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return (JDTModelLoader) ((JDTModuleManager) typeChecker.getPhasedUnits().getModuleManager()).getModelLoader(); } final static class BooleanHolder { public boolean value; }; @Override protected IProject[] build(final int kind, Map args, IProgressMonitor monitor) throws CoreException { if (getPreferencesService().getProject() == null) { getPreferencesService().setProject(getProject()); } boolean emitDiags= getDiagPreference(); fSourcesToCompile.clear(); IProject project = getProject(); ISourceProject sourceProject = getSourceProject(); if (sourceProject == null) { return new IProject[0]; } TypeChecker typeChecker = typeCheckers.get(project); List<PhasedUnit> builtPhasedUnits = Collections.emptyList(); List<IProject> requiredProjects = getRequiredProjects(project); final BooleanHolder mustDoFullBuild = new BooleanHolder(); final BooleanHolder mustResolveClasspathContainer = new BooleanHolder(); final IResourceDelta currentDelta = getDelta(getProject()); boolean somethingToDo = chooseBuildTypeFromDeltas(kind, currentDelta, monitor, typeChecker, mustDoFullBuild, mustResolveClasspathContainer); if (! somethingToDo) { return requiredProjects.toArray(new IProject[0]); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (mustResolveClasspathContainer.value) { IJavaProject javaProject = JavaCore.create(project); if (javaProject != null) { List<CeylonClasspathContainer> cpContainers = CeylonClasspathUtil.getCeylonClasspathContainers(javaProject); for (CeylonClasspathContainer container : cpContainers) { container.launchResolve(false, null); } return requiredProjects.toArray(new IProject[0]); } } try { startTime = System.nanoTime(); MessageConsole console = findConsole(); IBuildConfiguration[] buildConfsBefore = getContext().getAllReferencedBuildConfigs(); if (buildConfsBefore.length == 0) { console.activate(); } getConsoleStream().println("\n==================================="); getConsoleStream().println(timedMessage("Starting Ceylon build on project : " + getProject())); getConsoleStream().println(" boolean binariesGenerationOK; sourceFolders.clear(); if (mustDoFullBuild.value) { monitor.beginTask("Full Ceylon build of project " + project.getName(), 9); getConsoleStream().println(timedMessage("Full build of model")); if (monitor.isCanceled()) { throw new OperationCanceledException(); } builtPhasedUnits = fullBuild(project, sourceProject, monitor); getConsoleStream().println(timedMessage("Full generation of class files...")); monitor.subTask("Generating binaries"); if (monitor.isCanceled()) { throw new OperationCanceledException(); } final List<IFile> allSources = getProjectSources(project); binariesGenerationOK = generateBinaries(project, sourceProject, allSources, monitor); monitor.worked(1); getConsoleStream().println(successMessage(binariesGenerationOK)); } else { monitor.beginTask("Incremental Ceylon build of project " + project.getName(), 7); getConsoleStream().println(timedMessage("Incremental build of model")); List<IResourceDelta> projectDeltas = new ArrayList<IResourceDelta>(); projectDeltas.add(currentDelta); for (IProject requiredProject : requiredProjects) { projectDeltas.add(getDelta(requiredProject)); } final List<IFile> filesToRemove = new ArrayList<IFile>(); final Set<IFile> fChangedSources = new HashSet<IFile>(); monitor.subTask("Scanning deltas"); for (final IResourceDelta projectDelta : projectDeltas) { if (projectDelta != null) { List<IPath> deltaSourceFolders = getSourceFolders((IProject) projectDelta.getResource()); for (IResourceDelta sourceDelta : projectDelta.getAffectedChildren()) { if (! deltaSourceFolders.contains(sourceDelta.getResource().getFullPath())) { // Not a real Ceylon source folder : don't scan changes to it continue; } if (emitDiags) getConsoleStream().println("==> Scanning resource delta for '" + projectDelta.getResource().getName() + "'... <=="); sourceDelta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource instanceof IFile) { IFile file= (IFile) resource; if (isCeylonOrJava(file)) { fChangedSources.add(file); if (projectDelta == currentDelta) { if (delta.getKind() == IResourceDelta.REMOVED) { filesToRemove.add((IFile) resource); } } } return false; } return true; } }); if (emitDiags) getConsoleStream().println("Delta scan completed for project '" + projectDelta.getResource().getName() + "'..."); } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); monitor.worked(1); monitor.subTask("Scanning dependencies of deltas"); if (fChangedSources.size() > 0) { Collection<IFile> changeDependents= new HashSet<IFile>(); changeDependents.addAll(fChangedSources); if (emitDiags) { getConsoleStream().println("Changed files:"); dumpSourceList(changeDependents); } boolean changed = false; do { Collection<IFile> additions= new HashSet<IFile>(); for(Iterator<IFile> iter= changeDependents.iterator(); iter.hasNext(); ) { IFile srcFile= iter.next(); IProject currentFileProject = srcFile.getProject(); TypeChecker currentFileTypeChecker = null; if (currentFileProject == project) { currentFileTypeChecker = typeChecker; } else { currentFileTypeChecker = getProjectTypeChecker(currentFileProject); } Set<PhasedUnit> phasedUnitsDependingOn = Collections.emptySet(); phasedUnitsDependingOn = getDependentsOf(srcFile, currentFileTypeChecker, currentFileProject); for(PhasedUnit dependingPhasedUnit : phasedUnitsDependingOn ) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } IFile depFile= (IFile) ((IFileVirtualFile) dependingPhasedUnit.getUnitFile()).getResource(); IProject newDependencyProject = depFile.getProject(); if (newDependencyProject == project || newDependencyProject == currentFileProject) { additions.add(depFile); } else { // System.out.println("a depending resource is in a third-party project"); } } } changed = changeDependents.addAll(additions); } while (changed); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnits.getPhasedUnits()) { Unit unit = phasedUnit.getUnit(); if (unit.getUnresolvedReferences().size() > 0) { IFile fileToAdd = (IFile) ((IFileVirtualFile)(phasedUnit.getUnitFile())).getResource(); if (fileToAdd.exists()) { fSourcesToCompile.add(fileToAdd); } } Set<Declaration> duplicateDeclarations = unit.getDuplicateDeclarations(); if (duplicateDeclarations.size() > 0) { IFile fileToAdd = (IFile) ((IFileVirtualFile)(phasedUnit.getUnitFile())).getResource(); if (fileToAdd.exists()) { fSourcesToCompile.add(fileToAdd); } for (Declaration duplicateDeclaration : duplicateDeclarations) { PhasedUnit duplicateDeclPU = CeylonReferenceResolver.getPhasedUnit(project, duplicateDeclaration); if (duplicateDeclPU != null) { IFile duplicateDeclFile = (IFile) ((IFileVirtualFile)(duplicateDeclPU.getUnitFile())).getResource(); if (duplicateDeclFile.exists()) { fSourcesToCompile.add(duplicateDeclFile); } } } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for(IFile f: changeDependents) { if (isSourceFile(f) && f.getProject() == project) { if (f.exists()) { fSourcesToCompile.add(f); } else { // If the file is moved : add a dependency on the new file if (currentDelta != null) { IResourceDelta removedFile = currentDelta.findMember(f.getProjectRelativePath()); if (removedFile != null && (removedFile.getFlags() & IResourceDelta.MOVED_TO) != 0 && removedFile.getMovedToPath() != null) { fSourcesToCompile.add(project.getFile(removedFile.getMovedToPath().removeFirstSegments(1))); } } } } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); monitor.subTask("Cleaning removed files"); removeObsoleteClassFiles(filesToRemove); for (IFile fileToRemove : filesToRemove) { if(isCeylon(fileToRemove)) { // Remove the ceylon phasedUnit (which will also remove the unit from the package) PhasedUnit phasedUnitToDelete = phasedUnits.getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(fileToRemove)); if (phasedUnitToDelete != null) { phasedUnits.removePhasedUnitForRelativePath(phasedUnitToDelete.getPathRelativeToSrcDir()); } } else if (isJava(fileToRemove)) { // Remove the external unit from the package Package pkg = retrievePackage(fileToRemove.getParent()); if (pkg != null) { Unit unitToRemove = null; for (Unit unitToTest : pkg.getUnits()) { if (unitToTest.getFilename().equals(fileToRemove.getName())) { unitToRemove = unitToTest; break; } } if (unitToRemove != null) { pkg.removeUnit(unitToRemove); } } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); monitor.subTask("Compiling " + fSourcesToCompile + " file(s)"); if (emitDiags) { getConsoleStream().println("All files to compile:"); dumpSourceList(fSourcesToCompile); } builtPhasedUnits = incrementalBuild(project, sourceProject, monitor); if (builtPhasedUnits== null) return new IProject[0]; if (builtPhasedUnits.isEmpty() && fSourcesToCompile.isEmpty()) { return requiredProjects.toArray(new IProject[0]); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); monitor.subTask("Generating binaries"); getConsoleStream().println(timedMessage("Incremental generation of class files...")); binariesGenerationOK = generateBinaries(project, sourceProject, fSourcesToCompile, monitor); if (monitor.isCanceled()) { throw new OperationCanceledException(); } getConsoleStream().println(successMessage(binariesGenerationOK)); monitor.worked(1); monitor.subTask("Updating referencing projects"); getConsoleStream().println(timedMessage("Updating model in referencing projects")); updateExternalPhasedUnitsInReferencingProjects(project, builtPhasedUnits); monitor.worked(1); } if (!binariesGenerationOK) { // Add a problem marker if binary generation went wrong for ceylon files IMarker marker = project.createMarker(PROBLEM_MARKER_ID); marker.setAttribute(IMarker.MESSAGE, "Bytecode generation has failed on some Ceylon source files. Look at the Ceylon console for more information."); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); } typeChecker = typeCheckers.get(project); // could have been instanciated and added into the map by the full build monitor.subTask("Collecting dependencies"); getConsoleStream().println(timedMessage("Collecting dependencies")); List<PhasedUnits> phasedUnitsForDependencies = new ArrayList<PhasedUnits>(); for (IProject requiredProject : requiredProjects) { TypeChecker requiredProjectTypeChecker = getProjectTypeChecker(requiredProject); if (requiredProjectTypeChecker != null) { phasedUnitsForDependencies.add(requiredProjectTypeChecker.getPhasedUnits()); } } for (PhasedUnit pu : builtPhasedUnits) { pu.collectUnitDependencies(typeChecker.getPhasedUnits(), phasedUnitsForDependencies); } monitor.worked(1); monitor.done(); return requiredProjects.toArray(new IProject[0]); } finally { getConsoleStream().println(" getConsoleStream().println(timedMessage("End Ceylon build on project : " + getProject())); getConsoleStream().println("==================================="); } } public boolean chooseBuildTypeFromDeltas(final int kind, final IResourceDelta currentDelta, IProgressMonitor monitor, TypeChecker typeChecker, final CeylonBuilder.BooleanHolder mustDoFullBuild, final CeylonBuilder.BooleanHolder mustResolveClasspathContainer) { mustDoFullBuild.value = kind == FULL_BUILD || kind == CLEAN_BUILD || typeChecker == null; mustResolveClasspathContainer.value = false; final BooleanHolder sourceModified = new BooleanHolder(); sourceModified.value = false; boolean somethingToDo = false; if (! mustDoFullBuild.value) { if (currentDelta != null) { try { currentDelta.accept(new IResourceDeltaVisitor() { @Override public boolean visit(IResourceDelta resourceDelta) throws CoreException { IResource resource = resourceDelta.getResource(); if (resourceDelta.getKind() == IResourceDelta.REMOVED) { if (resource instanceof IFolder) { IFolder folder = (IFolder) resource; Package pkg = retrievePackage(folder); // If a package has been removed, then trigger a full build if (pkg != null) { mustDoFullBuild.value = true; return true; } } } if (resource instanceof IFile) { if (resource.getName().equals(ModuleManager.PACKAGE_FILE)) { // If a package descriptor has been added, removed or changed, trigger a full build mustDoFullBuild.value = true; return false; } if (resource.getName().equals(ModuleManager.MODULE_FILE)) { // If a module descriptor has been added, removed or changed, resolve the Ceylon classpath container mustResolveClasspathContainer.value = true; return false; } if ( isCeylonOrJava((IFile)resource) ) { sourceModified.value = true; } } if (resource instanceof IProject && ((resourceDelta.getFlags() & IResourceDelta.DESCRIPTION) != 0)) { mustDoFullBuild.value = true; return false; } return true; } }); } catch (CoreException e) { getPlugin().getLog().log(new Status(IStatus.ERROR, getPlugin().getID(), e.getLocalizedMessage(), e)); mustDoFullBuild.value = true; } } else { mustDoFullBuild.value = true; } } return mustDoFullBuild.value || mustResolveClasspathContainer.value || sourceModified.value; } private static String successMessage(boolean binariesGenerationOK) { return " " + (binariesGenerationOK ? "...binary generation succeeded" : "...binary generation FAILED"); } private Set<PhasedUnit> getDependentsOf(IFile srcFile, TypeChecker currentFileTypeChecker, IProject currentFileProject) { if(LANGUAGE.hasExtension(srcFile.getRawLocation().getFileExtension())) { PhasedUnit phasedUnit = currentFileTypeChecker.getPhasedUnits().getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(srcFile)); if (phasedUnit != null) { return phasedUnit.getDependentsOf(); } } else { Unit unit = getJavaUnit(currentFileProject, srcFile); if (unit instanceof ExternalUnit) { return ((ExternalUnit)unit).getDependentsOf(); } } return Collections.emptySet(); } private void updateExternalPhasedUnitsInReferencingProjects( IProject project, List<PhasedUnit> builtPhasedUnits) { for (IProject referencingProject : project.getReferencingProjects()) { TypeChecker referencingTypeChecker = getProjectTypeChecker(referencingProject); if (referencingTypeChecker != null) { List<PhasedUnit> referencingPhasedUnits = new ArrayList<PhasedUnit>(); for (PhasedUnit builtPhasedUnit : builtPhasedUnits) { List<PhasedUnits> phasedUnitsOfDependencies = referencingTypeChecker.getPhasedUnitsOfDependencies(); for (PhasedUnits phasedUnitsOfDependency : phasedUnitsOfDependencies) { String relativePath = builtPhasedUnit.getPathRelativeToSrcDir(); PhasedUnit referencingPhasedUnit = phasedUnitsOfDependency.getPhasedUnitFromRelativePath(relativePath); if (referencingPhasedUnit != null) { phasedUnitsOfDependency.removePhasedUnitForRelativePath(relativePath); PhasedUnit newReferencingPhasedUnit = new PhasedUnit(referencingPhasedUnit.getUnitFile(), referencingPhasedUnit.getSrcDir(), builtPhasedUnit.getCompilationUnit(), referencingPhasedUnit.getPackage(), phasedUnitsOfDependency.getModuleManager(), referencingTypeChecker.getContext(), builtPhasedUnit.getTokens()); phasedUnitsOfDependency.addPhasedUnit(newReferencingPhasedUnit.getUnitFile(), newReferencingPhasedUnit); // replace referencingPhasedUnit referencingPhasedUnits.add(newReferencingPhasedUnit); } } } for (PhasedUnit pu : referencingPhasedUnits) { pu.scanDeclarations(); } for (PhasedUnit pu : referencingPhasedUnits) { pu.scanTypeDeclarations(); } for (PhasedUnit pu : referencingPhasedUnits) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } } } } private static PhasedUnit parseFileToPhasedUnit(ModuleManager moduleManager, Context context, ResourceVirtualFile file, ResourceVirtualFile srcDir, Package pkg) { ANTLRInputStream input; try { input = new ANTLRInputStream(file.getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } CeylonLexer lexer = new CeylonLexer(input); CommonTokenStream tokenStream = new CommonTokenStream(lexer); CeylonParser parser = new CeylonParser(tokenStream); Tree.CompilationUnit cu; try { cu = parser.compilationUnit(); } catch (org.antlr.runtime.RecognitionException e) { throw new RuntimeException(e); } List<CommonToken> tokens = new ArrayList<CommonToken>(tokenStream.getTokens().size()); tokens.addAll(tokenStream.getTokens()); List<LexError> lexerErrors = lexer.getErrors(); for (LexError le : lexerErrors) { //System.out.println("Lexer error in " + file.getName() + ": " + le.getMessage()); cu.addLexError(le); } lexerErrors.clear(); List<ParseError> parserErrors = parser.getErrors(); for (ParseError pe : parserErrors) { //System.out.println("Parser error in " + file.getName() + ": " + pe.getMessage()); cu.addParseError(pe); } parserErrors.clear(); PhasedUnit newPhasedUnit = new PhasedUnit(file, srcDir, cu, pkg, moduleManager, context, tokens); return newPhasedUnit; } private List<PhasedUnit> incrementalBuild(IProject project, ISourceProject sourceProject, IProgressMonitor monitor) { TypeChecker typeChecker = typeCheckers.get(project); ModuleManager moduleManager = typeChecker.getPhasedUnits().getModuleManager(); JDTModelLoader modelLoader = getProjectModelLoader(project); Context context = typeChecker.getContext(); Set<String> cleanedPackages = new HashSet<String>(); List<PhasedUnit> phasedUnitsToUpdate = new ArrayList<PhasedUnit>(); for (IFile fileToUpdate : fSourcesToCompile) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } // skip non-ceylon files if(!isCeylon(fileToUpdate)) { if (isJava(fileToUpdate)) { Unit toRemove = getJavaUnit(project, fileToUpdate); if(toRemove != null) { // If the unit is not null, the package should never be null toRemove.getPackage().removeUnit(toRemove); } else { String packageName = getPackageName(fileToUpdate); if (! cleanedPackages.contains(packageName)) { modelLoader.clearCachesOnPackage(packageName); } } } continue; } ResourceVirtualFile file = ResourceVirtualFile.createResourceVirtualFile(fileToUpdate); IPath srcFolderPath = retrieveSourceFolder(fileToUpdate); ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); PhasedUnit alreadyBuiltPhasedUnit = typeChecker.getPhasedUnits().getPhasedUnit(file); Package pkg = null; Set<PhasedUnit> dependentsOf = Collections.emptySet(); if (alreadyBuiltPhasedUnit!=null) { // Editing an already built file pkg = alreadyBuiltPhasedUnit.getPackage(); dependentsOf = alreadyBuiltPhasedUnit.getDependentsOf(); } else { IContainer packageFolder = file.getResource().getParent(); pkg = retrievePackage(packageFolder); if (pkg == null) { pkg = createNewPackage(packageFolder); } } PhasedUnit newPhasedUnit = parseFileToPhasedUnit(moduleManager, context, file, srcDir, pkg); newPhasedUnit.getDependentsOf().addAll(dependentsOf); phasedUnitsToUpdate.add(newPhasedUnit); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (phasedUnitsToUpdate.size() == 0) { return phasedUnitsToUpdate; } clearProjectMarkers(project); clearMarkersOn(fSourcesToCompile); for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (typeChecker.getPhasedUnits().getPhasedUnitFromRelativePath(phasedUnit.getPathRelativeToSrcDir()) != null) { typeChecker.getPhasedUnits().removePhasedUnitForRelativePath(phasedUnit.getPathRelativeToSrcDir()); } typeChecker.getPhasedUnits().addPhasedUnit(phasedUnit.getUnitFile(), phasedUnit); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { phasedUnit.validateTree(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { phasedUnit.scanDeclarations(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isTypeDeclarationsScanned()) { phasedUnit.scanTypeDeclarations(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isRefinementValidated()) { phasedUnit.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isFullyTyped()) { phasedUnit.analyseTypes(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { phasedUnit.analyseFlow(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } addProblemAndTaskMarkers(phasedUnitsToUpdate); return phasedUnitsToUpdate; } private Unit getJavaUnit(IProject project, IFile fileToUpdate) { IJavaElement javaElement = (IJavaElement) fileToUpdate.getAdapter(IJavaElement.class); if (javaElement instanceof ICompilationUnit) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; IJavaElement packageFragment = compilationUnit.getParent(); JDTModelLoader projectModelLoader = getProjectModelLoader(project); if (projectModelLoader != null) { Package pkg = projectModelLoader.findPackage(packageFragment.getElementName()); if (pkg != null) { for (Unit unit : pkg.getUnits()) { if (unit.getFilename().equals(fileToUpdate.getName())) { return unit; } } } } } return null; } private List<PhasedUnit> fullBuild(IProject project, ISourceProject sourceProject, IProgressMonitor monitor) throws CoreException { System.out.println("Starting ceylon full build of project " + project.getName()); monitor.subTask("Clearing existing markers"); clearProjectMarkers(project); clearMarkersOn(project); monitor.worked(1); TypeChecker alreadyExistingTypeChecker = getProjectTypeChecker(project); final TypeChecker typeChecker = alreadyExistingTypeChecker != null ? alreadyExistingTypeChecker : buildCeylonModelWithoutTypechecking(project, monitor); final List<PhasedUnit> listOfUnits = typeChecker.getPhasedUnits().getPhasedUnits(); monitor.subTask("Compiling Ceylon source files for project " + project.getName()); for (PhasedUnit pu : listOfUnits) { if (! pu.isDeclarationsScanned()) { pu.validateTree(); pu.scanDeclarations(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isTypeDeclarationsScanned()) { pu.scanTypeDeclarations(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { if (! pu.isRefinementValidated()) { pu.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isFullyTyped()) { pu.analyseTypes(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { pu.analyseFlow(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); monitor.subTask("Collecting Ceylon problems for project " + project.getName()); addProblemAndTaskMarkers(typeChecker.getPhasedUnits().getPhasedUnits()); monitor.worked(1); System.out.println("Finished ceylon full build of project " + project.getName()); return typeChecker.getPhasedUnits().getPhasedUnits(); } public static TypeChecker buildCeylonModelWithoutTypechecking( final IProject project, IProgressMonitor monitor) throws CoreException { monitor.subTask("Collecting Ceylon source files for project " + project.getName()); typeCheckers.remove(project); projectSources.remove(project); final List<IFile> scannedSources = new ArrayList<IFile>(); monitor.subTask("Setting up typechecker for project " + project.getName()); if (monitor.isCanceled()) { throw new OperationCanceledException(); } project.refreshLocal(IResource.DEPTH_INFINITE, monitor); final IJavaProject javaProject = JavaCore.create(project); TypeCheckerBuilder typeCheckerBuilder = new TypeCheckerBuilder() .verbose(false) .moduleManagerFactory(new ModuleManagerFactory(){ @Override public ModuleManager createModuleManager(Context context) { return new JDTModuleManager(context, javaProject); } }); List<String> repos = getUserRepositories(project); typeCheckerBuilder.setRepositoryManager(Util.makeRepositoryManager(repos, getModulesOutputDirectory(javaProject).getAbsolutePath(), new EclipseLogger())); final TypeChecker typeChecker = typeCheckerBuilder.getTypeChecker(); final PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); final JDTModuleManager moduleManager = (JDTModuleManager) phasedUnits.getModuleManager(); final Context context = typeChecker.getContext(); final JDTModelLoader modelLoader = (JDTModelLoader) moduleManager.getModelLoader(); final Module defaultModule = context.getModules().getDefaultModule(); monitor.worked(1); monitor.subTask("Parsing Ceylon source files for project " + project.getName()); if (monitor.isCanceled()) { throw new OperationCanceledException(); } final Collection<IPath> sourceFolders = getSourceFolders(project); for (final IPath srcAbsoluteFolderPath : sourceFolders) { final IPath srcFolderPath = srcAbsoluteFolderPath.makeRelativeTo(project.getFullPath()); final ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); IResource srcDirResource = srcDir.getResource(); if (! srcDirResource.exists()) { continue; } if (monitor.isCanceled()) { throw new OperationCanceledException(); } srcDirResource.accept(new IResourceVisitor() { private Module module; public boolean visit(IResource resource) throws CoreException { Package pkg; if (resource.equals(srcDir.getResource())) { IFile moduleFile = ((IFolder) resource).getFile(ModuleManager.MODULE_FILE); if (moduleFile.exists()) { moduleManager.addTopLevelModuleError(); } return true; } if (resource.getParent().equals(srcDir.getResource())) { // We've come back to a source directory child : // => reset the current Module to default and set the package to emptyPackage module = defaultModule; pkg = modelLoader.findPackage(""); assert(pkg != null); } if (resource instanceof IFolder) { List<String> pkgName = Arrays.asList(resource.getProjectRelativePath().makeRelativeTo(srcFolderPath).segments()); String pkgNameAsString = formatPath(pkgName); if ( module != defaultModule ) { if (! pkgNameAsString.startsWith(module.getNameAsString() + ".")) { // We've ran above the last module => reset module to default module = defaultModule; } } IFile moduleFile = ((IFolder) resource).getFile(ModuleManager.MODULE_FILE); if (moduleFile.exists()) { if ( module != defaultModule ) { moduleManager.addTwoModulesInHierarchyError(module.getName(), pkgName); } else { final List<String> moduleName = pkgName; //we don't know the version at this stage, will be filled later module = moduleManager.getOrCreateModule(moduleName, null); assert(module != null); } } pkg = modelLoader.findOrCreatePackage(module, pkgNameAsString); return true; } if (resource instanceof IFile) { IFile file = (IFile) resource; if (file.exists() && isCeylonOrJava(file)) { List<String> pkgName = Arrays.asList(file.getParent().getProjectRelativePath().makeRelativeTo(srcFolderPath).segments()); String pkgNameAsString = formatPath(pkgName); pkg = modelLoader.findOrCreatePackage(module, pkgNameAsString); if (isCeylon(file)) { if (scannedSources != null) { scannedSources.add(file); } ResourceVirtualFile virtualFile = ResourceVirtualFile.createResourceVirtualFile(file); PhasedUnit newPhasedUnit = parseFileToPhasedUnit(moduleManager, context, virtualFile, srcDir, pkg); phasedUnits.addPhasedUnit(virtualFile, newPhasedUnit); } if (isJava((IFile)resource)) { if (scannedSources != null) { scannedSources.add((IFile)resource); } } } } return false; } }); } monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } modelLoader.setupSourceFileObjects(typeChecker.getPhasedUnits().getPhasedUnits()); monitor.worked(1); // Parsing of ALL units in the source folder should have been done if (monitor.isCanceled()) { throw new OperationCanceledException(); } phasedUnits.getModuleManager().prepareForTypeChecking(); phasedUnits.visitModules(); //By now the language module version should be known (as local) //or we should use the default one. Module languageModule = context.getModules().getLanguageModule(); if (languageModule.getVersion() == null) { languageModule.setVersion(TypeChecker.LANGUAGE_MODULE_VERSION); } final ModuleValidator moduleValidator = new ModuleValidator(context, phasedUnits) { @Override protected void executeExternalModulePhases() { for (PhasedUnits dependencyPhasedUnits : getPhasedUnitsOfDependencies()) { modelLoader.addSourceArchivePhasedUnits(dependencyPhasedUnits.getPhasedUnits()); } // super.executeExternalModulePhases(); } }; monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } moduleValidator.verifyModuleDependencyTree(); typeChecker.setPhasedUnitsOfDependencies(moduleValidator.getPhasedUnitsOfDependencies()); typeCheckers.put(project, typeChecker); projectSources.put(project, scannedSources); UIJob refreshJob = new UIJob("Refresh Current Ceylon Editor") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { IEditorPart currentEditor = com.redhat.ceylon.eclipse.imp.editor.Util.getCurrentEditor(); if (currentEditor instanceof CeylonEditor) { ((CeylonEditor) currentEditor).scheduleParsing(); } return Status.OK_STATUS; } }; refreshJob.schedule(); if (monitor.isCanceled()) { throw new OperationCanceledException(); } return typeChecker; } private static void addProblemAndTaskMarkers(List<PhasedUnit> units) { for (PhasedUnit phasedUnit : units) { IFile file = getFile(phasedUnit); List<CommonToken> tokens = phasedUnit.getTokens(); phasedUnit.getCompilationUnit() .visit(new ErrorVisitor(new MarkerCreator(file, PROBLEM_MARKER_ID)) { @Override public int getSeverity(Message error, boolean expected) { return expected ? IMarker.SEVERITY_WARNING : IMarker.SEVERITY_ERROR; } }); addTaskMarkers(file, tokens); } } private boolean generateBinaries(IProject project, ISourceProject sourceProject, Collection<IFile> filesToCompile, IProgressMonitor monitor) throws CoreException { List<String> options = new ArrayList<String>(); String srcPath = ""; for (IPath sourceFolder : getSourceFolders(project)) { File sourcePathElement = toFile(project,sourceFolder.makeRelativeTo(project.getFullPath())); if (! srcPath.isEmpty()) { srcPath += File.pathSeparator; } srcPath += sourcePathElement.getAbsolutePath(); } options.add("-src"); options.add(srcPath); for (String repository : getUserRepositories(project)) { options.add("-rep"); options.add(repository); } String verbose = System.getProperty("ceylon.verbose"); if (verbose!=null && "true".equals(verbose)) { options.add("-verbose"); } options.add("-g:lines,vars,source"); IJavaProject javaProject = JavaCore.create(project); final File modulesOutputDir = getModulesOutputDirectory(javaProject); final File ceylonOutputDir = getCeylonOutputDirectory(javaProject); if (modulesOutputDir!=null) { options.add("-out"); options.add(modulesOutputDir.getAbsolutePath()); } java.util.List<File> javaSourceFiles = new ArrayList<File>(); java.util.List<File> sourceFiles = new ArrayList<File>(); for (IFile file : filesToCompile) { if(isCeylon(file)) sourceFiles.add(file.getRawLocation().toFile()); else if(isJava(file)) javaSourceFiles.add(file.getRawLocation().toFile()); } if (sourceFiles.size() > 0 || javaSourceFiles.size() > 0) { PrintWriter printWriter = new PrintWriter(getConsoleStream(), true); boolean success = true; if (! compileWithJDTModelLoader) { // first java source files if(!javaSourceFiles.isEmpty()){ compile(project, options, javaSourceFiles, printWriter); } } else { sourceFiles.addAll(javaSourceFiles); } // then ceylon source files if that last run worked if(!sourceFiles.isEmpty()){ success = compile(project, options, sourceFiles, printWriter); } if (modulesOutputDir != null) { monitor.subTask("Unzipping archives files in the Ceylon output folder"); List<String> extensionsToUnzip = Arrays.asList(".car"); new RepositoryLister(extensionsToUnzip).list(modulesOutputDir, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { try { ZipFile carFile = new ZipFile(path); carFile.extractAll(ceylonOutputDir.getAbsolutePath()); } catch (ZipException e) { e.printStackTrace(); } } }); } return success; } else return true; } private boolean compile(final IProject project, List<String> options, java.util.List<File> sourceFiles, PrintWriter printWriter) throws VerifyError { CeyloncTool compiler; try { compiler = new CeyloncTool(); } catch (VerifyError e) { System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?"); throw e; } final com.sun.tools.javac.util.Context context = new com.sun.tools.javac.util.Context(); context.put(com.sun.tools.javac.util.Log.outKey, printWriter); CeylonLog.preRegister(context); CeyloncFileManager fileManager = new CeyloncFileManager(context, true, null); //(CeyloncFileManager)compiler.getStandardFileManager(null, null, null); ArtifactContext ctx = null; Modules projectModules = getProjectModules(project); if (projectModules != null) { Module languageModule = projectModules.getLanguageModule(); ctx = new ArtifactContext(languageModule.getNameAsString(), languageModule.getVersion()); } else { ctx = new ArtifactContext("ceylon.language", TypeChecker.LANGUAGE_MODULE_VERSION); } List<String> classpathElements = new ArrayList<String>(); ctx.setSuffix(ArtifactContext.CAR); RepositoryManager repositoryManager = getProjectRepositoryManager(project); if (repositoryManager != null) { File languageModuleArchive; try { languageModuleArchive = repositoryManager.getArtifact(ctx); classpathElements.add(languageModuleArchive.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } } IJavaProject javaProject = JavaCore.create(project); IPath workspaceLocation = project.getWorkspace().getRoot().getLocation(); try { List<CeylonClasspathContainer> containers = CeylonClasspathUtil.getCeylonClasspathContainers(javaProject); for (CeylonClasspathContainer container : containers) { for (IClasspathEntry cpEntry : container.getClasspathEntries()) { classpathElements.add(cpEntry.getPath().toOSString()); } } classpathElements.add(workspaceLocation.append(javaProject.getOutputLocation()).toOSString()); } catch (JavaModelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } options.add("-classpath"); String classpath = ""; for (String cpElement : classpathElements) { if (! classpath.isEmpty()) { classpath += File.pathSeparator; } classpath += cpElement; } options.add(classpath); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles); if (compileWithJDTModelLoader) { context.put(LanguageCompiler.ceylonContextKey, getProjectTypeChecker(project).getContext()); context.put(LanguageCompiler.existingPhasedUnitsKey, getProjectTypeChecker(project).getPhasedUnits()); final JDTModelLoader modelLoader = getProjectModelLoader(project); modelLoader.setSourceFileObjectManager(new SourceFileObjectManager() { @Override public void setupSourceFileObjects(List<?> treeHolders) { for(Object treeHolder : treeHolders){ if (!(treeHolder instanceof CeylonCompilationUnit)) { continue; } final CeylonCompilationUnit tree = (CeylonCompilationUnit)treeHolder; CompilationUnit ceylonTree = tree.ceylonTree; final String pkgName = tree.getPackageName() != null ? tree.getPackageName().toString() : ""; ceylonTree.visit(new SourceDeclarationVisitor(){ @Override public void loadFromSource(Tree.Declaration decl) { String name = Util.quoteIfJavaKeyword(decl.getIdentifier().getText()); String fqn = pkgName.isEmpty() ? name : pkgName+"."+name; try{ CeylonClassReader.instance(context).enterClass(Names.instance(context).fromString(fqn), tree.getSourceFile()); } catch (AssertionError error){ // this happens when we have already registered a source file for this decl, so let's // print out a helpful message ClassMirror previousClass = modelLoader.lookupClassMirror(fqn); CeylonLog.instance(context).error("ceylon", "Duplicate declaration error: " + fqn + " is declared twice: once in " + tree.getSourceFile() + " and again in: " + fileName(previousClass)); } } }); } } }); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(ModelLoaderFactory.class, new ModelLoaderFactory() { @Override public AbstractModelLoader createModelLoader( com.sun.tools.javac.util.Context context) { return modelLoader; } }); } CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(printWriter, fileManager, null, options, null, compilationUnits1); boolean success=false; try { success = task.call(); } catch (Exception e) { e.printStackTrace(); } return success; } public static String fileName(ClassMirror c) { if (c instanceof JavacClass) { return ((JavacClass) c).classSymbol.classfile.getName(); } else if (c instanceof JDTClass) { return ((JDTClass) c).getFileName(); } else if (c instanceof SourceClass) { return ((SourceClass) c).getModelDeclaration().getUnit().getFilename(); } else { return "another file"; } } public static List<IProject> getRequiredProjects(IJavaProject javaProject) { List<IProject> requiredProjects = new ArrayList<IProject>(); try { for (String requiredProjectName : javaProject.getRequiredProjectNames()) { IProject requiredProject = javaProject.getProject().getWorkspace().getRoot().getProject(requiredProjectName); if (requiredProject != null) { requiredProjects.add(requiredProject); } } } catch (JavaModelException e) { e.printStackTrace(); } return requiredProjects; } public static List<IProject> getRequiredProjects(IProject project) { IJavaProject javaProject = JavaCore.create(project); if (javaProject == null) { return Collections.emptyList(); } return getRequiredProjects(javaProject); } public static List<String> getUserRepositories(IProject project) throws CoreException { List<String> userRepos = new ArrayList<String>(); File repo = getCeylonRepository(project); userRepos.add(repo.getAbsolutePath()); if (project != null) { List<IProject> requiredProjects = getRequiredProjects(project); for (IProject requiredProject : requiredProjects) { if (!requiredProject.isOpen()) { continue; } if (! requiredProject.hasNature(CeylonNature.NATURE_ID)) { continue; } IJavaProject requiredJavaProject = JavaCore.create(requiredProject); if (requiredJavaProject == null) { continue; } userRepos.add(getModulesOutputDirectory(requiredJavaProject).getAbsolutePath()); } /*userRepos.add(project.getLocation().append("modules").toOSString()); for (IProject requiredProject : requiredProjects) { userRepos.add(requiredProject.getLocation().append("modules").toOSString()); }*/ } return userRepos; } public static File getCeylonRepository(IProject project) { String repoPath = new ProjectScope(project) .getNode(CeylonPlugin.PLUGIN_ID) .get("repo", null); //project.getPersistentProperty(new QualifiedName(CeylonPlugin.PLUGIN_ID,"repo")); File repo; if (repoPath==null) { repo = CeylonPlugin.getInstance().getCeylonRepository(); } else { repo = CeylonPlugin.getCeylonRepository(repoPath); } return repo; } private static File toFile(IProject project, IPath path) { return project.getFolder(path).getRawLocation().toFile(); } /** * Clears all problem markers (all markers whose type derives from IMarker.PROBLEM) * from the given file. A utility method for the use of derived builder classes. */ private static void clearMarkersOn(IFile file) { try { clearTaskMarkersOn(file); file.deleteMarkers(CeylonBuilder.PROBLEM_MARKER_ID, true, IResource.DEPTH_INFINITE); } catch (CoreException e) { } } /** * Clears all problem markers (all markers whose type derives from IMarker.PROBLEM) * from the given file. A utility method for the use of derived builder classes. */ private static void clearMarkersOn(IResource resource) { try { clearTaskMarkersOn(resource); resource.deleteMarkers(CeylonBuilder.PROBLEM_MARKER_ID, true, IResource.DEPTH_INFINITE); } catch (CoreException e) { } } private static void clearProjectMarkers(IProject project) { try { project.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, IResource.DEPTH_ZERO); project.deleteMarkers(PROBLEM_MARKER_ID, true, IResource.DEPTH_ZERO); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void clearMarkersOn(Collection<IFile> files) { for(IFile file: files) { clearMarkersOn(file); } } private void dumpSourceList(Collection<IFile> sourcesToCompile) { MessageConsoleStream consoleStream= getConsoleStream(); for(Iterator<IFile> iter= sourcesToCompile.iterator(); iter.hasNext(); ) { IFile srcFile= iter.next(); consoleStream.println(" " + srcFile.getFullPath()); } } protected IPreferencesService getPreferencesService() { if (fPrefService == null) { fPrefService= new PreferencesService(null, getPlugin().getLanguageID()); } return fPrefService; } protected boolean getDiagPreference() { final IPreferencesService builderPrefSvc= getPlugin().getPreferencesService(); final IPreferencesService impPrefSvc= RuntimePlugin.getInstance().getPreferencesService(); boolean msgs= builderPrefSvc.isDefined(PreferenceConstants.P_EMIT_BUILDER_DIAGNOSTICS) ? builderPrefSvc.getBooleanPreference(PreferenceConstants.P_EMIT_BUILDER_DIAGNOSTICS) : impPrefSvc.getBooleanPreference(PreferenceConstants.P_EMIT_BUILDER_DIAGNOSTICS); return msgs; } /** * Refreshes all resources in the entire project tree containing the given resource. * Crude but effective. */ /*protected void doRefresh(final IResource resource) { IWorkspaceRunnable r= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { resource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } }; try { getProject().getWorkspace().run(r, resource.getProject(), IWorkspace.AVOID_UPDATE, null); } catch (CoreException e) { getPlugin().logException("Error while refreshing after a build", e); } }*/ /** * @return the ID of the marker type for the given marker severity (one of * <code>IMarker.SEVERITY_*</code>). If the severity is unknown/invalid, * returns <code>getInfoMarkerID()</code>. */ protected String getMarkerIDFor(int severity) { switch(severity) { case IMarker.SEVERITY_ERROR: return getErrorMarkerID(); case IMarker.SEVERITY_WARNING: return getWarningMarkerID(); case IMarker.SEVERITY_INFO: return getInfoMarkerID(); default: return getInfoMarkerID(); } } /** * Utility method to create a marker on the given resource using the given * information. * @param errorResource * @param startLine the line with which the error is associated * @param charStart the offset of the first character with which the error is associated * @param charEnd the offset of the last character with which the error is associated * @param message a human-readable text message to appear in the "Problems View" * @param severity the message severity, one of <code>IMarker.SEVERITY_*</code> */ public IMarker createMarker(IResource errorResource, int startLine, int charStart, int charEnd, String message, int severity) { try { // TODO Handle resources that are templates and not in user's workspace if (!errorResource.exists()) return null; IMarker m = errorResource.createMarker(getMarkerIDFor(severity)); final int MIN_ATTR= 4; final boolean hasStart= (charStart >= 0); final boolean hasEnd= (charEnd >= 0); final int numAttr= MIN_ATTR + (hasStart ? 1 : 0) + (hasEnd ? 1 : 0); String[] attrNames = new String[numAttr]; Object[] attrValues = new Object[numAttr]; // N.B. Any "null" values will be treated as undefined int idx= 0; attrNames[idx]= IMarker.LINE_NUMBER; attrValues[idx++]= startLine; attrNames[idx]= IMarker.MESSAGE; attrValues[idx++]= message; attrNames[idx]= IMarker.PRIORITY; attrValues[idx++]= IMarker.PRIORITY_HIGH; attrNames[idx]= IMarker.SEVERITY; attrValues[idx++]= severity; if (hasStart) { attrNames[idx]= IMarker.CHAR_START; attrValues[idx++]= charStart; } if (hasEnd) { attrNames[idx]= IMarker.CHAR_END; attrValues[idx++]= charEnd; } m.setAttributes(attrNames, attrValues); return m; } catch (CoreException e) { getPlugin().writeErrorMsg("Unable to create marker: " + e.getMessage()); } return null; } public static Shell getShell() { return RuntimePlugin.getInstance().getWorkbench() .getActiveWorkbenchWindow().getShell(); } /** * Posts a dialog displaying the given message as soon as "conveniently possible". * This is not a synchronous call, since this method will get called from a * different thread than the UI thread, which is the only thread that can * post the dialog box. */ protected void postMsgDialog(final String title, final String msg) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openInformation(getShell(), title, msg); } }); } /** * Posts a dialog displaying the given message as soon as "conveniently possible". * This is not a synchronous call, since this method will get called from a * different thread than the UI thread, which is the only thread that can * post the dialog box. */ protected void postQuestionDialog(final String title, final String query, final Runnable runIfYes, final Runnable runIfNo) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { boolean response= MessageDialog.openQuestion(getShell(), title, query); if (response) runIfYes.run(); else if (runIfNo != null) runIfNo.run(); } }); } protected static MessageConsoleStream getConsoleStream() { return findConsole().newMessageStream(); } private String timedMessage(String message) { long elapsedTimeMs = (System.nanoTime() - startTime) / 1000000; return String.format("[%1$10d] %2$s", elapsedTimeMs, message); } /** * Find or create the console with the given name * @param consoleName */ protected static MessageConsole findConsole() { String consoleName = CEYLON_CONSOLE; MessageConsole myConsole= null; final IConsoleManager consoleManager= ConsolePlugin.getDefault().getConsoleManager(); IConsole[] consoles= consoleManager.getConsoles(); for(int i= 0; i < consoles.length; i++) { IConsole console= consoles[i]; if (console.getName().equals(consoleName)) myConsole= (MessageConsole) console; } if (myConsole == null) { myConsole= new MessageConsole(consoleName, null); consoleManager.addConsoles(new IConsole[] { myConsole }); } // consoleManager.showConsoleView(myConsole); return myConsole; } private static void addTaskMarkers(IFile file, List<CommonToken> tokens) { //clearTaskMarkersOnFile(file); for (CommonToken token: tokens) { if (token.getType()==CeylonLexer.LINE_COMMENT) { int priority = priority(token); if (priority>=0) { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(IMessageHandler.SEVERITY_KEY, IMarker.SEVERITY_INFO); attributes.put(IMarker.PRIORITY, priority); attributes.put(IMarker.USER_EDITABLE, false); new MarkerCreator(file, IMarker.TASK) .handleSimpleMessage(token.getText().substring(2), token.getStartIndex(), token.getStopIndex(), token.getCharPositionInLine(), token.getCharPositionInLine(), token.getLine(), token.getLine(), attributes); } } } } private static void clearTaskMarkersOn(IResource resource) { try { resource.deleteMarkers(IMarker.TASK, false, IResource.DEPTH_INFINITE); } catch (CoreException e) { e.printStackTrace(); } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); IJavaProject javaProject = JavaCore.create(getProject()); final File modulesOutputDirectory = getModulesOutputDirectory(javaProject); if (modulesOutputDirectory != null) { monitor.subTask("Cleaning existing artifacts"); List<String> extensionsToDelete = Arrays.asList(".jar", ".car", ".src", ".sha1"); new RepositoryLister(extensionsToDelete).list(modulesOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && ! path.equals(modulesOutputDirectory)) { path.delete(); } } }); } final File ceylonOutputDirectory = getCeylonOutputDirectory(javaProject); if (ceylonOutputDirectory != null) { new RepositoryLister(Arrays.asList(".*")).list(ceylonOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && ! path.equals(ceylonOutputDirectory)) { path.delete(); } } }); } monitor.subTask("Clear project and source markers"); clearProjectMarkers(getProject()); clearMarkersOn(getProject()); } public static IFile getFile(PhasedUnit phasedUnit) { return (IFile) ((ResourceVirtualFile) phasedUnit.getUnitFile()).getResource(); } // generated files go into parent folder public static int priority(Token token) { String comment = token.getText().toLowerCase(); if (comment.startsWith("//todo")) { return IMarker.PRIORITY_NORMAL; } else if (comment.startsWith("//fix")) { return IMarker.PRIORITY_HIGH; } else { return -1; } } private static List<IFile> getProjectSources(IProject project) { return projectSources.get(project); } public static TypeChecker getProjectTypeChecker(IProject project) { return typeCheckers.get(project); } public static Modules getProjectModules(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return typeChecker.getContext().getModules(); } public static RepositoryManager getProjectRepositoryManager(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return typeChecker.getContext().getRepositoryManager(); } public static Iterable<IProject> getProjects() { return typeCheckers.keySet(); } public static void removeProjectTypeChecker(IProject project) { typeCheckers.remove(project); sourceFolders.remove(project); projectSources.remove(project); } /** * Read the IJavaProject classpath configuration and populate the ISourceProject's * build path accordingly. */ public static List<IPath> getSourceFolders(IProject theProject) { if (sourceFolders.containsKey(theProject)) { return sourceFolders.get(theProject); } IJavaProject javaProject = JavaCore.create(theProject); if (javaProject.exists()) { try { List<IPath> projectSourceFolders = new ArrayList<IPath>(); for (IClasspathEntry entry: javaProject.getResolvedClasspath(true)) { IPath path = entry.getPath(); if (isCeylonSourceEntry(entry)) { projectSourceFolders.add(path); } } sourceFolders.put(theProject, projectSourceFolders); return projectSourceFolders; } catch (JavaModelException e) { ErrorHandler.reportError(e.getMessage(), e); } } return Collections.emptyList(); } public static boolean isCeylonSourceEntry(IClasspathEntry entry) { if (entry.getEntryKind()!=IClasspathEntry.CPE_SOURCE) { return false; } for (IClasspathAttribute attribute : entry.getExtraAttributes()) { if (attribute.getName().equals("CEYLON") && "true".equalsIgnoreCase(attribute.getValue())) { return true; } } for (IPath exclusionPattern : entry.getExclusionPatterns()) { if (exclusionPattern.toString().endsWith(".ceylon")) { return false; } } return true; } private IPath retrieveSourceFolder(IFile file) { IPath path = file.getProjectRelativePath(); if (path == null) return null; if (! isCeylonOrJava(file)) return null; return retrieveSourceFolder(path); } // path is project-relative private IPath retrieveSourceFolder(IPath path) { IProject project = getProject(); if (project != null) { Collection<IPath> sourceFolders = getSourceFolders(project); for (IPath sourceFolderAbsolute : sourceFolders) { IPath sourceFolder = sourceFolderAbsolute.makeRelativeTo(project.getFullPath()); if (sourceFolder.isPrefixOf(path)) { return sourceFolder; } } } return null; } private Package retrievePackage(IResource folder) { String packageName = getPackageName(folder); if (packageName == null) { return null; } TypeChecker typeChecker = typeCheckers.get(folder.getProject()); Context context = typeChecker.getContext(); Modules modules = context.getModules(); for (Module module : modules.getListOfModules()) { for (Package p : module.getPackages()) { if (p.getQualifiedNameString().equals(packageName)) { return p; } } } return null; } public String getPackageName(IResource resource) { IContainer folder = null; if (resource instanceof IFile) { folder = resource.getParent(); } else { folder = (IContainer) resource; } String packageName = null; IPath folderPath = folder.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(folderPath); if (sourceFolder != null) { IPath relativeFolderPath = folderPath.makeRelativeTo(sourceFolder); packageName = relativeFolderPath.toString().replace('/', '.'); } return packageName; } private Package createNewPackage(IContainer folder) { IPath folderPath = folder.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(folderPath); if (sourceFolder == null) { return null; } IContainer parent = folder.getParent(); IPath packageRelativePath = folder.getProjectRelativePath().makeRelativeTo(parent.getProjectRelativePath()); Package parentPackage = null; while (parentPackage == null && ! parent.equals(folder.getProject())) { packageRelativePath = folder.getProjectRelativePath().makeRelativeTo(parent.getProjectRelativePath()); parentPackage = retrievePackage(parent); parent = parent.getParent(); } Context context = typeCheckers.get(folder.getProject()).getContext(); return createPackage(parentPackage, packageRelativePath, context.getModules()); } private Package createPackage(Package parentPackage, IPath packageRelativePath, Modules modules) { String[] packageSegments = packageRelativePath.segments(); if (packageSegments.length == 1) { Package pkg = new LazyPackage(CeylonBuilder.getProjectModelLoader(getProject())); List<String> parentName = null; if (parentPackage == null) { parentName = Collections.emptyList(); } else { parentName = parentPackage.getName(); } final ArrayList<String> name = new ArrayList<String>(parentName.size() + 1); name.addAll(parentName); name.add(packageRelativePath.segment(0)); pkg.setName(name); Module module = null; if (parentPackage != null) { module = parentPackage.getModule(); } if (module == null) { module = modules.getDefaultModule(); } module.getPackages().add(pkg); pkg.setModule(module); return pkg; } else { Package childPackage = createPackage(parentPackage, packageRelativePath.uptoSegment(1), modules); return createPackage(childPackage, packageRelativePath.removeFirstSegments(1), modules); } } private void removeObsoleteClassFiles(List<IFile> filesToRemove) { if (filesToRemove.size() == 0) { return; } Set<File> moduleJars = new HashSet<File>(); for (IFile file : filesToRemove) { IPath filePath = file.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(filePath); if (sourceFolder == null) { return; } Package pkg = retrievePackage(file.getParent()); if (pkg == null) { return; } IProject project = file.getProject(); Module module = pkg.getModule(); TypeChecker typeChecker = typeCheckers.get(project); if (typeChecker == null) { return; } IJavaProject javaProject = JavaCore.create(project); final File modulesOutputDirectory = getModulesOutputDirectory(javaProject); final File ceylonOutputDirectory = getCeylonOutputDirectory(javaProject); File moduleDir = Util.getModulePath(modulesOutputDirectory, module); File moduleJar = new File(moduleDir, Util.getModuleArchiveName(module)); if(moduleJar.exists()){ moduleJars.add(moduleJar); String relativeFilePath = filePath.makeRelativeTo(sourceFolder).toString(); try { ZipFile zipFile = new ZipFile(moduleJar); FileHeader fileHeader = zipFile.getFileHeader("META-INF/mapping.txt"); List<String> entriesToDelete = new ArrayList<String>(); ZipInputStream zis = zipFile.getInputStream(fileHeader); try { Properties mapping = new Properties(); mapping.load(zis); for (String className : mapping.stringPropertyNames()) { String sourceFile = mapping.getProperty(className); if (relativeFilePath.equals(sourceFile)) { entriesToDelete.add(className); } } } finally { zis.close(); } for (String entryToDelete : entriesToDelete) { zipFile.removeFile(entryToDelete); File classFile = new File(ceylonOutputDirectory, entryToDelete.replace('/', File.separatorChar)); classFile.delete(); } } catch (ZipException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } final com.sun.tools.javac.util.Context dummyContext = new com.sun.tools.javac.util.Context(); class MyLog extends Log { public MyLog() { super(dummyContext, new PrintWriter(getConsoleStream())); } } Log log = new MyLog(); Options options = Options.instance(dummyContext); for (File moduleJar : moduleJars) { ShaSigner.sign(moduleJar, log, options); } } private static IPath getProjectRelativeOutputDir(IJavaProject javaProject) { if (!javaProject.exists()) return null; try { return javaProject.getOutputLocation() .makeRelativeTo(javaProject.getProject().getFullPath()); } catch (JavaModelException e) { return null; } } public static File getJavaOutputDirectory(IJavaProject javaProject) { return toFile(javaProject.getProject(), getProjectRelativeOutputDir(javaProject)); } public static File getCeylonOutputDirectory(IJavaProject javaProject) { File ceylonOutputDir = javaProject.getProject().getFolder("JDTClasses").getRawLocation().toFile(); if (! ceylonOutputDir.exists()) { ceylonOutputDir.mkdirs(); } return ceylonOutputDir; } public static File getModulesOutputDirectory(IJavaProject javaProject) { File modulesOutputDir = javaProject.getProject().getFolder("modules").getRawLocation().toFile(); if (! modulesOutputDir.exists()) { modulesOutputDir.mkdirs(); } return modulesOutputDir; } /** * String representation for debugging purposes */ public String toString() { return this.getProject() == null ? "CeylonBuilder for unknown project" //$NON-NLS-1$ : "CeylonBuilder for " + getProject().getName(); //$NON-NLS-1$ } }
package mil.nga.geopackage; import mil.nga.geopackage.tiles.TileBoundingBoxUtils; import mil.nga.sf.GeometryEnvelope; import mil.nga.sf.proj.ProjectionConstants; import mil.nga.sf.proj.ProjectionTransform; import org.osgeo.proj4j.units.Units; /** * Bounding Box with longitude and latitude ranges in degrees * * @author osbornb */ public class BoundingBox { /** * Min longitude in degrees */ private double minLongitude; /** * Max longitude in degrees */ private double maxLongitude; /** * Min latitude in degrees */ private double minLatitude; /** * Max latitude in degrees */ private double maxLatitude; /** * Constructor */ public BoundingBox() { this(-ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH, -ProjectionConstants.WGS84_HALF_WORLD_LAT_HEIGHT, ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH, ProjectionConstants.WGS84_HALF_WORLD_LAT_HEIGHT); } /** * Constructor * * @param minLongitude * min longitude * @param minLatitude * min latitude * @param maxLongitude * max longitude * @param maxLatitude * max latitude * @since 2.0.0 */ public BoundingBox(double minLongitude, double minLatitude, double maxLongitude, double maxLatitude) { this.minLongitude = minLongitude; this.minLatitude = minLatitude; this.maxLongitude = maxLongitude; this.maxLatitude = maxLatitude; } /** * Constructor * * @param boundingBox * bounding box * @since 1.1.6 */ public BoundingBox(BoundingBox boundingBox) { this(boundingBox.getMinLongitude(), boundingBox.getMinLatitude(), boundingBox.getMaxLongitude(), boundingBox.getMaxLatitude()); } /** * Constructor * * @param envelope * geometry envelope * @since 2.0.0 */ public BoundingBox(GeometryEnvelope envelope) { this(envelope.getMinX(), envelope.getMinY(), envelope.getMaxX(), envelope.getMaxY()); } /** * Get the min longitude * * @return min longitude */ public double getMinLongitude() { return minLongitude; } /** * Set the min longitude * * @param minLongitude * min longitude */ public void setMinLongitude(double minLongitude) { this.minLongitude = minLongitude; } /** * Get the max longitude * * @return max longitude */ public double getMaxLongitude() { return maxLongitude; } /** * Set the max longitude * * @param maxLongitude * max longitude */ public void setMaxLongitude(double maxLongitude) { this.maxLongitude = maxLongitude; } /** * Get the min latitude * * @return min latitude */ public double getMinLatitude() { return minLatitude; } /** * Set the min latitude * * @param minLatitude * min latitude */ public void setMinLatitude(double minLatitude) { this.minLatitude = minLatitude; } /** * Get the max latitude * * @return max latitude */ public double getMaxLatitude() { return maxLatitude; } /** * Set the max latitude * * @param maxLatitude * max latitude */ public void setMaxLatitude(double maxLatitude) { this.maxLatitude = maxLatitude; } /** * Build a Geometry Envelope from the bounding box * * @return geometry envelope * @since 1.1.0 */ public GeometryEnvelope buildEnvelope() { return buildEnvelope(this); } /** * Build a Geometry Envelope from the bounding box * * @param boundingBox * bounding box * @return geometry envelope * @since 3.1.1 */ public static GeometryEnvelope buildEnvelope(BoundingBox boundingBox) { GeometryEnvelope envelope = new GeometryEnvelope(); envelope.setMinX(boundingBox.getMinLongitude()); envelope.setMaxX(boundingBox.getMaxLongitude()); envelope.setMinY(boundingBox.getMinLatitude()); envelope.setMaxY(boundingBox.getMaxLatitude()); return envelope; } /** * If the bounding box spans the Anti-Meridian, attempt to get a * complementary bounding box using the max longitude of the unit projection * * @param maxProjectionLongitude * max longitude of the world for the current bounding box units * * @return complementary bounding box or nil if none * @since 2.0.0 */ public BoundingBox complementary(double maxProjectionLongitude) { BoundingBox complementary = null; Double adjust = null; if (this.maxLongitude > maxProjectionLongitude) { if (this.minLongitude >= -maxProjectionLongitude) { adjust = -2 * maxProjectionLongitude; } } else if (this.minLongitude < -maxProjectionLongitude) { if (this.maxLongitude <= maxProjectionLongitude) { adjust = 2 * maxProjectionLongitude; } } if (adjust != null) { complementary = new BoundingBox(this); complementary.setMinLongitude(complementary.getMinLongitude() + adjust); complementary.setMaxLongitude(complementary.getMaxLongitude() + adjust); } return complementary; } /** * If the bounding box spans the Anti-Meridian, attempt to get a * complementary WGS84 bounding box * * @return complementary bounding box or nil if none * @since 2.0.0 */ public BoundingBox complementaryWgs84() { return complementary(ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH); } /** * If the bounding box spans the Anti-Meridian, attempt to get a * complementary Web Mercator bounding box * * @return complementary bounding box or nil if none * @since 2.0.0 */ public BoundingBox complementaryWebMercator() { return complementary(ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH); } /** * Bound the bounding box longitudes within the min and max possible * projection values. This may result in a max longitude numerically lower * than the min longitude. * * @param maxProjectionLongitude * max longitude of the world for the current bounding box units * @return bounded bounding box * @since 2.0.0 */ public BoundingBox boundCoordinates(double maxProjectionLongitude) { BoundingBox bounded = new BoundingBox(this); double minLongitude = (getMinLongitude() + maxProjectionLongitude) % (2 * maxProjectionLongitude) - maxProjectionLongitude; double maxLongitude = (getMaxLongitude() + maxProjectionLongitude) % (2 * maxProjectionLongitude) - maxProjectionLongitude; bounded.setMinLongitude(minLongitude); bounded.setMaxLongitude(maxLongitude); return bounded; } /** * Bound the bounding box coordinates within WGS84 range values * * @return bounded bounding box * @since 2.0.0 */ public BoundingBox boundWgs84Coordinates() { return boundCoordinates(ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH); } /** * Bound the bounding box coordinates within Web Mercator range values * * @return bounded bounding box * @since 2.0.0 */ public BoundingBox boundWebMercatorCoordinates() { return boundCoordinates(ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH); } /** * Expand the bounding box max longitude above the max possible projection * value if needed to create a bounding box where the max longitude is * numerically larger than the min longitude. * * @param maxProjectionLongitude * max longitude of the world for the current bounding box units * @return expanded bounding box * @since 2.0.0 */ public BoundingBox expandCoordinates(double maxProjectionLongitude) { BoundingBox expanded = new BoundingBox(this); double minLongitude = getMinLongitude(); double maxLongitude = getMaxLongitude(); if (minLongitude > maxLongitude) { int worldWraps = 1 + (int) ((minLongitude - maxLongitude) / (2 * maxProjectionLongitude)); maxLongitude += (worldWraps * 2 * maxProjectionLongitude); expanded.setMaxLongitude(maxLongitude); } return expanded; } /** * Expand the bounding box max longitude above the max WGS84 projection * value if needed to create a bounding box where the max longitude is * numerically larger than the min longitude. * * @return expanded bounding box * @since 2.0.0 */ public BoundingBox expandWgs84Coordinates() { return expandCoordinates(ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH); } /** * Expand the bounding box max longitude above the max Web Mercator * projection value if needed to create a bounding box where the max * longitude is numerically larger than the min longitude. * * @return expanded bounding box * @since 2.0.0 */ public BoundingBox expandWebMercatorCoordinates() { return expandCoordinates(ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH); } /** * Transform the bounding box using the provided projection transform * * @param transform * projection transform * @return transformed bounding box * @since 3.0.0 */ public BoundingBox transform(ProjectionTransform transform) { BoundingBox transformed = this; if (transform.isSameProjection()) { transformed = new BoundingBox(transformed); } else { if (transform.getFromProjection().getUnit() == Units.DEGREES) { transformed = TileBoundingBoxUtils .boundDegreesBoundingBoxWithWebMercatorLimits(transformed); } GeometryEnvelope envelope = buildEnvelope(transformed); GeometryEnvelope transformedEnvelope = transform .transform(envelope); transformed = new BoundingBox(transformedEnvelope); } return transformed; } /** * Determine if intersects with the provided bounding box * * @param boundingBox * bounding box * @return true if intersects * @since 3.1.0 */ public boolean intersects(BoundingBox boundingBox) { return overlap(boundingBox) != null; } /** * Determine if intersects with the provided bounding box * * @param boundingBox * bounding box * @param allowEmpty * allow empty ranges when determining intersection * * @return true if intersects * @since 3.1.0 */ public boolean intersects(BoundingBox boundingBox, boolean allowEmpty) { return overlap(boundingBox, allowEmpty) != null; } /** * Get the overlapping bounding box with the provided bounding box * * @param boundingBox * bounding box * @return bounding box * @since 3.1.0 */ public BoundingBox overlap(BoundingBox boundingBox) { return overlap(boundingBox, false); } /** * Get the overlapping bounding box with the provided bounding box * * @param boundingBox * bounding box * @param allowEmpty * allow empty ranges when determining overlap * * @return bounding box * @since 3.1.0 */ public BoundingBox overlap(BoundingBox boundingBox, boolean allowEmpty) { double minLongitude = Math.max(getMinLongitude(), boundingBox.getMinLongitude()); double maxLongitude = Math.min(getMaxLongitude(), boundingBox.getMaxLongitude()); double minLatitude = Math.max(getMinLatitude(), boundingBox.getMinLatitude()); double maxLatitude = Math.min(getMaxLatitude(), boundingBox.getMaxLatitude()); BoundingBox overlap = null; if ((minLongitude < maxLongitude && minLatitude < maxLatitude) || (allowEmpty && minLongitude <= maxLongitude && minLatitude <= maxLatitude)) { overlap = new BoundingBox(minLongitude, minLatitude, maxLongitude, maxLatitude); } return overlap; } /** * Get the union bounding box with the provided bounding box * * @param boundingBox * bounding box * @return bounding box * @since 3.1.0 */ public BoundingBox union(BoundingBox boundingBox) { double minLongitude = Math.min(getMinLongitude(), boundingBox.getMinLongitude()); double maxLongitude = Math.max(getMaxLongitude(), boundingBox.getMaxLongitude()); double minLatitude = Math.min(getMinLatitude(), boundingBox.getMinLatitude()); double maxLatitude = Math.max(getMaxLatitude(), boundingBox.getMaxLatitude()); BoundingBox union = null; if (minLongitude < maxLongitude && minLatitude < maxLatitude) { union = new BoundingBox(minLongitude, minLatitude, maxLongitude, maxLatitude); } return union; } /** * Determine if inclusively contains the provided bounding box * * @param boundingBox * bounding box * @return true if contains * @since 3.1.0 */ public boolean contains(BoundingBox boundingBox) { return getMinLongitude() <= boundingBox.getMinLongitude() && getMaxLongitude() >= boundingBox.getMaxLongitude() && getMinLatitude() <= boundingBox.getMinLatitude() && getMaxLatitude() >= boundingBox.getMaxLatitude(); } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(maxLatitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(maxLongitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(minLatitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(minLongitude); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BoundingBox other = (BoundingBox) obj; if (Double.doubleToLongBits(maxLatitude) != Double .doubleToLongBits(other.maxLatitude)) return false; if (Double.doubleToLongBits(maxLongitude) != Double .doubleToLongBits(other.maxLongitude)) return false; if (Double.doubleToLongBits(minLatitude) != Double .doubleToLongBits(other.minLatitude)) return false; if (Double.doubleToLongBits(minLongitude) != Double .doubleToLongBits(other.minLongitude)) return false; return true; } }
package net.mybluemix.rest; import javax.servlet.annotation.WebServlet; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; @Path("employee") public class RestExample { @GET public String employeeList(){ return "{'All you need is love'}"; } //@Path("{name}") /* public String sayHello(@PathParam("name") String name){ StringBuilder stringBuilder = new StringBuilder("SandBox | Hello "); stringBuilder.append(name).append("!"); return stringBuilder.toString(); } */ }
package org.jkiss.dbeaver.ext.mysql.edit; import org.eclipse.jface.dialogs.IDialogConstants; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.ext.mysql.model.MySQLTable; import org.jkiss.dbeaver.ext.mysql.model.MySQLTrigger; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.impl.DBSObjectCache; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTriggerManager; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.ui.UITask; import org.jkiss.dbeaver.ui.dialogs.struct.CreateEntityDialog; import java.util.List; /** * MySQLTriggerManager */ public class MySQLTriggerManager extends SQLTriggerManager<MySQLTrigger, MySQLTable> { @Nullable @Override public DBSObjectCache<? extends DBSObject, MySQLTrigger> getObjectsCache(MySQLTrigger object) { return object.getCatalog().getTriggerCache(); } @Override protected MySQLTrigger createDatabaseObject(DBRProgressMonitor monitor, DBECommandContext context, final MySQLTable parent, Object copyFrom) { return new UITask<MySQLTrigger>() { @Override protected MySQLTrigger runTask() { CreateEntityDialog dialog = new CreateEntityDialog(DBeaverUI.getActiveWorkbenchShell(), parent.getDataSource(), "Create trigger"); if (dialog.open() != IDialogConstants.OK_ID) { return null; } MySQLTrigger newTrigger = new MySQLTrigger(parent.getContainer(), parent, dialog.getEntityName()); newTrigger.setObjectDefinitionText(""); //$NON-NLS-1$ return newTrigger; } }.execute(); } protected void createOrReplaceTriggerQuery(List<DBEPersistAction> actions, MySQLTrigger trigger) { String ddl = "CREATE TRIGGER " + trigger.getFullyQualifiedName(DBPEvaluationContext.DDL) + "\n" + trigger.getActionTiming() + " " + trigger.getManipulationType() + "\n" + "ON " + trigger.getTable().getFullyQualifiedName(DBPEvaluationContext.DDL) + " FOR EACH ROW\n" + trigger.getBody(); actions.add(new SQLDatabasePersistAction("Create trigger", ddl)); //$NON-NLS-2$ } }
package org.jkiss.dbeaver.ext.oracle.data; import org.jkiss.dbeaver.model.data.DBDContent; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.impl.jdbc.data.JDBCContentValueHandler; import org.jkiss.dbeaver.model.struct.DBSTypedObject; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLXML; /** * XML type support */ public class OracleXMLValueHandler extends JDBCContentValueHandler { public static final OracleXMLValueHandler INSTANCE = new OracleXMLValueHandler(); @Override protected DBDContent fetchColumnValue(DBCExecutionContext context, JDBCResultSet resultSet, DBSTypedObject type, int index) throws DBCException, SQLException { Object object; try { object = resultSet.getObject(index); } catch (SQLException e) { try { object = resultSet.getSQLXML(index); } catch (SQLException e1) { /* try { ResultSet originalRS = resultSet.getOriginal(); Class<?> rsClass = originalRS.getClass().getClassLoader().loadClass("oracle.jdbc.OracleResultSet"); Method method = rsClass.getMethod("getOPAQUE", Integer.TYPE); object = method.invoke(originalRS, index); if (object != null) { Class<?> xmlType = object.getClass().getClassLoader().loadClass("oracle.xdb.XMLType"); Method xmlConstructor = xmlType.getMethod("createXML", object.getClass()); object = xmlConstructor.invoke(null, object); } } catch (Throwable e2) { object = null; } */ object = null; } } if (object == null) { return new OracleContentXML(context.getDataSource(), null); } else if (object.getClass().getName().equals("oracle.xdb.XMLType")) { return new OracleContentXML(context.getDataSource(), new OracleXMLWrapper(object)); } else if (object instanceof SQLXML) { return new OracleContentXML(context.getDataSource(), (SQLXML) object); } else { throw new DBCException("Unsupported object type: " + object.getClass().getName()); } } @Override public DBDContent getValueFromObject(DBCExecutionContext context, DBSTypedObject type, Object object, boolean copy) throws DBCException { if (object == null) { return new OracleContentXML(context.getDataSource(), null); } return super.getValueFromObject(context, type, object, copy); } }
package jade.tools.introspector; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import jade.util.leap.List; import jade.util.leap.ArrayList; import java.util.Map; import java.util.TreeMap; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import jade.core.*; import jade.core.behaviours.*; import jade.tools.introspector.gui.IntrospectorGUI; import jade.domain.FIPANames; import jade.domain.FIPAServiceCommunicator; import jade.domain.introspection.*; // FIXME: These three imports will not be needed anymore, when // suitable actions will be put into the 'jade-introspection' // ontology. import jade.domain.JADEAgentManagement.JADEManagementOntology; import jade.domain.JADEAgentManagement.DebugOn; import jade.domain.JADEAgentManagement.DebugOff; import jade.gui.AgentTreeModel; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.content.lang.sl.SLCodec; import jade.content.onto.basic.Action; import jade.content.onto.basic.Done; import jade.proto.SimpleAchieveREInitiator; import jade.proto.AchieveREInitiator; import jade.tools.ToolAgent; import jade.tools.introspector.gui.IntrospectorGUI; import jade.tools.introspector.gui.MainWindow; /* This class represents the Introspector Agent. This agent registers with the AMS as a tool, to manage an AgentTree component, then activates its GUI. The agent listens for ACL messages containing introspection events and updates the display through the IntrospectorGUI class. @author Andrea Squeri, - Universita` di Parma @author Giovanni Caire, - TILAB */ public class Introspector extends ToolAgent { private class AMSRequester extends SimpleAchieveREInitiator { private String actionName; public AMSRequester(String an, ACLMessage request) { super(Introspector.this, request); actionName = an; } protected void handleNotUnderstood(ACLMessage reply) { myGUI.showError("NOT-UNDERSTOOD received during " + actionName); } protected void handleRefuse(ACLMessage reply) { myGUI.showError("REFUSE received during " + actionName); } protected void handleAgree(ACLMessage reply) { // System.out.println("AGREE received"); } protected void handleFailure(ACLMessage reply) { myGUI.showError("FAILURE received during " + actionName); } protected void handleInform(ACLMessage reply) { // System.out.println("INFORM received"); } } // End of AMSRequester class // GUI events public static final int STEP_EVENT = 1; public static final int BREAK_EVENT = 2; public static final int SLOW_EVENT = 3; public static final int GO_EVENT = 4; public static final int KILL_EVENT = 5; public static final int SUSPEND_EVENT = 6; private IntrospectorGUI myGUI; private Sensor guiSensor = new Sensor(); private String myContainerName; private Map windowMap = Collections.synchronizedMap(new TreeMap()); // The set of agents that are observed in step-by-step mode private Set stepByStepAgents = new HashSet(); // The set of agents that are observed in slow mode private Set slowAgents = new HashSet(); // Maps an observed agent with the String used as reply-with in the // message that notified about an event that had to be observed synchronously private Map pendingReplies = new HashMap(); // Maps an observed agent with the ToolNotifier that notifies events // about that agent to this Introspector private Map notifiers = new HashMap(); private SequentialBehaviour AMSSubscribe = new SequentialBehaviour(); class IntrospectorAMSListenerBehaviour extends AMSListenerBehaviour { protected void installHandlers(Map handlersTable) { handlersTable.put(IntrospectionVocabulary.ADDEDCONTAINER, new EventHandler() { public void handle(Event ev) { AddedContainer ac = (AddedContainer)ev; ContainerID cid = ac.getContainer(); String name = cid.getName(); String address = cid.getAddress(); try { InetAddress addr = InetAddress.getByName(address); myGUI.addContainer(name, addr); } catch(UnknownHostException uhe) { myGUI.addContainer(name, null); } } }); handlersTable.put(IntrospectionVocabulary.REMOVEDCONTAINER, new EventHandler() { public void handle(Event ev) { RemovedContainer rc = (RemovedContainer)ev; ContainerID cid = rc.getContainer(); String name = cid.getName(); myGUI.removeContainer(name); } }); handlersTable.put(IntrospectionVocabulary.BORNAGENT, new EventHandler() { public void handle(Event ev) { BornAgent ba = (BornAgent)ev; ContainerID cid = ba.getWhere(); String container = cid.getName(); AID agent = ba.getAgent(); myGUI.addAgent(container, agent); if(agent.equals(getAID())) myContainerName = container; } }); handlersTable.put(IntrospectionVocabulary.DEADAGENT, new EventHandler() { public void handle(Event ev) { DeadAgent da = (DeadAgent)ev; ContainerID cid = da.getWhere(); String container = cid.getName(); AID agent = da.getAgent(); MainWindow m = (MainWindow)windowMap.get(agent); if(m != null) { myGUI.closeInternal(m); windowMap.remove(agent); } myGUI.removeAgent(container, agent); } }); handlersTable.put(IntrospectionVocabulary.MOVEDAGENT, new EventHandler() { public void handle(Event ev) { MovedAgent ma = (MovedAgent)ev; AID agent = ma.getAgent(); ContainerID from = ma.getFrom(); myGUI.removeAgent(from.getName(), agent); ContainerID to = ma.getTo(); myGUI.addAgent(to.getName(), agent); if (windowMap.containsKey(agent)) { MainWindow m = (MainWindow)windowMap.get(agent); // FIXME: We should clean behaviours and pending messages here requestDebugOn(agent); } } }); } // End of installHandlers() method } public void toolSetup() { getContentManager().registerOntology(JADEManagementOntology.getInstance()); getContentManager().registerOntology(IntrospectionOntology.getInstance()); getContentManager().registerLanguage(new SLCodec(), FIPANames.ContentLanguage.FIPA_SL0); ACLMessage msg = getRequest(); msg.setOntology(JADEManagementOntology.NAME); // Send 'subscribe' message to the AMS AMSSubscribe.addSubBehaviour(new SenderBehaviour(this, getSubscribe())); // Handle incoming 'inform' messages about Platform events from the AMS AMSSubscribe.addSubBehaviour(new IntrospectorAMSListenerBehaviour()); addBehaviour(AMSSubscribe); // Handle incoming INFORM messages about Agent and Message events from the // ToolNotifiers addBehaviour(new IntrospectionListenerBehaviour()); // Handle incoming INFORM messages about observation start/stop from // ToolNotifiers addBehaviour(new ControlListenerBehaviour(this)); // Manages GUI events addBehaviour(new SensorManager(this, guiSensor) { public void onEvent(jade.util.Event ev) { AID id = ((MainWindow) ev.getSource()).getDebugged(); switch (ev.getType()) { case STEP_EVENT: proceed(id); break; case BREAK_EVENT: stepByStepAgents.add(id); slowAgents.remove(id); break; case SLOW_EVENT: stepByStepAgents.remove(id); slowAgents.add(id); proceed(id); break; case GO_EVENT: stepByStepAgents.remove(id); slowAgents.remove(id); proceed(id); } } } ); // Show Graphical User Interface myGUI = new IntrospectorGUI(this); myGUI.setVisible(true); } /* Adds an agent to the debugged agents map, and asks the AMS to start debugging mode on that agent. */ public void addAgent(AID name) { if(!windowMap.containsKey(name)) { MainWindow m = new MainWindow(guiSensor, name); myGUI.addWindow(m); windowMap.put(name, m); stepByStepAgents.add(name); requestDebugOn(name); } /* try { ACLMessage msg = getRequest(); DebugOn dbgOn = new DebugOn(); dbgOn.setDebugger(getAID()); dbgOn.addDebuggedAgents(name); Action a = new Action(); a.setActor(getAMS()); a.setAction(dbgOn); getContentManager().fillContent(msg, a); addBehaviour(new AMSRequester("DebugOn", msg)); } catch(Exception fe) { fe.printStackTrace(); } }*/ } private void requestDebugOn(AID name) { try { ACLMessage msg = getRequest(); DebugOn dbgOn = new DebugOn(); dbgOn.setDebugger(getAID()); dbgOn.addDebuggedAgents(name); Action a = new Action(); a.setActor(getAMS()); a.setAction(dbgOn); getContentManager().fillContent(msg, a); addBehaviour(new AMSRequester("DebugOn", msg)); } catch(Exception fe) { fe.printStackTrace(); } } /* Removes an agent from the debugged agents map, and closes its window. Moreover,it and asks the AMS to stop debugging mode on that agent. */ public void removeAgent(final AID name) { if(windowMap.containsKey(name)) { try { final MainWindow m = (MainWindow)windowMap.get(name); myGUI.closeInternal(m); windowMap.remove(name); stepByStepAgents.remove(name); slowAgents.remove(name); proceed(name); ACLMessage msg = getRequest(); DebugOff dbgOff = new DebugOff(); dbgOff.setDebugger(getAID()); dbgOff.addDebuggedAgents(name); Action a = new Action(); a.setActor(getAMS()); a.setAction(dbgOff); getContentManager().fillContent(msg, a); addBehaviour(new AMSRequester("DebugOff", msg)); } catch(Exception fe) { fe.printStackTrace(); } } } /** Cleanup during agent shutdown. This method cleans things up when <em>RMA</em> agent is destroyed, disconnecting from <em>AMS</em> agent and closing down the platform administration <em>GUI</em>. */ public void toolTakeDown() { // Stop debugging all the agents if(!windowMap.isEmpty()) { ACLMessage msg = getRequest(); DebugOff dbgOff = new DebugOff(); dbgOff.setDebugger(getAID()); Iterator it = windowMap.keySet().iterator(); while(it.hasNext()) { AID id = (AID)it.next(); dbgOff.addDebuggedAgents(id); } Action a = new Action(); a.setActor(getAMS()); a.setAction(dbgOff); try { getContentManager().fillContent(msg, a); FIPAServiceCommunicator.doFipaRequestClient(this, msg); } catch(Exception fe) { // When the AMS replies the tool notifier is no longer registered. // But we don't care as we are exiting //System.out.println(e.getMessage()); } } send(getCancel()); // myGUI.setVisible(false); Not needed and can cause thread deadlock on join. myGUI.disposeAsync(); } /** Callback method for platform management <em>GUI</em>. */ public AgentTreeModel getModel() { return myGUI.getModel(); } /* Listens to introspective messages and dispatches them. */ private class IntrospectionListenerBehaviour extends CyclicBehaviour { private MessageTemplate template; private Map handlers = new TreeMap(String.CASE_INSENSITIVE_ORDER); IntrospectionListenerBehaviour() { template = MessageTemplate.and(MessageTemplate.MatchOntology(IntrospectionOntology.NAME), MessageTemplate.MatchConversationId(getName() + "-event")); // Fill handlers table ... handlers.put(IntrospectionVocabulary.CHANGEDAGENTSTATE, new EventHandler() { public void handle(Event ev) { } }); handlers.put(IntrospectionVocabulary.ADDEDBEHAVIOUR, new EventHandler() { public void handle(Event ev) { AddedBehaviour ab = (AddedBehaviour)ev; AID agent = ab.getAgent(); MainWindow wnd = (MainWindow)windowMap.get(agent); if(wnd != null) myGUI.behaviourAdded(wnd, ab); } }); handlers.put(IntrospectionVocabulary.REMOVEDBEHAVIOUR, new EventHandler() { public void handle(Event ev) { RemovedBehaviour rb = (RemovedBehaviour)ev; AID agent = rb.getAgent(); MainWindow wnd = (MainWindow)windowMap.get(agent); if(wnd != null) myGUI.behaviourRemoved(wnd, rb); } }); handlers.put(IntrospectionVocabulary.CHANGEDBEHAVIOURSTATE, new EventHandler() { public void handle(Event ev) { ChangedBehaviourState cs = (ChangedBehaviourState)ev; AID agent = cs.getAgent(); MainWindow wnd = (MainWindow)windowMap.get(agent); if(wnd != null) { myGUI.behaviourChangeState(wnd, cs); } if (stepByStepAgents.contains(agent)) { return; } if (slowAgents.contains(agent)) { try { Thread.sleep(500); } catch (InterruptedException ie) { // The introspector is probably being killed } } proceed(agent); } }); handlers.put(IntrospectionVocabulary.SENTMESSAGE, new EventHandler() { public void handle(Event ev) { SentMessage sm = (SentMessage)ev; AID sender = sm.getSender(); MainWindow wnd = (MainWindow)windowMap.get(sender); if(wnd != null) myGUI.messageSent(wnd, sm); } }); handlers.put(IntrospectionVocabulary.RECEIVEDMESSAGE, new EventHandler() { public void handle(Event ev) { ReceivedMessage rm = (ReceivedMessage)ev; AID receiver = rm.getReceiver(); MainWindow wnd = (MainWindow)windowMap.get(receiver); if(wnd != null) myGUI.messageReceived(wnd, rm); } }); handlers.put(IntrospectionVocabulary.POSTEDMESSAGE, new EventHandler() { public void handle(Event ev) { PostedMessage pm = (PostedMessage)ev; AID receiver = pm.getReceiver(); MainWindow wnd = (MainWindow)windowMap.get(receiver); if(wnd != null) myGUI.messagePosted(wnd, pm); } }); handlers.put(IntrospectionVocabulary.CHANGEDAGENTSTATE, new EventHandler() { public void handle(Event ev) { ChangedAgentState cas = (ChangedAgentState)ev; AID agent = cas.getAgent(); MainWindow wnd = (MainWindow)windowMap.get(agent); if(wnd != null) myGUI.changedAgentState(wnd, cas); } }); } public void action() { ACLMessage message = receive(template); if(message != null) { AID name = message.getSender(); try{ Occurred o = (Occurred)getContentManager().extractContent(message); EventRecord er = o.get_0(); Event ev = er.getWhat(); // DEBUG //System.out.println("Received event "+ev); if (message.getReplyWith() != null) { // A reply is expected --> put relevant information into the // pendingReplies Map ChangedBehaviourState cs = (ChangedBehaviourState)ev; pendingReplies.put(cs.getAgent(), message.getReplyWith()); } String eventName = ev.getName(); EventHandler h = (EventHandler)handlers.get(eventName); if(h != null) h.handle(ev); } catch(Exception fe) { fe.printStackTrace(); } } else block(); } } // End of inner class IntrospectionListenerBehaviour /** Inner class ControlListenerBehaviour. This is a behaviour that listen for messages from ToolNotifiers informing that they have started notifying events about a given agent. These information are used to keep the map between observed agents and ToolNotifiers up to date. */ private class ControlListenerBehaviour extends CyclicBehaviour { private MessageTemplate template; ControlListenerBehaviour(Agent a) { super(a); template = MessageTemplate.and( MessageTemplate.MatchOntology(JADEIntrospectionOntology.NAME), MessageTemplate.MatchConversationId(getName() + "-control")); } public void action() { ACLMessage message = receive(template); if(message != null) { try{ Done d = (Done)getContentManager().extractContent(message); Action a = (Action)d.getAction(); AID tn = a.getActor(); StartNotify sn = (StartNotify) a.getAction(); AID observed = sn.getObserved(); System.out.println("Map "+observed+" to "+tn); notifiers.put(observed, tn); } catch(Exception fe) { fe.printStackTrace(); } } else { block(); } } } // End of inner class ControlListenerBehaviour private void proceed(AID id) { String pendingReplyWith = (String) pendingReplies.remove(id); AID tn = (AID) notifiers.get(id); if (pendingReplyWith != null && tn != null) { ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.addReceiver(tn); msg.setInReplyTo(pendingReplyWith); send(msg); } } }
package org.lockss.plugin.usdocspln.gov.gpo.fdsys; import java.util.*; import java.util.regex.*; import org.lockss.util.*; import org.lockss.plugin.*; import org.lockss.extractor.*; import org.lockss.daemon.PluginException; public class GPOFDSysSitemapsArticleIteratorFactory implements ArticleIteratorFactory, ArticleMetadataExtractorFactory { protected static Logger log = Logger.getLogger(GPOFDSysSitemapsArticleIteratorFactory.class); protected static final String ROOT_TEMPLATE = "\"%sfdsys/pkg/\", base_url"; protected static final String PATTERN_TEMPLATE = "\"^%sfdsys/pkg/([^/]+)/(html?|mp3|pdf|xml)/([^/]+)\\.(html?|mp3|pdf|xml)$\", base_url"; protected static final Pattern HTML_PATTERN = Pattern.compile("([^/]+)/html/([^/]+)\\.htm$", Pattern.CASE_INSENSITIVE); protected static final Pattern MP3_PATTERN = Pattern.compile("([^/]+)/mp3/([^/]+)\\.mp3$", Pattern.CASE_INSENSITIVE); protected static final Pattern PDF_PATTERN = Pattern.compile("([^/]+)/pdf/([^/]+)\\.pdf$", Pattern.CASE_INSENSITIVE); protected static final Pattern XML_PATTERN = Pattern.compile("([^/]+)/xml/([^/]+)\\.xml$", Pattern.CASE_INSENSITIVE); protected static final String HTML_REPLACEMENT1 = "$1/html/$2.htm"; protected static final String HTML_REPLACEMENT2 = "$1/html/$2.html"; protected static final String MP3_REPLACEMENT = "$1/mp3/$2.mp3"; protected static final String PDF_REPLACEMENT = "$1/pdf/$2.pdf"; protected static final String XML_REPLACEMENT = "$1/xml/$2.xml"; protected static final String ROLE_AUDIO_FILE = "AudioFile"; public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au, MetadataTarget target) throws PluginException { SubTreeArticleIteratorBuilder builder = new SubTreeArticleIteratorBuilder(au); builder.setSpec(target, ROOT_TEMPLATE, PATTERN_TEMPLATE, Pattern.CASE_INSENSITIVE); // set up html, pdf, xml to be an aspects that will trigger an ArticleFiles builder.addAspect( HTML_PATTERN, Arrays.asList(HTML_REPLACEMENT1, HTML_REPLACEMENT2), ArticleFiles.ROLE_FULL_TEXT_HTML); builder.addAspect( PDF_PATTERN, PDF_REPLACEMENT, ArticleFiles.ROLE_FULL_TEXT_PDF); builder.addAspect( XML_PATTERN, XML_REPLACEMENT, ArticleFiles.ROLE_FULL_TEXT_XML); builder.addAspect( MP3_PATTERN, MP3_REPLACEMENT, ROLE_AUDIO_FILE); // add metadata role from html, xml, or pdf (NOTE: pdf metadata is the access url) builder.setRoleFromOtherRoles(ArticleFiles.ROLE_ARTICLE_METADATA, Arrays.asList( ArticleFiles.ROLE_FULL_TEXT_HTML, ArticleFiles.ROLE_FULL_TEXT_PDF, ArticleFiles.ROLE_FULL_TEXT_XML, ROLE_AUDIO_FILE)); return builder.getSubTreeArticleIterator(); } public ArticleMetadataExtractor createArticleMetadataExtractor(MetadataTarget target) throws PluginException { return new BaseArticleMetadataExtractor(ArticleFiles.ROLE_ARTICLE_METADATA); } }
package sample; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonReader; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.hamcrest.Matchers; import org.hamcrest.core.IsNot; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.loadui.testfx.GuiTest; import org.testfx.framework.junit.ApplicationTest; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.*; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; import static org.loadui.testfx.GuiTest.find; import static org.loadui.testfx.GuiTest.waitUntil; import static org.loadui.testfx.controls.impl.VisibleNodesMatcher.visible; import static org.testfx.api.FxAssert.verifyThat; import static org.testfx.matcher.base.NodeMatchers.isVisible; import static org.testfx.matcher.control.TextFlowMatchers.hasText; import static org.testfx.util.WaitForAsyncUtils.waitFor; import org.loadui.testfx.controls.impl.VisibleNodesMatcher; public class MainTest extends ApplicationTest { private Stage testStage; private Gson gson; private PodcastListEntry podcastEntry; @BeforeClass public static void setUpClass () throws Exception { ApplicationTest.launch(Main.class); } @Override public void start (Stage stage) { testStage = stage; testStage.show(); } @Before public void setUp () throws Exception { gson = new Gson(); JsonReader reader = new JsonReader(new FileReader("data/PodcastListLoader/iTunes.json")); podcastEntry = gson.fromJson(reader, PodcastListEntry.class); } @After public void tearDown () throws Exception { gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(podcastEntry); FileWriter writer = new FileWriter("data/PodcastListLoader/iTunes.json"); writer.write(json); writer.close(); } @Test public void testOn_UserClick_CanceliTunesPodcastPopup () throws Exception { List<String> podcastNameList = new ArrayList<>(); podcastNameList.add("History of Rome"); podcastNameList.add("Levar Burton Reads"); clickOn("#menuBarFile").clickOn("#menuBarFileNew"); clickOn(500, 300); write("https://feeds.soundcloud.com/users/soundcloud:users:63303345/sounds.rss"); clickOn(800, 375); ListView list = (ListView) GuiTest.find("#mainVBox #podcastList"); assertThat(list.getItems().toString(), equalTo(podcastNameList.toString())); } @Test public void testOn_UserClick_AddiTunesPodcastPopup () throws Exception { List<String> podcastNameList = new ArrayList<>(); podcastNameList.add("History of Rome"); podcastNameList.add("Levar Burton Reads"); podcastNameList.add("OWASP 24/7"); clickOn("#menuBarFile").clickOn("#menuBarFileNew"); clickOn(500, 300); write("https://feeds.soundcloud.com/users/soundcloud:users:63303345/sounds.rss"); clickOn(900, 375); ListView list = (ListView) GuiTest.find("#mainVBox #podcastList"); assertThat(list.getItems().toString(), equalTo(podcastNameList.toString())); } @Test public void testOn_UserClick_AddiTunesPodcastPopup_WithDuplicateEntry () throws Exception { List<String> podcastNameList = new ArrayList<>(); podcastNameList.add("History of Rome"); podcastNameList.add("Levar Burton Reads"); clickOn("#menuBarFile").clickOn("#menuBarFileNew"); clickOn(500, 300); write("http://historyofrome.libsyn.com/rss/"); clickOn(900, 375); ListView list = (ListView) GuiTest.find("#mainVBox #podcastList"); assertThat(list.getItems().toString(), equalTo(podcastNameList.toString())); } }
package cd4017be.indlog.tileentity; import static cd4017be.lib.property.PropertyByte.cast; import java.util.ArrayList; import java.util.List; import cd4017be.lib.block.AdvancedBlock.IInteractiveTile; import cd4017be.lib.block.AdvancedBlock.INeighborAwareTile; import cd4017be.lib.block.AdvancedBlock.ITilePlaceHarvest; import cd4017be.lib.block.MultipartBlock.IModularTile; import cd4017be.lib.templates.Cover; import cd4017be.lib.tileentity.BaseTileEntity; import cd4017be.lib.util.TileAccess; import cd4017be.lib.util.Utils; import cd4017be.indlog.util.PipeFilter; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; /** * * @author CD4017BE */ public abstract class Pipe<T extends Pipe<T, O, F, I>, O, F extends PipeFilter<O, I>, I> extends BaseTileEntity implements INeighborAwareTile, IInteractiveTile, IModularTile, ITickable, ITilePlaceHarvest { public static boolean SAVE_PERFORMANCE; public O content, last; protected T target; protected F filter; protected ArrayList<TileAccess> invs = null; protected byte type, dest; /** bits[0-13 (6+1)*2]: (side + total) * dir{0:none, 1:out, 2:in, 3:lock/both}, bit[14]: update, bit[15]: blocked */ protected short flow; private byte time; protected boolean updateCon = true; protected Cover cover = new Cover(); private boolean onChunkBorder; public Pipe() {} public Pipe(IBlockState state) { super(state); type = (byte)blockType.getMetaFromState(state); } @Override public void update() { if (world.isRemote) return; if (world.getTotalWorldTime() % resetTimer() == time) { if (updateCon) updateConnections(); switch(type) { case 1: if ((flow & 0x8000) != 0) break; if (content != null && (filter == null || filter.active(world.isBlockPowered(pos)))) { I acc; for (TileAccess inv : invs) if (inv.te.isInvalid() || (acc = inv.te.getCapability(capability(), inv.side)) == null) updateCon = true; else if (transferOut(acc)) break; } case 3: if ((flow & 0x3000) == 0x3000 && content != null && target != null && target.content == null && (filter == null || filter.transfer(content))) { if (target.tileEntityInvalid) target = null; else { target.content = content; content = null; markDirty(); if (onChunkBorder) target.markDirty(); } } break; case 2: if ((flow & 0x8000) == 0 && (filter == null || filter.active(world.isBlockPowered(pos)))) { I acc; for (TileAccess inv : invs) if (inv.te.isInvalid() || (acc = inv.te.getCapability(capability(), inv.side)) == null) updateCon = true; else if (transferIn(acc)) break; } default: if ((flow & 0x3000) == 0x3000 && content != null && target != null && target.content == null) { if (target.tileEntityInvalid) target = null; else { target.content = content; content = null; markDirty(); if (onChunkBorder) target.markDirty(); } } } } else if (SAVE_PERFORMANCE) return; if (content != last) { last = content; markUpdate(); } } private boolean unloadedNeighbor() { int i = pos.getX() & 15, j = pos.getZ() & 15; return (i == 0 && !world.isBlockLoaded(pos.west())) || (i == 15 && !world.isBlockLoaded(pos.east())) || (j == 0 && !world.isBlockLoaded(pos.north())) || (j == 15 && !world.isBlockLoaded(pos.south())); } protected void updateConnections() { updateCon = false; if (invs != null) invs.clear(); else if (type > 0 && type < 3) invs = new ArrayList<TileAccess>(5); if (target != null && target.invalid()) { target = null; dest = -1; } TileEntity te; if (onChunkBorder && unloadedNeighbor()) { //only refresh cached tiles for (EnumFacing s : EnumFacing.values()) { int io = getFlowBit(s.ordinal()); if (io == 0 || io == 3) continue; te = Utils.neighborTile(this, s); if (te == null) continue; if (pipeClass().isInstance(te)) { if (io == 1 && target == null) target = pipeClass().cast(te); } else if(te.hasCapability(capability(), s.getOpposite()) && io == type) invs.add(new TileAccess(te, s.getOpposite())); } return; } EnumFacing dir; ArrayList<T> updateList = new ArrayList<T>(); /** -1: fine, 0: best match, 1: any match, 2: no match */ int newDest = target == null || target.getFlowBit(dest^1) != 2 || (target.getFlowBit(6) & 1) == 0 ? 2 : -1; int lHasIO = getFlowBit(6), nHasIO = type > 2 ? type - 2 : 0, lDirIO, nDirIO; short lFlow = flow; for (int i = 0; i < 6; i++) { lDirIO = getFlowBit(i); if (lDirIO == 3) continue; dir = EnumFacing.VALUES[i]; te = world.getTileEntity(pos.offset(dir)); if (te == null) setFlowBit(i, 0); else if (pipeClass().isInstance(te)) { T pipe = pipeClass().cast(te); if (newDest < 0 && lDirIO == 1 && dest == i) { nHasIO |= 1; updateList.add(pipe); continue; } int pDirIO = pipe.getFlowBit(i ^ 1); if (pDirIO != 3) { int pHasIO = pipe.getFlowBit(6); nDirIO = (~lHasIO | lDirIO) & ~pDirIO & pHasIO; if (newDest <= 0 || !(newDest > 1 || pDirIO == 2 || (pHasIO & 2) == 0)) nDirIO &= 2; else nDirIO &= 3; if (nDirIO == 3) nDirIO = 0; if (nDirIO == 0) { if (pDirIO != 1 && pHasIO == 1 || pDirIO == 2 && pHasIO == 3 && newDest == 2 && type == 1) nDirIO = 1; else if (pDirIO != 2 && pHasIO == 2) nDirIO = 2; } if (nDirIO == 1) { target = pipe; if (dest >= 0 && getFlowBit(dest) == 1) setFlowBit(dest, 0); dest = (byte)i; newDest = pDirIO == 2 ? 0 : 1; } else if (dest == i) { target = null; dest = -1; updateCon = true; } setFlowBit(i, nDirIO); nHasIO |= nDirIO; updateList.add(pipe); } else if (type > 0 && type < 3) { setFlowBit(i, type); nHasIO |= type; invs.add(new TileAccess(te, dir.getOpposite())); } else setFlowBit(i, 3); } else if (type > 0 && type < 3 && te.hasCapability(capability(), dir.getOpposite())) { setFlowBit(i, type); nHasIO |= type; invs.add(new TileAccess(te, dir.getOpposite())); } else { byte d = conDir(te, dir.getOpposite()); if (d == 1 && newDest >= 0) { if (dest >= 0 && getFlowBit(dest) == 1) setFlowBit(dest, 0); dest = -1; target = null; newDest = -1; } else if (d == 3) d = 0; setFlowBit(i, d); nHasIO |= d; } } setFlowBit(6, nHasIO); flow &= 0xbfff; if (flow != lFlow) { this.markUpdate(); this.markDirty(); for (T pipe : updateList) pipe.updateCon = true; } } protected int getFlowBit(int b) { return flow >> (b * 2) & 3; } protected void setFlowBit(int b, int v) { b *= 2; flow = (short)(flow & ~(3 << b) | (v & 3) << b); } @Override public boolean onActivated(EntityPlayer player, EnumHand hand, ItemStack item, EnumFacing dir, float X, float Y, float Z) { if (world.isRemote) return true; if (cover.interact(this, player, hand, item, dir, X, Y, Z)) return true; if (item.getCount() > 0) return false; if (player.isSneaking()) { dir = Utils.hitSide(X, Y, Z); int s = dir.getIndex(); lockCon(s, getFlowBit(s) == 3); return true; } else if (filter == null) { flow ^= 0x8000; markUpdate(); markDirty(); return true; } else return false; } @Override public void onClicked(EntityPlayer player) { if (world.isRemote) return; if (cover.state == null) { RayTraceResult hit = Utils.getHit(player, getBlockState(), pos); if (hit != null) { int i = hit.subHit - 1; if (i >= 0 && getFlowBit(i) != 3) lockCon(i, false); } } else cover.hit(this, player); } protected void lockCon(int s, boolean unlock) { int lock = unlock ? 0 : 3; setFlowBit(s, lock); if (lock != 0) flow |= 0x4000; updateCon = true; this.markUpdate(); this.markDirty(); ICapabilityProvider te = getTileOnSide(EnumFacing.VALUES[s]); if (pipeClass().isInstance(te)) { T pipe = pipeClass().cast(te); if (unlock || pipe.type == 1 || pipe.type == 2) pipe.setFlowBit(s^1, 0); else { pipe.setFlowBit(s^1, 3); pipe.flow |= 0x4000; } pipe.updateCon = true; pipe.markUpdate(); if (onChunkBorder) pipe.markDirty(); } } @Override public void neighborBlockChange(Block b, BlockPos src) { updateCon = true; } @Override public void neighborTileChange(TileEntity te, EnumFacing side) { updateCon = true; } @Override public void setPos(BlockPos posIn) { super.setPos(posIn); if ((posIn.getX() + posIn.getY() + posIn.getZ() & 1) == 0) time = 0; else time = (byte) Math.min(127, resetTimer() / 2); onChunkBorder = (posIn.getX() + 1 & 15) <= 1 || (posIn.getZ() + 1 & 15) <= 1; } @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt.setByte("type", type); nbt.setShort("flow", flow); cover.writeNBT(nbt, "cover", false); return super.writeToNBT(nbt); } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); type = nbt.getByte("type"); flow = nbt.getShort("flow"); cover.readNBT(nbt, "cover", null); updateCon = true; } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { NBTTagCompound nbt = pkt.getNbtCompound(); IBlockState c = cover.state; cover.readNBT(nbt, "cv", this); short nf = nbt.getShort("flow"); if (onDataPacket(nbt) || nf != flow || cover.state != c) { flow = nf; this.markUpdate(); } } @Override public SPacketUpdateTileEntity getUpdatePacket() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setShort("flow", flow); cover.writeNBT(nbt, "cv", true); getUpdatePacket(nbt); return new SPacketUpdateTileEntity(getPos(), -1, nbt); } @SuppressWarnings("unchecked") @Override public <M> M getModuleState(int m) { if (m == 6) return cover.module(); int b = getFlowBit(m); if (b == 3) return cast(-1); EnumFacing f = EnumFacing.VALUES[m]; TileEntity p = Utils.neighborTile(this, f); boolean isPipe = pipeClass().isInstance(p) && ((T)p).getFlowBit(m^1) != 3; if (b == 0) { if (!isPipe) b = -1; } else if ((flow & 0x8000) != 0) { if (b == type && !(b == 2 && isPipe)) b += 4; } else if (filter != null && (b == type || b == type - 2) && !(isPipe && (b == 2 || !filter.blocking()))) b += 2; return cast(b); } @Override public boolean isModulePresent(int m) { if (m == 6) return cover.state != null; int b = getFlowBit(m); if (b == 3) return false; else if (b != 0) return true; EnumFacing f = EnumFacing.VALUES[m]; TileEntity p = Utils.neighborTile(this, f); return pipeClass().isInstance(p); } @Override public void onPlaced(EntityLivingBase entity, ItemStack item) { } @Override public List<ItemStack> dropItem(IBlockState state, int fortune) { List<ItemStack> list = makeDefaultDrops(null); if (cover.stack != null) list.add(cover.stack); return list; } @Override public boolean hasCapability(Capability<?> cap, EnumFacing facing) { return cap == capability(); } @SuppressWarnings("unchecked") @Override public <C> C getCapability(Capability<C> cap, EnumFacing facing) { return cap == capability() ? (C) getInv(type != 0 && facing != null && getFlowBit(facing.ordinal()) != 3) : null; } protected abstract boolean transferOut(I acc); protected abstract boolean transferIn(I acc); protected abstract boolean onDataPacket(NBTTagCompound nbt); protected abstract void getUpdatePacket(NBTTagCompound nbt); protected abstract byte conDir(TileEntity te, EnumFacing side); protected abstract int resetTimer(); protected abstract I getInv(boolean filtered); protected abstract Class<T> pipeClass(); protected abstract Capability<I> capability(); }
package okra.serialization; import okra.Preconditions; import okra.util.DateUtil; import org.bson.Document; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; class InputMapper { private final static Logger LOGGER = LoggerFactory.getLogger(InputMapper.class); public <T> Optional<T> fromDocument(final Class<T> clazz, final Document document) { Preconditions.checkNotNull(clazz, "clazz"); Preconditions.checkNotNull(document, "document"); try { final T model = clazz.newInstance(); final Field[] fields = clazz.getDeclaredFields(); parseIdField(model, document); for (final Field field : fields) { parseSingleField(model, field, document); } return Optional.of(model); } catch (final InstantiationException | IllegalAccessException e) { LOGGER.error("Error serializing object with type [{}} from document [{}}", clazz, document, e); } return Optional.empty(); } @SuppressWarnings("unchecked") private <T> void parseSingleField(final T model, final Field field, final Document document) throws IllegalAccessException { final FieldType type = FieldType.get(field.getType()); if (field.getName().equals("id")) return; field.setAccessible(true); switch (type) { case DOUBLE: field.set(model, document.getDouble(field.getName())); break; case INTEGER: field.set(model, document.getInteger(field.getName())); break; case STRING: final String value = document.getString(field.getName()); if (field.getType().isEnum()) { field.set(model, Enum.valueOf((Class<Enum>) field.getType(), value)); } else { field.set(model, value); } break; case BOOLEAN: field.set(model, document.getBoolean(field.getName())); break; case DATETIME: field.set(model, DateUtil.toLocalDateTime(document.getDate(field.getName()))); break; case DATE: field.set(model, document.getDate(field.getName())); break; default: // TODO: Object type - Not supported yet } } private <T> void parseIdField(final T model, final Document document) { try { final ObjectId objectId = document.getObjectId("_id"); final String id = objectId == null ? null : objectId.toString(); final Method method = model.getClass().getDeclaredMethod("setId", String.class); method.invoke(model, id); } catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { // Just ignore it } } }
package net.sf.jabref.gui; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoableEdit; import com.jgoodies.forms.builder.DefaultFormBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import net.sf.jabref.AbstractWorker; import net.sf.jabref.BasePanel; import net.sf.jabref.BibtexEntry; import net.sf.jabref.CheckBoxMessage; import net.sf.jabref.GUIGlobals; import net.sf.jabref.Globals; import net.sf.jabref.ImportSettingsTab; import net.sf.jabref.JabRefFrame; import net.sf.jabref.JabRefPreferences; import net.sf.jabref.Util; import net.sf.jabref.external.ExternalFileType; import net.sf.jabref.imports.HTMLConverter; import net.sf.jabref.undo.NamedCompound; import net.sf.jabref.undo.UndoableFieldChange; public class CleanUpAction extends AbstractWorker { private Logger logger = Logger.getLogger(CleanUpAction.class.getName()); public final static String AKS_AUTO_NAMING_PDFS_AGAIN = "AskAutoNamingPDFsAgain", CLEANUP_DOI = "CleanUpDOI", CLEANUP_MONTH = "CleanUpMonth", CLEANUP_PAGENUMBERS = "CleanUpPageNumbers", CLEANUP_MAKEPATHSRELATIVE = "CleanUpMakePathsRelative", CLEANUP_RENAMEPDF = "CleanUpRenamePDF", CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS = "CleanUpRenamePDFonlyRelativePaths", CLEANUP_SUPERSCRIPTS = "CleanUpSuperscripts", CLEANUP_HTML = "CleanUpHTML"; public static void putDefaults(HashMap<String, Object> defaults) { defaults.put(AKS_AUTO_NAMING_PDFS_AGAIN, Boolean.TRUE); defaults.put(CLEANUP_SUPERSCRIPTS, Boolean.TRUE); defaults.put(CLEANUP_DOI, Boolean.TRUE); defaults.put(CLEANUP_MONTH, Boolean.TRUE); defaults.put(CLEANUP_PAGENUMBERS, Boolean.TRUE); defaults.put(CLEANUP_MAKEPATHSRELATIVE, Boolean.TRUE); defaults.put(CLEANUP_RENAMEPDF, Boolean.TRUE); defaults.put(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS, Boolean.FALSE); defaults.put(CLEANUP_MAKEPATHSRELATIVE, Boolean.TRUE); defaults.put(CLEANUP_HTML, Boolean.TRUE); } private JCheckBox cleanUpSuperscrips; private JCheckBox cleanUpDOI; private JCheckBox cleanUpMonth; private JCheckBox cleanUpPageNumbers; private JCheckBox cleanUpMakePathsRelative; private JCheckBox cleanUpRenamePDF; private JCheckBox cleanUpRenamePDFonlyRelativePaths; private JCheckBox cleanUpHTML; private JPanel optionsPanel = new JPanel(); private BasePanel panel; private JabRefFrame frame; // global variable to count unsucessful Renames int unsuccesfullRenames = 0; public CleanUpAction(BasePanel panel) { this.panel = panel; this.frame = panel.frame(); initOptionsPanel(); } private void initOptionsPanel() { cleanUpSuperscrips = new JCheckBox(Globals.lang("Convert 1st, 2nd, ... to real superscripts")); cleanUpDOI = new JCheckBox(Globals.lang("Move DOIs from note and URL field to DOI field and remove http prefix")); cleanUpMonth = new JCheckBox(Globals.lang("Format content of month field to #mon#")); cleanUpPageNumbers = new JCheckBox(Globals.lang("Ensure that page ranges are of the form num1--num2")); cleanUpMakePathsRelative = new JCheckBox(Globals.lang("Make paths of linked files relative (if possible)")); cleanUpRenamePDF = new JCheckBox(Globals.lang("Rename PDFs to given file name format pattern")); cleanUpRenamePDF.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { cleanUpRenamePDFonlyRelativePaths.setEnabled(cleanUpRenamePDF.isSelected()); } }); cleanUpRenamePDFonlyRelativePaths = new JCheckBox(Globals.lang("Rename only PDFs having a relative path")); cleanUpHTML = new JCheckBox(Globals.lang("Run HTML converter on title")); optionsPanel = new JPanel(); retrieveSettings(); FormLayout layout = new FormLayout("left:15dlu,pref:grow", "pref, pref, pref, pref, pref, pref, pref, pref, pref"); DefaultFormBuilder builder = new DefaultFormBuilder(layout, optionsPanel); builder.setDefaultDialogBorder(); CellConstraints cc = new CellConstraints(); builder.add(cleanUpHTML, cc.xyw(1,1,2)); builder.add(cleanUpSuperscrips, cc.xyw(1,2,2)); builder.add(cleanUpDOI, cc.xyw(1,3,2)); builder.add(cleanUpMonth, cc.xyw(1,4,2)); builder.add(cleanUpPageNumbers, cc.xyw(1,5,2)); builder.add(cleanUpMakePathsRelative, cc.xyw(1,6,2)); builder.add(cleanUpRenamePDF, cc.xyw(1,7,2)); String currentPattern = Globals.lang("File name format pattern").concat(": ").concat(Globals.prefs.get(ImportSettingsTab.PREF_IMPORT_FILENAMEPATTERN)); builder.add(new JLabel(currentPattern), cc.xyw(2,8,1)); builder.add(cleanUpRenamePDFonlyRelativePaths, cc.xyw(2,9,1)); } private void retrieveSettings() { cleanUpSuperscrips.setSelected(Globals.prefs.getBoolean(CLEANUP_SUPERSCRIPTS)); cleanUpDOI.setSelected(Globals.prefs.getBoolean(CLEANUP_DOI)); cleanUpMonth.setSelected(Globals.prefs.getBoolean(CLEANUP_MONTH)); cleanUpPageNumbers.setSelected(Globals.prefs.getBoolean(CLEANUP_PAGENUMBERS)); cleanUpMakePathsRelative.setSelected(Globals.prefs.getBoolean(CLEANUP_MAKEPATHSRELATIVE)); cleanUpRenamePDF.setSelected(Globals.prefs.getBoolean(CLEANUP_RENAMEPDF)); cleanUpRenamePDFonlyRelativePaths.setSelected(Globals.prefs.getBoolean(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS)); cleanUpRenamePDFonlyRelativePaths.setEnabled(cleanUpRenamePDF.isSelected()); cleanUpHTML.setSelected(Globals.prefs.getBoolean(CLEANUP_HTML)); } private void storeSettings() { Globals.prefs.putBoolean(CLEANUP_SUPERSCRIPTS, cleanUpSuperscrips.isSelected()); Globals.prefs.putBoolean(CLEANUP_DOI, cleanUpDOI.isSelected()); Globals.prefs.putBoolean(CLEANUP_MONTH, cleanUpMonth.isSelected()); Globals.prefs.putBoolean(CLEANUP_PAGENUMBERS, cleanUpPageNumbers.isSelected()); Globals.prefs.putBoolean(CLEANUP_MAKEPATHSRELATIVE, cleanUpMakePathsRelative.isSelected()); Globals.prefs.putBoolean(CLEANUP_RENAMEPDF, cleanUpRenamePDF.isSelected()); Globals.prefs.putBoolean(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS, cleanUpRenamePDFonlyRelativePaths.isSelected()); Globals.prefs.putBoolean(CLEANUP_HTML, cleanUpHTML.isSelected()); } private int showCleanUpDialog() { String dialogTitle = Globals.lang("Cleanup entries"); Object[] messages = {Globals.lang("What would you like to clean up?"), optionsPanel}; return JOptionPane.showConfirmDialog(frame, messages, dialogTitle, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); } boolean cancelled; int modifiedEntriesCount; int numSelected; public void init() { cancelled = false; modifiedEntriesCount = 0; int numSelected = panel.getSelectedEntries().length; if (numSelected == 0) { // None selected. Inform the user to select entries first. JOptionPane.showMessageDialog(frame, Globals.lang("First select entries to clean up."), Globals.lang("Cleanup entry"), JOptionPane.INFORMATION_MESSAGE); cancelled = true; return; } frame.block(); panel.output(Globals.lang("Doing a cleanup for %0 entries...", Integer.toString(numSelected))); } public void run() { if (cancelled) return; int choice = showCleanUpDialog(); if (choice != JOptionPane.OK_OPTION) { cancelled = true; return; } storeSettings(); boolean choiceCleanUpSuperscripts = cleanUpSuperscrips.isSelected(), choiceCleanUpDOI = cleanUpDOI.isSelected(), choiceCleanUpMonth = cleanUpMonth.isSelected(), choiceCleanUpPageNumbers = cleanUpPageNumbers.isSelected(), choiceMakePathsRelative = cleanUpMakePathsRelative.isSelected(), choiceRenamePDF = cleanUpRenamePDF.isSelected(), choiceConvertHTML = cleanUpHTML.isSelected(); if (choiceRenamePDF && Globals.prefs.getBoolean(AKS_AUTO_NAMING_PDFS_AGAIN)) { CheckBoxMessage cbm = new CheckBoxMessage(Globals.lang("Auto-generating PDF-Names does not support undo. Continue?"), Globals.lang("Disable this confirmation dialog"), false); int answer = JOptionPane.showConfirmDialog(frame, cbm, Globals.lang("Autogenerate PDF Names"), JOptionPane.YES_NO_OPTION); if (cbm.isSelected()) Globals.prefs.putBoolean(AKS_AUTO_NAMING_PDFS_AGAIN, false); if (answer == JOptionPane.NO_OPTION) { cancelled = true; return; } } for (BibtexEntry entry : panel.getSelectedEntries()) { // undo granularity is on entry level NamedCompound ce = new NamedCompound(Globals.lang("Cleanup entry")); if (choiceCleanUpSuperscripts) doCleanUpSuperscripts(entry, ce); if (choiceCleanUpDOI) doCleanUpDOI(entry, ce); if (choiceCleanUpMonth) doCleanUpMonth(entry, ce); if (choiceCleanUpPageNumbers) doCleanUpPageNumbers(entry, ce); if (choiceMakePathsRelative) doMakePathsRelative(entry, ce); if (choiceRenamePDF) doRenamePDFs(entry, ce); if (choiceConvertHTML) doConvertHTML(entry, ce); ce.end(); if (ce.hasEdits()) { modifiedEntriesCount++; panel.undoManager.addEdit(ce); } } } public void update() { if (cancelled) { frame.unblock(); return; } if(unsuccesfullRenames>0) { //Rename failed for at least one entry JOptionPane.showMessageDialog(frame, Globals.lang("File rename failed for")+" " + unsuccesfullRenames + " "+Globals.lang("entries") + ".", Globals.lang("Autogenerate PDF Names"), JOptionPane.INFORMATION_MESSAGE); } if (modifiedEntriesCount>0) { panel.updateEntryEditorIfShowing(); panel.markBaseChanged() ; } String message; switch (modifiedEntriesCount) { case 0: message = Globals.lang("No entry needed a clean up"); break; case 1: message = Globals.lang("One entry needed a clean up"); break; default: message = Globals.lang("%0 entries needed a clean up"); break; } panel.output(message); frame.unblock(); } /** * Converts the text in 1st, 2nd, ... to real superscripts by wrapping in \textsuperscript{st}, ... */ private void doCleanUpSuperscripts(BibtexEntry entry, NamedCompound ce) { final String field = "booktitle"; String oldValue = entry.getField(field); if (oldValue == null) return; String newValue = oldValue.replaceAll(" (\\d+)(st|nd|rd|th) ", " $1\\\\textsuperscript{$2} "); if (!oldValue.equals(newValue)) { entry.setField(field, newValue); ce.addEdit(new UndoableFieldChange(entry, field, oldValue, newValue)); } } private void doCleanUpDOI(BibtexEntry bes, NamedCompound ce) { // fields to check String[] fields = {"note", "url", "ee"}; // First check if the DOI Field is empty if (bes.getField("doi") != null) { String doiFieldValue = bes.getField("doi"); if (Util.checkForDOIwithHTTPprefix(doiFieldValue)) { String newValue = Util.getDOI(doiFieldValue); ce.addEdit(new UndoableFieldChange(bes, "doi", doiFieldValue, newValue)); bes.setField("doi", newValue); }; if (Util.checkForPlainDOI(doiFieldValue)) { // DOI field seems to contain DOI // cleanup note, url, ee field // we do NOT copy values to the DOI field as the DOI field contains a DOI! for (String field: fields) { if (Util.checkForPlainDOI(bes.getField(field))){ Util.removeDOIfromBibtexEntryField(bes, field, ce); } } } } else { // As the DOI field is empty we now check if note, url, or ee field contains a DOI for (String field: fields) { if (Util.checkForPlainDOI(bes.getField(field))){ // update DOI String oldValue = bes.getField("doi"); String newValue = Util.getDOI(bes.getField(field)); ce.addEdit(new UndoableFieldChange(bes, "doi", oldValue, newValue)); bes.setField("doi", newValue); Util.removeDOIfromBibtexEntryField(bes, field, ce); } } } } private void doCleanUpMonth(BibtexEntry entry, NamedCompound ce) { // implementation based on patch 3470076 by Mathias Walter String oldValue = entry.getField("month"); if (oldValue == null) return; String newValue = oldValue; try { int month = Integer.parseInt(newValue); newValue = new StringBuffer("#").append(Globals.MONTHS[month - 1]).append('#').toString(); } catch (NumberFormatException e) { // adapt casing of newValue to follow entry in Globals_MONTH_STRINGS String casedString = newValue.substring(0, 1).toUpperCase().concat(newValue.substring(1).toLowerCase()); if (Globals.MONTH_STRINGS.containsKey(newValue.toLowerCase()) || Globals.MONTH_STRINGS.containsValue(casedString)) { newValue = new StringBuffer("#").append(newValue.substring(0, 3).toLowerCase()).append('#').toString(); } } if (!oldValue.equals(newValue)) { entry.setField("month", newValue); ce.addEdit(new UndoableFieldChange(entry, "month", oldValue, newValue)); } } private void doCleanUpPageNumbers(BibtexEntry entry, NamedCompound ce) { String oldValue = entry.getField("pages"); if (oldValue == null) return; String newValue = oldValue.replaceAll("(\\d+) *- *(\\d+)", "$1 if (!oldValue.equals(newValue)) { entry.setField("pages", newValue); ce.addEdit(new UndoableFieldChange(entry, "pages", oldValue, newValue)); } } private void doExportToKeywords(BibtexEntry entry, NamedCompound ce) { } private void doImportFromKeywords(BibtexEntry entry, NamedCompound ce) { } private void doMakePathsRelative(BibtexEntry entry, NamedCompound ce) { String oldValue = entry.getField(GUIGlobals.FILE_FIELD); if (oldValue == null) return; FileListTableModel flModel = new FileListTableModel(); flModel.setContent(oldValue); if (flModel.getRowCount() == 0) { return; } boolean changed = false; for (int i = 0; i<flModel.getRowCount(); i++) { FileListEntry flEntry = flModel.getEntry(i); String oldFileName = flEntry.getLink(); String newFileName = Util.shortenFileName(new File(oldFileName), panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD)).toString(); if (!oldFileName.equals(newFileName)) { flEntry.setLink(newFileName); changed = true; } } if (changed) { String newValue = flModel.getStringRepresentation(); assert(!oldValue.equals(newValue)); entry.setField(GUIGlobals.FILE_FIELD, newValue); ce.addEdit(new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue)); } } private void doRenamePDFs(BibtexEntry entry, NamedCompound ce) { //Extract the path String oldValue = entry.getField(GUIGlobals.FILE_FIELD); if (oldValue == null) return; FileListTableModel flModel = new FileListTableModel(); flModel.setContent(oldValue); if (flModel.getRowCount() == 0) { return; } boolean changed = false; for (int i=0; i<flModel.getRowCount(); i++) { String realOldFilename = flModel.getEntry(i).getLink(); if (cleanUpRenamePDFonlyRelativePaths.isSelected() && (new File(realOldFilename).isAbsolute())) return; String newFilename = Util.getLinkedFileName(panel.database(), entry); //String oldFilename = bes.getField(GUIGlobals.FILE_FIELD); // would have to be stored for undoing purposes //Add extension to newFilename newFilename = newFilename + "." + flModel.getEntry(i).getType().getExtension(); //get new Filename with path //Create new Path based on old Path and new filename File expandedOldFile = Util.expandFilename(realOldFilename, panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD)); String newPath = expandedOldFile.getParent().concat(System.getProperty("file.separator")).concat(newFilename); if (new File(newPath).exists()) // we do not overwrite files // TODO: we could check here if the newPath file is linked with the current entry. And if not, we could add a link return; //do rename boolean renameSuccesfull = Util.renameFile(expandedOldFile.toString(), newPath); if (renameSuccesfull) { changed = true; //Change the path for this entry String description = flModel.getEntry(i).getDescription(); ExternalFileType type = flModel.getEntry(i).getType(); flModel.removeEntry(i); // we cannot use "newPath" to generate a FileListEntry as newPath is absolute, but we want to keep relative paths whenever possible File parent = (new File(realOldFilename)).getParentFile(); String newFileEntryFileName; if (parent == null) { newFileEntryFileName = newFilename; } else { newFileEntryFileName = parent.toString().concat(System.getProperty("file.separator")).concat(newFilename); } flModel.addEntry(i, new FileListEntry(description, newFileEntryFileName, type)); } else { unsuccesfullRenames++; } } if (changed) { String newValue = flModel.getStringRepresentation(); assert(!oldValue.equals(newValue)); entry.setField(GUIGlobals.FILE_FIELD, newValue); //we put an undo of the field content here //the file is not being renamed back, which leads to inconsostencies //if we put a null undo object here, the change by "doMakePathsRelative" would overwrite the field value nevertheless. ce.addEdit(new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue)); } } /** * Converts HTML code to LaTeX code */ private void doConvertHTML(BibtexEntry entry, NamedCompound ce) { final String field = "title"; String oldValue = entry.getField(field); if (oldValue == null) return; final HTMLConverter htmlConverter = new HTMLConverter(); String newValue = htmlConverter.format(oldValue); if (!oldValue.equals(newValue)) { entry.setField(field, newValue); ce.addEdit(new UndoableFieldChange(entry, field, oldValue, newValue)); } } }
package org.animotron.graph; import org.animotron.Executor; import org.animotron.graph.index.Cache; import org.animotron.graph.index.Order; import org.animotron.graph.index.Result; import org.animotron.graph.index.State; import org.animotron.statement.language.WORD; import org.animotron.statement.operator.THE; import org.neo4j.graphdb.*; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.kernel.EmbeddedGraphDatabase; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static org.neo4j.graphdb.Direction.OUTGOING; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class AnimoGraph { private final static String BIN_STORAGE = "binary"; private final static String TMP_STORAGE = "tmp"; private static GraphDatabaseService graphDb = null; private static String STORAGE; private static List<Transaction> activeTx; private static Map<Transaction, Throwable> debugActiveTx; private static Node ROOT; private static File BIN; private static File TMP; public static boolean startDB(String folder, Map<String, String> config) { if (graphDb != null) { return false; } System.gc(); activeTx = Collections.synchronizedList(new LinkedList<Transaction>()); debugActiveTx = new ConcurrentHashMap<Transaction, Throwable>(); STORAGE = folder; Executor.init(); graphDb = new EmbeddedGraphDatabase(STORAGE, config); BIN = new File(STORAGE, BIN_STORAGE); BIN.mkdir(); TMP = new File(STORAGE, TMP_STORAGE); TMP.mkdir(); initDB(); return true; } public static boolean startDB(String folder) { return startDB(folder, new HashMap<String, String>()); } public static void initDB() { ROOT = graphDb.getReferenceNode(); IndexManager index = graphDb.index(); Cache.RELATIONSHIP.init(index); Cache.NODE.init(index); Result._.init(index); Order._.init(index); State._.init(index); WORD._.init(index); THE._.init(index); } public static GraphDatabaseService getDb() { return graphDb; } public static String getStorage() { return STORAGE; } public static File binStorage(){ return BIN; } public static File tmpStorage(){ return TMP; } public static Node getROOT() { return ROOT; } public static void shutdownDB() { if (graphDb == null) { return; } System.out.println("shotdown"); Executor.shutdown(); while (!activeTx.isEmpty()) { System.out.println("Active transactions "+activeTx.size()); for (Map.Entry<Transaction, Throwable> e : debugActiveTx.entrySet()) { if (e != null) { System.out.println(e.getKey()); e.getValue().printStackTrace(); } else { System.out.println("NULL @ debugActiveTx"); } } try { Thread.sleep(1000); } catch (InterruptedException e) {} } graphDb.shutdown(); graphDb = null; } public static Transaction beginTx() { Transaction tx = graphDb.beginTx(); activeTx.add(tx); debugActiveTx.put(tx, new IOException()); return tx; } public static void finishTx(final Transaction tx) { if (tx == null) { System.out.println("tx == NULL"); return; } tx.finish(); activeTx.remove(tx); debugActiveTx.remove(tx); } // public static boolean isTransactionActive(Transaction tx) { // return activeTx.containsKey(tx); /** * Execute operation with transaction. * @param <T> * * @param operation * @return */ public static <T> T execute(GraphOperation<T> operation) throws Throwable { T result = null; Transaction tx = beginTx(); try { result = operation.execute(); tx.success(); } catch (Throwable t) { throw t; } finally { finishTx(tx); } return result; } public static Node getNode(Node parent, RelationshipType type) { Relationship r = parent.getSingleRelationship(type, OUTGOING); return r == null ? null : r.getEndNode(); } public static Node createNode(){ return graphDb.createNode(); } public static Node createNode(Node parent, RelationshipType type) { Node node = createNode(); parent.createRelationshipTo(node, type); return node; } public static Node getOrCreateNode(Node parent, RelationshipType type) { Relationship r = parent.getSingleRelationship(type, OUTGOING); if (r != null) return r.getEndNode(); Node node = createNode(parent, type); return node; } public static void copyProperties(PropertyContainer src, PropertyContainer dst) { for (String name : src.getPropertyKeys()) { dst.setProperty(name, src.getProperty(name)); } } public static Relationship copy(Node start, Relationship r) { Relationship c = start.createRelationshipTo(r.getEndNode(), r.getType()); copyProperties(r, c); return c; } public static Relationship copy(Relationship r, Node end) { Relationship c = r.getStartNode().createRelationshipTo(end, r.getType()); copyProperties(r, c); return c; } }
package net.sf.picard.util; import net.sf.picard.PicardException; import net.sf.picard.io.IoUtil; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMSequenceDictionary; import net.sf.samtools.SAMTextHeaderCodec; import net.sf.samtools.util.StringLineReader; import java.io.*; import java.util.*; /** * Represents a list of intervals against a reference sequence that can be written to * and read from a file. The file format is relatively simple and reflects the SAM * alignment format to a degree. * * A SAM style header must be present in the file which lists the sequence records * against which the intervals are described. After the header the file then contains * records one per line in text format with the following values tab-separated: * - Sequence name * - Start position (1-based) * - End position (1-based, end inclusive) * - Strand (either + or -) * - Interval name (an, ideally unique, name for the interval) * * @author Tim Fennell */ public class IntervalList implements Iterable<Interval> { private final SAMFileHeader header; private final List<Interval> intervals = new ArrayList<Interval>(); private static final Log log = Log.getInstance(IntervalList.class); /** Constructs a new interval list using the supplied header information. */ public IntervalList(final SAMFileHeader header) { if (header == null) { throw new IllegalArgumentException("SAMFileHeader must be supplied."); } this.header = header; } /** Gets the header (if there is one) for the interval list. */ public SAMFileHeader getHeader() { return header; } /** Returns an iterator over the intervals. */ public Iterator<Interval> iterator() { return this.intervals.iterator(); } /** Adds an interval to the list of intervals. */ public void add(final Interval interval) { this.intervals.add(interval); } /** Sorts the internal collection of intervals by coordinate. */ public void sort() { Collections.sort(this.intervals, new IntervalCoordinateComparator(this.header)); this.header.setSortOrder(SAMFileHeader.SortOrder.coordinate); } /** Sorts and uniques the list of intervals held within this interval list. */ public void unique() { unique(true); } /** * Sorts and uniques the list of intervals held within this interval list. * @param concatenateNames If false, interval names are not concatenated when merging intervals to save space. */ public void unique(final boolean concatenateNames) { sort(); final List<Interval> tmp = getUniqueIntervals(concatenateNames); this.intervals.clear(); this.intervals.addAll(tmp); } /** Gets the set of intervals as held internally. */ public List<Interval> getIntervals() { return Collections.unmodifiableList(this.intervals); } /** * Merges the list of intervals and then reduces them down where regions overlap * or are directly adjacent to one another. During this process the "merged" interval * will retain the strand and name of the 5' most interval merged. * * Note: has the side-effect of sorting the stored intervals in coordinate order if not already sorted. * * @return the set of unique intervals condensed from the contained intervals */ public List<Interval> getUniqueIntervals() { return getUniqueIntervals(true); } /** * Merges list of intervals and reduces them like net.sf.picard.util.IntervalList#getUniqueIntervals() * @param concatenateNames If false, the merged interval has the name of the earlier interval. This keeps name shorter. */ public List<Interval> getUniqueIntervals(final boolean concatenateNames) { if (getHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) { sort(); } final List<Interval> unique = new ArrayList<Interval>(); final ListIterator<Interval> iterator = this.intervals.listIterator(); Interval previous = iterator.next(); while (iterator.hasNext()) { final Interval next = iterator.next(); if (previous.intersects(next) || previous.abuts(next)) { final String intervalName = (concatenateNames? previous.getName() + "|" + next.getName(): previous.getName()); previous = new Interval(previous.getSequence(), previous.getStart(), Math.max(previous.getEnd(), next.getEnd()), previous.isNegativeStrand(), intervalName); } else { unique.add(previous); previous = next; } } if (previous != null) unique.add(previous); return unique; } /** Gets the (potentially redundant) sum of the length of the intervals in the list. */ public long getBaseCount() { return Interval.countBases(this.intervals); } /** Gets the count of unique bases represented by the intervals in the list. */ public long getUniqueBaseCount() { return Interval.countBases(getUniqueIntervals()); } /** Returns the count of intervals in the list. */ public int size() { return this.intervals.size(); } /** * Parses an interval list from a file. * @param file the file containing the intervals * @return an IntervalList object that contains the headers and intervals from the file */ public static IntervalList fromFile(final File file) { return fromReader(new BufferedReader(new InputStreamReader(IoUtil.openFileForReading(file)), IoUtil.STANDARD_BUFFER_SIZE)); } /** * Parses an interval list from a reader in a stream based fashion. * @param in a BufferedReader that can be read from * @return an IntervalList object that contains the headers and intervals from the file */ public static IntervalList fromReader(final BufferedReader in) { try { // Setup a reader and parse the header final StringBuilder builder = new StringBuilder(4096); String line = null; while ((line = in.readLine()) != null) { if (line.startsWith("@")) { builder.append(line).append('\n'); } else { break; } } if (builder.length() == 0) { throw new IllegalStateException("Interval list file must contain header. "); } final StringLineReader headerReader = new StringLineReader(builder.toString()); final SAMTextHeaderCodec codec = new SAMTextHeaderCodec(); final IntervalList list = new IntervalList(codec.decode(headerReader, "BufferedReader")); final SAMSequenceDictionary dict = list.getHeader().getSequenceDictionary(); // Then read in the intervals final FormatUtil format = new FormatUtil(); do { if (line.trim().length() == 0) continue; // skip over blank lines // Make sure we have the right number of fields final String[] fields = line.split("\t"); if (fields.length != 5) { throw new PicardException("Invalid interval record contains " + fields.length + " fields: " + line); } // Then parse them out final String seq = fields[0]; final int start = format.parseInt(fields[1]); final int end = format.parseInt(fields[2]); final boolean negative; if (fields[3].equals("-")) negative = true; else if (fields[3].equals("+")) negative = false; else throw new IllegalArgumentException("Invalid strand field: " + fields[3]); final String name = fields[4]; final Interval interval = new Interval(seq, start, end, negative, name); if (dict.getSequence(seq) == null) { log.warn("Ignoring interval for unknown reference: " + interval); } else { list.intervals.add(interval); } } while ((line = in.readLine()) != null); return list; } catch (IOException ioe) { throw new PicardException("Error parsing interval list.", ioe); } finally { try { in.close(); } catch (Exception e) { /* do nothing */ } } } /** * Writes out the list of intervals to the supplied file. * @param file a file to write to. If exists it will be overwritten. */ public void write(final File file) { try { final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(IoUtil.openFileForWriting(file)), IoUtil.STANDARD_BUFFER_SIZE); final FormatUtil format = new FormatUtil(); // Write out the header if (this.header != null) { final SAMTextHeaderCodec codec = new SAMTextHeaderCodec(); codec.encode(out, this.header); } // Write out the intervals for (final Interval interval : this) { out.write(interval.getSequence()); out.write('\t'); out.write(format.format(interval.getStart())); out.write('\t'); out.write(format.format(interval.getEnd())); out.write('\t'); out.write(interval.isPositiveStrand() ? '+' : '-'); out.write('\t'); out.write(interval.getName()); out.newLine(); } out.flush(); out.close(); } catch (IOException ioe) { throw new PicardException("Error writing out interval list to file: " + file.getAbsolutePath(), ioe); } } } /** * Comparator that orders intervals based on their sequence index, by coordinate * then by strand and finally by name. */ class IntervalCoordinateComparator implements Comparator<Interval> { private final SAMFileHeader header; /** Constructs a comparator using the supplied sequence header. */ IntervalCoordinateComparator(final SAMFileHeader header) { this.header = header; } public int compare(final Interval lhs, final Interval rhs) { final int lhsIndex = this.header.getSequenceIndex(lhs.getSequence()); final int rhsIndex = this.header.getSequenceIndex(rhs.getSequence()); int retval = lhsIndex - rhsIndex; if (retval == 0) retval = lhs.getStart() - rhs.getStart(); if (retval == 0) retval = lhs.getEnd() - rhs.getEnd(); if (retval == 0) { if (lhs.isPositiveStrand() && rhs.isNegativeStrand()) retval = -1; else if (lhs.isNegativeStrand() && rhs.isPositiveStrand()) retval = 1; } if (retval == 0) { retval = lhs.getName().compareTo(rhs.getName()); } return retval; } }
package org.dynmap.canary; import java.io.File; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import net.canarymod.Canary; import net.canarymod.api.OfflinePlayer; import net.canarymod.api.PlayerReference; import net.canarymod.api.chat.ChatComponent; import net.canarymod.api.entity.living.humanoid.CanaryPlayer; import net.canarymod.api.entity.living.humanoid.Player; import net.canarymod.api.world.Biome; import net.canarymod.api.world.Chunk; import net.canarymod.api.world.World; import net.canarymod.api.world.blocks.Block; import net.canarymod.api.world.blocks.BlockType; import net.canarymod.api.world.blocks.Sign; import net.canarymod.api.world.position.Location; import net.canarymod.bansystem.Ban; import net.canarymod.chat.MessageReceiver; import net.canarymod.chat.ReceiverType; import net.canarymod.commandsys.Command; import net.canarymod.commandsys.CommandDependencyException; import net.canarymod.commandsys.CommandListener; import net.canarymod.config.Configuration; import net.canarymod.exceptions.InvalidPluginException; import net.canarymod.exceptions.PluginLoadFailedException; import net.canarymod.hook.HookHandler; import net.canarymod.hook.player.BedExitHook; import net.canarymod.hook.player.BlockDestroyHook; import net.canarymod.hook.player.BlockPlaceHook; import net.canarymod.hook.player.ChatHook; import net.canarymod.hook.player.ConnectionHook; import net.canarymod.hook.player.DisconnectionHook; import net.canarymod.hook.player.PlayerMoveHook; import net.canarymod.hook.player.SignChangeHook; import net.canarymod.hook.system.LoadWorldHook; import net.canarymod.hook.system.PluginEnableHook; import net.canarymod.hook.system.ServerTickHook; import net.canarymod.hook.system.UnloadWorldHook; import net.canarymod.hook.world.BlockGrowHook; import net.canarymod.hook.world.BlockPhysicsHook; import net.canarymod.hook.world.BlockUpdateHook; import net.canarymod.hook.world.ChunkCreatedHook; import net.canarymod.hook.world.DecorateHook; import net.canarymod.hook.world.ExplosionHook; import net.canarymod.hook.world.FlowHook; import net.canarymod.hook.world.IgnitionHook; import net.canarymod.hook.world.LeafDecayHook; import net.canarymod.hook.world.LiquidDestroyHook; import net.canarymod.hook.world.PistonExtendHook; import net.canarymod.hook.world.PistonRetractHook; import net.canarymod.hook.world.RedstoneChangeHook; import net.canarymod.hook.world.IgnitionHook.IgnitionCause; import net.canarymod.hook.world.TreeGrowHook; import net.canarymod.logger.Logman; import net.canarymod.plugin.Plugin; import net.canarymod.plugin.PluginListener; import net.canarymod.plugin.PluginManager; import net.canarymod.plugin.Priority; import net.canarymod.tasks.ServerTask; import net.canarymod.tasks.ServerTaskManager; import org.dynmap.DynmapChunk; import org.dynmap.DynmapCommonAPI; import org.dynmap.DynmapCommonAPIListener; import org.dynmap.DynmapCore; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWorld; import org.dynmap.Log; import org.dynmap.MapManager; import org.dynmap.PlayerList; import org.dynmap.common.BiomeMap; import org.dynmap.common.DynmapCommandSender; import org.dynmap.common.DynmapPlayer; import org.dynmap.common.DynmapServerInterface; import org.dynmap.common.DynmapListenerManager.EventType; import org.dynmap.markers.MarkerAPI; import org.dynmap.modsupport.ModSupportImpl; import org.dynmap.utils.DynmapLogger; import org.dynmap.utils.MapChunkCache; import org.dynmap.utils.VisibilityLimit; public class DynmapPlugin extends Plugin implements DynmapCommonAPI { private DynmapCore core; private CanaryServer server; private String version; public SnapshotCache sscache; public PlayerList playerList; private MapManager mapManager; public static DynmapPlugin plugin; public PluginManager pm; private BukkitEnableCoreCallback enabCoreCB = new BukkitEnableCoreCallback(); private HashMap<String, CanaryModWorld> world_by_name = new HashMap<String, CanaryModWorld>(); private long perTickLimit; private int chunks_in_cur_tick = 0; private long prev_tick; private HashMap<String, Integer> sortWeights = new HashMap<String, Integer>(); /* Lookup cache */ private World last_world; private CanaryModWorld last_bworld; private CanaryVersionHelper helper; private static class TaskRecord implements Comparable<Object> { private long ticktorun; private long id; private FutureTask<?> future; @Override public int compareTo(Object o) { TaskRecord tr = (TaskRecord)o; if (this.ticktorun < tr.ticktorun) { return -1; } else if (this.ticktorun > tr.ticktorun) { return 1; } else if (this.id < tr.id) { return -1; } else if (this.id > tr.id) { return 1; } else { return 0; } } } private final CanaryModWorld getWorldByName(String name) { if((last_world != null) && (last_world.getFqName().equals(name))) { return last_bworld; } return world_by_name.get(name); } private final CanaryModWorld getWorld(World w) { if(last_world == w) { return last_bworld; } CanaryModWorld bw = world_by_name.get(w.getFqName()); if(bw == null) { bw = new CanaryModWorld(w); world_by_name.put(w.getFqName(), bw); } else if(bw.isLoaded() == false) { bw.setWorldLoaded(w); } last_world = w; last_bworld = bw; return bw; } final void removeWorld(World w) { world_by_name.remove(w.getFqName()); if(w == last_world) { last_world = null; last_bworld = null; } } private class BukkitEnableCoreCallback extends DynmapCore.EnableCoreCallbacks { @Override public void configurationLoaded() { File st = new File(core.getDataFolder(), "renderdata/spout-texture.txt"); if(st.exists()) { st.delete(); } } } private static class BlockToCheck { Location loc; int typeid; byte data; String trigger; }; private LinkedList<BlockToCheck> blocks_to_check = null; private LinkedList<BlockToCheck> blocks_to_check_accum = new LinkedList<BlockToCheck>(); public DynmapPlugin() { plugin = this; helper = CanaryVersionHelper.getHelper(); pm = Canary.pluginManager(); ModSupportImpl.init(); } /** * Server access abstraction class */ public class CanaryServer extends DynmapServerInterface implements PluginListener { /* Server thread scheduler */ private Object schedlock = new Object(); private long cur_tick; private long next_id; private long cur_tick_starttime; private PriorityQueue<TaskRecord> runqueue = new PriorityQueue<TaskRecord>(); @Override public int getBlockIDAt(String wname, int x, int y, int z) { World w = Canary.getServer().getWorld(wname); Chunk c = null; if (w != null) { c = w.getChunk(x >> 4, z >> 4); } if (c != null) { return c.getBlockTypeAt(x & 0xF, y, z & 0xF); } return -1; } @Override public void scheduleServerTask(Runnable run, long delay) { TaskRecord tr = new TaskRecord(); tr.future = new FutureTask<Object>(run, null); /* Add task record to queue */ synchronized (schedlock) { tr.id = next_id++; tr.ticktorun = cur_tick + delay; runqueue.add(tr); } } @Override public DynmapPlayer[] getOnlinePlayers() { List<Player> players = Canary.getServer().getPlayerList(); DynmapPlayer[] dplay = new DynmapPlayer[players.size()]; for(int i = 0; i < dplay.length; i++) dplay[i] = new BukkitPlayer(players.get(i)); return dplay; } @Override public void reload() { PluginManager pluginManager = Canary.pluginManager(); try { pluginManager.reloadPlugin("dynmap"); } catch (PluginLoadFailedException e) { } catch (InvalidPluginException e) { } } @Override public DynmapPlayer getPlayer(String name) { Player p = Canary.getServer().getPlayer(name); if(p != null) { return new BukkitPlayer(p); } return null; } @Override public Set<String> getIPBans() { Ban[] blist = Canary.bans().getAllBans(); Set<String> rslt = new HashSet<String>(); for (Ban b : blist) { if (b.isIpBan()) { rslt.add(b.getIp()); } } return rslt; } @Override public <T> Future<T> callSyncMethod(Callable<T> task) { return callSyncMethod(task, 0); } public <T> Future<T> callSyncMethod(Callable<T> task, long delay) { TaskRecord tr = new TaskRecord(); FutureTask<T> ft = new FutureTask<T>(task); tr.future = ft; /* Add task record to queue */ synchronized (schedlock) { tr.id = next_id++; tr.ticktorun = cur_tick + delay; runqueue.add(tr); } return ft; } @Override public String getServerName() { return Configuration.getServerConfig().getMotd(); } @Override public boolean isPlayerBanned(String pid) { return Canary.bans().isBanned(pid); } @Override public String stripChatColor(String s) { return org.dynmap.common.DynmapChatColor.stripColor(s); } private Set<EventType> registered = new HashSet<EventType>(); @Override public boolean requestEventNotification(EventType type) { if(registered.contains(type)) return true; switch(type) { case WORLD_LOAD: case WORLD_UNLOAD: /* Already called for normal world activation/deactivation */ break; case WORLD_SPAWN_CHANGE: //Canary.hooks().registerListener((new Listener() { // @EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true) // public void onSpawnChange(SpawnChangeEvent evt) { // CanaryModWorld w = getWorld(evt.getWorld()); // core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w); //}, DynmapPlugin.this); break; case PLAYER_JOIN: case PLAYER_QUIT: /* Already handled */ break; case PLAYER_BED_LEAVE: Canary.hooks().registerListener(new OurBedLeaveTrigger(), DynmapPlugin.this); break; case PLAYER_CHAT: Canary.hooks().registerListener(new OurPlayerChatTrigger(), DynmapPlugin.this); break; case BLOCK_BREAK: Canary.hooks().registerListener(new OurBreakTrigger(), DynmapPlugin.this); break; case SIGN_CHANGE: Canary.hooks().registerListener(new OurSignChangeTrigger(), DynmapPlugin.this); break; default: Log.severe("Unhandled event type: " + type); return false; } registered.add(type); return true; } @Override public boolean sendWebChatEvent(String source, String name, String msg) { //DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg); //getServer().getPluginManager().callEvent(evt); //return ((evt.isCancelled() == false) && (evt.isProcessed() == false)); return true; } @Override public void broadcastMessage(String msg) { Canary.getServer().broadcastMessage(msg); } @Override public String[] getBiomeIDs() { BiomeMap[] b = BiomeMap.values(); String[] bname = new String[b.length]; for(int i = 0; i < bname.length; i++) bname[i] = b[i].toString(); return bname; } @Override public double getCacheHitRate() { return sscache.getHitRate(); } @Override public void resetCacheStats() { sscache.resetStats(); } @Override public DynmapWorld getWorldByName(String wname) { return DynmapPlugin.this.getWorldByName(wname); } @Override public DynmapPlayer getOfflinePlayer(String name) { OfflinePlayer op = Canary.getServer().getOfflinePlayer(name); if(op != null) { return new BukkitPlayer(op); } return null; } @Override public Set<String> checkPlayerPermissions(String player, Set<String> perms) { if (Canary.bans().isBanned(player)) { return Collections.emptySet(); } OfflinePlayer p = Canary.getServer().getOfflinePlayer(player); if (p == null) { return Collections.emptySet(); } Set<String> rslt = new HashSet<String>(); for (String s : perms) { if (p.hasPermission(s)) { rslt.add(s); } } return rslt; } @Override public boolean checkPlayerPermission(String player, String perm) { if (Canary.bans().isBanned(player)) { return false; } OfflinePlayer p = Canary.getServer().getOfflinePlayer(player); boolean rslt = false; if (p != null) rslt = p.hasPermission(perm); return rslt; } /** * Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread */ @Override public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks, boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) { MapChunkCache c = w.getChunkCache(chunks); if(c == null) { /* Can fail if not currently loaded */ return null; } if(w.visibility_limits != null) { for(VisibilityLimit limit: w.visibility_limits) { c.setVisibleRange(limit); } c.setHiddenFillStyle(w.hiddenchunkstyle); } if(w.hidden_limits != null) { for(VisibilityLimit limit: w.hidden_limits) { c.setHiddenRange(limit); } c.setHiddenFillStyle(w.hiddenchunkstyle); } if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false) { Log.severe("CraftBukkit build does not support biome APIs"); } if(chunks.size() == 0) { /* No chunks to get? */ c.loadChunks(0); return c; } final MapChunkCache cc = c; while(!cc.isDoneLoading()) { Future<Boolean> f = core.getServer().callSyncMethod(new Callable<Boolean>() { public Boolean call() throws Exception { boolean exhausted = true; if (prev_tick != cur_tick) { prev_tick = cur_tick; cur_tick_starttime = System.nanoTime(); } if(chunks_in_cur_tick > 0) { boolean done = false; while (!done) { int cnt = chunks_in_cur_tick; if (cnt > 5) cnt = 5; chunks_in_cur_tick -= cc.loadChunks(cnt); exhausted = (chunks_in_cur_tick == 0) || ((System.nanoTime() - cur_tick_starttime) > perTickLimit); done = exhausted || cc.isDoneLoading(); } } return exhausted; } }); if (f == null) { return null; } Boolean delay; try { delay = f.get(); } catch (CancellationException cx) { return null; } catch (ExecutionException ex) { Log.severe("Exception while fetching chunks: ", ex.getCause()); return null; } catch (Exception ix) { Log.severe(ix); return null; } if((delay != null) && delay.booleanValue()) { try { Thread.sleep(25); } catch (InterruptedException ix) {} } } /* If cancelled due to world unload return nothing */ if(w.isLoaded() == false) return null; return c; } @Override public int getMaxPlayers() { return Canary.getServer().getMaxPlayers(); } @Override public int getCurrentPlayers() { return Canary.getServer().getNumPlayersOnline(); } @Override public boolean isModLoaded(String name) { return false; } @Override public String getModVersion(String name) { return null; } @Override public double getServerTPS() { return Canary.getServer().getTicksPerSecond(); } @Override public String getServerIP() { return Configuration.getServerConfig().getBindIp(); } @Override public Map<Integer, String> getBlockIDMap() { String[] bsn = helper.getBlockShortNames(); HashMap<Integer, String> map = new HashMap<Integer, String>(); for (int i = 0; i < bsn.length; i++) { if (bsn[i] != null) { map.put(i, bsn[i]); } } return map; } @HookHandler public void tickEvent(ServerTickHook event) { cur_tick_starttime = System.nanoTime(); // Tick core if (core != null) { core.serverTick(Canary.getServer().getTicksPerSecond()); } boolean done = false; TaskRecord tr = null; long now; synchronized(schedlock) { cur_tick++; now = System.nanoTime(); tr = runqueue.peek(); /* Nothing due to run */ if((tr == null) || (tr.ticktorun > cur_tick) || ((now - cur_tick_starttime) > perTickLimit)) { done = true; } else { tr = runqueue.poll(); } } while (!done) { tr.future.run(); synchronized(schedlock) { tr = runqueue.peek(); now = System.nanoTime(); /* Nothing due to run */ if((tr == null) || (tr.ticktorun > cur_tick) || ((now - cur_tick_starttime) > perTickLimit)) { done = true; } else { tr = runqueue.poll(); } } } if (mapManager != null) { chunks_in_cur_tick = mapManager.getMaxChunkLoadsPerTick(); } } } /** * Player access abstraction class */ public class BukkitPlayer extends CanaryCommandSender implements DynmapPlayer { private PlayerReference player; public BukkitPlayer(Player p) { super(p); player = p; } public BukkitPlayer(OfflinePlayer p) { super(null); player = p; } @Override public boolean isConnected() { return player.isOnline(); } @Override public String getName() { return player.getName(); } @Override public String getDisplayName() { if (player instanceof Player) { ChatComponent dname = ((Player)player).getDisplayNameComponent(); if (dname != null) { return dname.getText(); } } return player.getName(); } @Override public boolean isOnline() { return player.isOnline(); } @Override public DynmapLocation getLocation() { if (player instanceof Player) { Location loc = ((Player)player).getLocation(); // Use eye location, since we show head if (loc != null) { return toLoc(loc); } } return null; } @Override public String getWorld() { if(player == null) { return null; } World w = player.getWorld(); if(w != null) return DynmapPlugin.this.getWorld(w).getName(); return null; } @Override public InetSocketAddress getAddress() { if (player instanceof Player) { return (InetSocketAddress) ((Player) player).getNetServerHandler().getSocketAdress(); } return null; } @Override public boolean isSneaking() { if(player instanceof Player) return ((Player)player).isSneaking(); return false; } @Override public double getHealth() { if(player != null) return player.getHealth(); else return 0; } @Override public int getArmorPoints() { if (player instanceof CanaryPlayer) { return ((CanaryPlayer)player).getHandle().bq(); } return 0; } @Override public DynmapLocation getBedSpawnLocation() { Location loc = player.getHome(); if(loc != null) { return toLoc(loc); } return null; } @Override public long getLastLoginTime() { //return player.getLastJoined(); return 0; } @Override public long getFirstLoginTime() { //return player.getFirstPlayed(); return 0; } @Override public boolean isInvisible() { if(player != null) { return ((Player)player).isHiddenFromAll(); } return false; } @Override public int getSortWeight() { Integer wt = sortWeights.get(getName()); if (wt != null) return wt; return 0; } @Override public void setSortWeight(int wt) { if (wt == 0) { sortWeights.remove(getName()); } else { sortWeights.put(getName(), wt); } } } /* Handler for generic console command sender */ public class CanaryCommandSender implements DynmapCommandSender { private MessageReceiver sender; public CanaryCommandSender(MessageReceiver send) { sender = send; } @Override public boolean hasPrivilege(String privid) { if(sender != null) return sender.hasPermission(privid); return false; } @Override public void sendMessage(String msg) { if(sender != null) sender.message(msg); } @Override public boolean isConnected() { if(sender != null) return true; return false; } @Override public boolean isOp() { if(sender != null) { return (sender.getReceiverType() == ReceiverType.SERVER) || ((sender instanceof Player) && ((Player)sender).isOperator()); } else return false; } @Override public boolean hasPermissionNode(String node) { if (sender != null) { return sender.hasPermission(node); } return false; } } public void loadExtraBiomes(String mcver) { int cnt = 0; BiomeMap.loadWellKnownByVersion(mcver); /* Find array of biomes in biomebase */ Biome[] biomelist = helper.getBiomeBaseList(); /* Loop through list, skipping well known biomes */ for(int i = 0; i < biomelist.length; i++) { Biome bb = biomelist[i]; if(bb != null) { float tmp = bb.getTemperature(); float hum = (float) ((double)bb.getRainfall() / 65536.0); BiomeMap bmap = BiomeMap.byBiomeID(i); if (bmap.isDefault()) { String id = helper.getBiomeBaseIDString(bb); if(id == null) { id = "BIOME_" + i; } BiomeMap m = new BiomeMap(i, id, tmp, hum); Log.verboseinfo("Add custom biome [" + m.toString() + "] (" + i + ")"); cnt++; } else { bmap.setTemperature(tmp); bmap.setRainfall(hum); } } } if(cnt > 0) { Log.info("Added " + cnt + " custom biome mappings"); } } private static class OurLogger implements DynmapLogger { private Logman lm; public OurLogger(Logman lm) { this.lm = lm; } @Override public void info(String msg) { lm.info(msg); } @Override public void verboseinfo(String msg) { lm.info(msg); } @Override public void severe(Throwable e) { lm.error(e.getMessage(), e); } @Override public void severe(String msg) { lm.error(msg); } @Override public void severe(String msg, Throwable e) { lm.error(msg, e); } @Override public void warning(String msg) { lm.warn(msg); } @Override public void warning(String msg, Throwable e) { lm.warn(msg, e); } } @Override public boolean enable() { Log.setLogger(new OurLogger(getLogman())); if (helper == null) { Log.info("Dynmap is disabled (unsupported platform)"); return false; } version = getVersion(); /* Get MC version */ String canaryver = Canary.getServer().getCanaryModVersion(); String mcver = canaryver.split("-")[0]; /* Load extra biomes, if any */ loadExtraBiomes(mcver); /* Set up player login/quit event handler */ registerPlayerLoginListener(); /* Get and initialize data folder */ File dataDirectory = new File(Canary.getWorkingDirectory(), "config" + File.separator + "dynmap"); if(dataDirectory.exists() == false) dataDirectory.mkdirs(); /* Instantiate core */ if(core == null) core = new DynmapCore(); /* Inject dependencies */ core.setPluginJarFile(new File(this.getPath())); core.setPluginVersion(version, "CanaryMod"); core.setMinecraftVersion(mcver); core.setDataFolder(dataDirectory); if (server == null) { server = new CanaryServer(); } core.setServer(server); core.setBlockNames(helper.getBlockShortNames()); core.setBlockMaterialMap(helper.getBlockMaterialMap()); core.setBiomeNames(helper.getBiomeNames()); /* Load configuration */ if(!core.initConfiguration(enabCoreCB)) { return false; } /* See if we need to wait before enabling core */ if(!readyToEnable()) { Canary.hooks().registerListener(new OurPluginEnabledTrigger(), this); } else { doEnable(); } // Start tps calculation perTickLimit = core.getMaxTickUseMS() * 1000000; Canary.hooks().registerListener(server, this); try { Canary.commands().registerCommands(new OurCommandHandler(), this, false); } catch (CommandDependencyException e) { Log.severe("Error registering commands", e); } return true; } private boolean readyToEnable() { return true; } private void doEnable() { /* Enable core */ if(!core.enableCore(enabCoreCB)) { pm.disablePlugin("dynmap"); return; } playerList = core.playerList; sscache = new SnapshotCache(core.getSnapShotCacheSize(), core.useSoftRefInSnapShotCache()); /* Get map manager from core */ mapManager = core.getMapManager(); /* Initialized the currently loaded worlds */ for (World world : Canary.getServer().getWorldManager().getAllWorlds()) { CanaryModWorld w = getWorld(world); if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); } /* Register our update trigger events */ registerEvents(); /* Core is ready - notify API availability */ DynmapCommonAPIListener.apiInitialized(this); Log.info("Enabled"); } @Override public void disable() { /* Core is being disabled - notify API disable */ DynmapCommonAPIListener.apiTerminated(); /* Disable core */ core.disableCore(); if(sscache != null) { sscache.cleanup(); sscache = null; } Log.info("Disabled"); } public class OurCommandHandler implements CommandListener { @Command(aliases = { "dynmap" }, description = "Dynmap commands", permissions = { "" }, toolTip = "") public void dynmapCommand(MessageReceiver sender, String[] parameters) { DynmapCommandSender dsender; if(sender instanceof Player) { dsender = new BukkitPlayer((Player)sender); } else { dsender = new CanaryCommandSender(sender); } core.processCommand(dsender, "dynmap", parameters[0], Arrays.copyOfRange(parameters, 1, parameters.length)); } @Command(aliases = { "dmarker" }, description = "Dynmap marker commands", permissions = { "" }, toolTip = "") public void dmarkerCommand(MessageReceiver sender, String[] parameters) { DynmapCommandSender dsender; if(sender instanceof Player) { dsender = new BukkitPlayer((Player)sender); } else { dsender = new CanaryCommandSender(sender); } core.processCommand(dsender, "dmarker", parameters[0], Arrays.copyOfRange(parameters, 1, parameters.length)); } @Command(aliases = { "dmap" }, description = "Dynmap map commands", permissions = { "" }, toolTip = "") public void dmapCommand(MessageReceiver sender, String[] parameters) { DynmapCommandSender dsender; if(sender instanceof Player) { dsender = new BukkitPlayer((Player)sender); } else { dsender = new CanaryCommandSender(sender); } core.processCommand(dsender, "dmap", parameters[0], Arrays.copyOfRange(parameters, 1, parameters.length)); } } @Override public final MarkerAPI getMarkerAPI() { return core.getMarkerAPI(); } @Override public final boolean markerAPIInitialized() { return core.markerAPIInitialized(); } @Override public final boolean sendBroadcastToWeb(String sender, String msg) { return core.sendBroadcastToWeb(sender, msg); } @Override public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz, int maxx, int maxy, int maxz) { return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz); } @Override public final int triggerRenderOfBlock(String wid, int x, int y, int z) { return core.triggerRenderOfBlock(wid, x, y, z); } @Override public final void setPauseFullRadiusRenders(boolean dopause) { core.setPauseFullRadiusRenders(dopause); } @Override public final boolean getPauseFullRadiusRenders() { return core.getPauseFullRadiusRenders(); } @Override public final void setPauseUpdateRenders(boolean dopause) { core.setPauseUpdateRenders(dopause); } @Override public final boolean getPauseUpdateRenders() { return core.getPauseUpdateRenders(); } @Override public final void setPlayerVisiblity(String player, boolean is_visible) { core.setPlayerVisiblity(player, is_visible); } @Override public final boolean getPlayerVisbility(String player) { return core.getPlayerVisbility(player); } @Override public final void postPlayerMessageToWeb(String playerid, String playerdisplay, String message) { core.postPlayerMessageToWeb(playerid, playerdisplay, message); } @Override public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay, boolean isjoin) { core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin); } @Override public final String getDynmapCoreVersion() { return core.getDynmapCoreVersion(); } private static DynmapLocation toLoc(Location l) { return new DynmapLocation(DynmapWorld.normalizeWorldName(l.getWorld().getFqName()), l.getBlockX(), l.getBlockY(), l.getBlockZ()); } private void registerPlayerLoginListener() { Canary.hooks().registerListener(new OurPlayerConnectionTrigger(), this); } private class BlockCheckHandler implements Runnable { public void run() { BlockToCheck btt; while(blocks_to_check.isEmpty() != true) { btt = blocks_to_check.pop(); Location loc = btt.loc; World w = loc.getWorld(); if(!w.isChunkLoaded(loc.getBlockX()>>4, loc.getBlockZ()>>4)) continue; Block b = w.getBlockAt(loc); int bt = b.getTypeId(); /* Avoid stationary and moving water churn */ if(bt == 9) bt = 8; if(btt.typeid == 9) btt.typeid = 8; if((bt != btt.typeid) || (btt.data != b.getData())) { String wn = getWorld(w).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), btt.trigger); } } blocks_to_check = null; /* Kick next run, if one is needed */ startIfNeeded(); } public void startIfNeeded() { if((blocks_to_check == null) && (blocks_to_check_accum.isEmpty() == false)) { /* More pending? */ blocks_to_check = blocks_to_check_accum; blocks_to_check_accum = new LinkedList<BlockToCheck>(); server.scheduleServerTask(this, 10); } } } private BlockCheckHandler btth = new BlockCheckHandler(); private void checkBlock(Block b, String trigger) { BlockToCheck btt = new BlockToCheck(); btt.loc = b.getLocation(); btt.typeid = b.getTypeId(); btt.data = (byte) b.getData(); btt.trigger = trigger; blocks_to_check_accum.add(btt); /* Add to accumulator */ btth.startIfNeeded(); } private boolean onplace; private boolean onbreak; private boolean onblockfromto; private boolean onblockphysics; private boolean onleaves; private boolean onburn; private boolean onpiston; private boolean onplayerjoin; private boolean onplayermove; private boolean ongeneratechunk; private boolean onexplosion; private boolean onstructuregrow; private boolean onblockgrow; private boolean onblockredstone; private boolean onblockupdate; private boolean onliquiddestroy; private void registerEvents() { // To trigger rendering. onplace = core.isTrigger("blockplaced"); onbreak = core.isTrigger("blockbreak"); onleaves = core.isTrigger("leavesdecay"); onburn = core.isTrigger("blockburn"); onblockfromto = core.isTrigger("blockfromto"); onblockphysics = core.isTrigger("blockphysics"); onpiston = core.isTrigger("pistonmoved"); onblockredstone = core.isTrigger("blockredstone"); onstructuregrow = core.isTrigger("structuregrow"); onblockupdate = core.isTrigger("blockupdate"); onliquiddestroy = core.isTrigger("liquiddestroy"); onplayermove = core.isTrigger("playermove"); onblockgrow = core.isTrigger("blockgrow"); onplayerjoin = core.isTrigger("playerjoin"); onexplosion = core.isTrigger("explosion"); ongeneratechunk = core.isTrigger("chunkgenerated"); if(onplace) { Canary.hooks().registerListener(new OurBlockPlaceTrigger(), this); } if(onbreak) { Canary.hooks().registerListener(new OurBlockBreakTrigger(), this); } if(onleaves) { Canary.hooks().registerListener(new OurLeavesDecayTrigger(), this); } if(onburn) { Canary.hooks().registerListener(new OurBlockBurnTrigger(), this); } if(onliquiddestroy) { Canary.hooks().registerListener(new OurLiquidDestroyTrigger(), this); } if(onblockphysics) { Canary.hooks().registerListener(new OurBlockPhysicsTrigger(), this); } if(onblockfromto) { Canary.hooks().registerListener(new OurBlockFromToTrigger(), this); } if(onpiston) { Canary.hooks().registerListener(new OurPistonTrigger(), this); } if(onblockgrow) { Canary.hooks().registerListener(new OurBlockGrowTrigger(), this); } if(onblockredstone) { Canary.hooks().registerListener(new OurRedstoneTrigger(), this); } /* Register player event trigger handlers */ if (onplayerjoin) { Canary.hooks().registerListener(new OurPlayerJoinTrigger(), this); } /* Register block update handler */ if (onblockupdate) { Canary.hooks().registerListener(new OurBlockUpdateTrigger(), this); } if(onplayermove) { Canary.hooks().registerListener(new OurPlayerMoveTrigger(), this); Log.warning("playermove trigger enabled - this trigger can cause excessive tile updating: use with caution"); } /* Register entity event triggers */ Canary.hooks().registerListener(new OurEntityTrigger(), this); // To link configuration to real loaded worlds. Canary.hooks().registerListener(new OurWorldTrigger(), this); if(ongeneratechunk) { Canary.hooks().registerListener(new OurChunkTrigger(), this); } } @Override public void assertPlayerInvisibility(String player, boolean is_invisible, String plugin_id) { core.assertPlayerInvisibility(player, is_invisible, plugin_id); } @Override public void assertPlayerVisibility(String player, boolean is_visible, String plugin_id) { core.assertPlayerVisibility(player, is_visible, plugin_id); } @Override public boolean setDisableChatToWebProcessing(boolean disable) { return core.setDisableChatToWebProcessing(disable); } @Override public boolean testIfPlayerVisibleToPlayer(String player, String player_to_see) { return core.testIfPlayerVisibleToPlayer(player, player_to_see); } @Override public boolean testIfPlayerInfoProtected() { return core.testIfPlayerInfoProtected(); } @Override public void processSignChange(int blkid, String world, int x, int y, int z, String[] lines, String playerid) { core.processSignChange(blkid, world, x, y, z, lines, playerid); } /* Register world event triggers */ public class OurWorldTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onWorldLoad(LoadWorldHook event) { CanaryModWorld w = getWorld(event.getWorld()); if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); } @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onWorldUnload(UnloadWorldHook event) { CanaryModWorld w = getWorld(event.getWorld()); if(w != null) { core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w); w.setWorldUnloaded(); core.processWorldUnload(w); } } @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onStructureGrow(TreeGrowHook event) { if (onstructuregrow) checkBlock(event.getSapling(), "structuregrow"); } } public class OurChunkTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onChunkPopulate(ChunkCreatedHook event) { Chunk c = event.getChunk(); int maxy = 0; int[] hmap = c.getHeightMap(); int[] hmap2 = c.getPrecipitationHeightMap(); for (int i = 0; i < hmap.length; i++) { if (hmap[i] > maxy) maxy = hmap[i]; if (hmap2[i] > maxy) maxy = hmap2[i]; } /* Touch extreme corners */ int x = c.getX() << 4; int z = c.getZ() << 4; mapManager.touchVolume(getWorld(event.getWorld()).getName(), x, 0, z, x+15, maxy, z+16, "chunkpopulate"); } } public class OurEntityTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onEntityExplode(ExplosionHook event) { Location loc = event.getBlock().getLocation(); String wname = getWorld(loc.getWorld()).getName(); int minx, maxx, miny, maxy, minz, maxz; minx = maxx = loc.getBlockX(); miny = maxy = loc.getBlockY(); minz = maxz = loc.getBlockZ(); /* Calculate volume impacted by explosion */ List<Block> blocks = event.getAffectedBlocks(); for(Block b: blocks) { Location l = b.getLocation(); int x = l.getBlockX(); if(x < minx) minx = x; if(x > maxx) maxx = x; int y = l.getBlockY(); if(y < miny) miny = y; if(y > maxy) maxy = y; int z = l.getBlockZ(); if(z < minz) minz = z; if(z > maxz) maxz = z; } sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz); if(onexplosion) { mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode"); } } } public class OurPlayerMoveTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onPlayerMove(PlayerMoveHook event) { Location loc = event.getPlayer().getLocation(); mapManager.touch(getWorld(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playermove"); } } public class OurPlayerJoinTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onPlayerJoin(ConnectionHook event) { Location loc = event.getPlayer().getLocation(); mapManager.touch(getWorld(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playerjoin"); } } public class OurRedstoneTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockRedstone(RedstoneChangeHook event) { Location loc = event.getSourceBlock().getLocation(); String wn = getWorld(loc.getWorld()).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockredstone"); } } public class OurBlockGrowTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockGrow(BlockGrowHook event) { Location loc = event.getGrowth().getLocation(); String wn = getWorld(loc.getWorld()).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockgrow"); } } public class OurPistonTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockPistonRetract(PistonRetractHook event) { Block b = event.getPiston(); Location loc = b.getLocation(); String wn = getWorld(loc.getWorld()).getName(); int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); sscache.invalidateSnapshot(wn, x, y, z); if(onpiston) mapManager.touch(wn, x, y, z, "pistonretract"); b = event.getMoving(); if (b != null) { loc = b.getLocation(); x = loc.getBlockX(); y = loc.getBlockY(); z = loc.getBlockZ(); sscache.invalidateSnapshot(wn, x, y, z); if(onpiston) mapManager.touch(wn, x, y, z, "pistonretract"); } } @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockPistonExtend(PistonExtendHook event) { Block b = event.getPiston(); Location loc = b.getLocation(); String wn = getWorld(loc.getWorld()).getName(); int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); sscache.invalidateSnapshot(wn, x, y, z); if(onpiston) mapManager.touch(wn, x, y, z, "pistonretract"); b = event.getMoving(); if (b != null) { loc = b.getLocation(); x = loc.getBlockX(); y = loc.getBlockY(); z = loc.getBlockZ(); sscache.invalidateSnapshot(wn, x, y, z); if(onpiston) mapManager.touch(wn, x, y, z, "pistonretract"); } } } public class OurBlockFromToTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockFromTo(FlowHook event) { Block b = event.getBlockFrom(); BlockType m = b.getType(); if((m != BlockType.WoodPlate) && (m != BlockType.StonePlate) && (m != null)) checkBlock(b, "blockfromto"); b = event.getBlockTo(); m = b.getType(); if((m != BlockType.WoodPlate) && (m != BlockType.StonePlate) && (m != null)) checkBlock(b, "blockfromto"); } } public class OurBlockPhysicsTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockPhysics(BlockPhysicsHook event) { Block b = event.getBlock(); BlockType m = b.getType(); if(m == null) return; if ((m == BlockType.WaterFlowing) || (m == BlockType.Water) || (m == BlockType.Lava) || (m == BlockType.LavaFlowing) || (m == BlockType.Gravel) || (m == BlockType.Sand)) { checkBlock(b, "blockphysics"); } } } public class OurBlockBurnTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockBurn(IgnitionHook event) { IgnitionCause ic = event.getCause(); if (ic == IgnitionCause.LAVA) { return; } Location loc = event.getBlock().getLocation(); String wn = getWorld(loc.getWorld()).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if(onburn) { mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn." + ic); } } } public class OurLeavesDecayTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onLeavesDecay(LeafDecayHook event) { Location loc = event.getBlock().getLocation(); String wn = getWorld(loc.getWorld()).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay"); } } public class OurBlockBreakTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockBreak(BlockDestroyHook event) { Block b = event.getBlock(); if(b == null) return; /* Stupid mod workaround */ Location loc = b.getLocation(); String wn = getWorld(loc.getWorld()).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak"); } } public class OurBlockPlaceTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onBlockPlace(BlockPlaceHook event) { Location loc = event.getBlockPlaced().getLocation(); String wn = getWorld(loc.getWorld()).getName(); sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace"); } } public class OurLiquidDestroyTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onLiquidDestroy(LiquidDestroyHook event) { checkBlock(event.getBlock(), "liquiddestroy"); } } public class OurSignChangeTrigger implements PluginListener { @HookHandler(ignoreCanceled=true,priority=Priority.PASSIVE) public void onSignChange(SignChangeHook evt) { Sign s = evt.getSign(); String[] lines = s.getText(); /* Note: changes to this change event - intentional */ DynmapPlayer dp = null; Player p = evt.getPlayer(); if(p != null) dp = new BukkitPlayer(p); core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, s.isSignPost()?63:68, getWorld(s.getWorld()).getName(), s.getX(), s.getY(), s.getZ(), lines, dp); } } public class OurBedLeaveTrigger implements PluginListener { @HookHandler(ignoreCanceled=true,priority=Priority.PASSIVE) public void onPlayerBedLeave(BedExitHook evt) { DynmapPlayer p = new BukkitPlayer(evt.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p); } } public class OurPlayerChatTrigger implements PluginListener { @HookHandler(ignoreCanceled=true,priority=Priority.PASSIVE) public void onPlayerChat(ChatHook evt) { final Player p = evt.getPlayer(); final String msg = evt.getMessage(); ServerTaskManager.addTask(new ServerTask(DynmapPlugin.this, 1) { public void run() { DynmapPlayer dp = null; if(p != null) dp = new BukkitPlayer(p); core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, dp, msg); } }); } } public class OurPluginEnabledTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onPluginEnabled(PluginEnableHook evt) { if (!readyToEnable()) { if (readyToEnable()) { /* If we;re ready now, finish enable */ doEnable(); /* Finish enable */ } } } } public class OurBreakTrigger implements PluginListener { @HookHandler(ignoreCanceled=true,priority=Priority.PASSIVE) public void onBlockBreak(BlockDestroyHook evt) { Block b = evt.getBlock(); if(b == null) return; /* Work around for stupid mods.... */ Location l = b.getLocation(); core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getType().getId(), getWorld(l.getWorld()).getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ()); } } public class OurBlockUpdateTrigger implements PluginListener { @HookHandler(ignoreCanceled=true,priority=Priority.PASSIVE) public void onBlockUpdate(BlockUpdateHook evt) { checkBlock(evt.getBlock(), "blockupdate"); } } public class OurPlayerConnectionTrigger implements PluginListener { @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onPlayerJoin(ConnectionHook evt) { final DynmapPlayer dp = new BukkitPlayer(evt.getPlayer()); // Give other handlers a change to prep player (nicknames and such from Essentials) server.scheduleServerTask(new Runnable() { @Override public void run() { core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp); } }, 2); } @HookHandler(priority=Priority.PASSIVE, ignoreCanceled=true) public void onPlayerQuit(DisconnectionHook evt) { DynmapPlayer dp = new BukkitPlayer(evt.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp); } } }
package org.expresso.impl; import java.io.IOException; import java.util.Collection; import java.util.function.Supplier; import org.expresso.Expression; import org.expresso.ExpressionType; import org.expresso.ExpressoGrammar; import org.expresso.ExpressoParser; import org.expresso.stream.BranchableStream; import org.qommons.collect.BetterSortedSet; import org.qommons.tree.BetterTreeSet; import org.qommons.tree.SortedTreeList; /** * Does the work of parsing a stream * * @param <S> The type of the stream */ public class ParseSession<S extends BranchableStream<?, ?>> { @SuppressWarnings("unused") // Not used currently, but seems like it belongs here private final ExpressoGrammar<? super S> theGrammar; private final BetterTreeSet<ExpressoParserImpl<S>> theParsers; private boolean isDebugging; private int theDebugIndent; /** @param grammar The grammer to use to parse expressions */ public ParseSession(ExpressoGrammar<? super S> grammar) { theGrammar = grammar; theParsers = new BetterTreeSet<>(false, ParseSession::compareParseStates); isDebugging = false; } /** * @param stream The stream whose content to parse * @param component The root component with which to parse the stream * @param bestError Whether to tolerate errors in the result * @return The best interpretation of the stream content * @throws IOException If an error occurs reading the stream data */ public Expression<S> parse(S stream, ExpressionType<? super S> component, boolean bestError) throws IOException { SortedTreeList<Expression<S>> toEvaluate = new SortedTreeList<>(false, Expression::compareTo); // SortedTreeList<ExpressionPossibility<S>> forks = new SortedTreeList<>(false, ExpressionPossibility::compareTo); Expression<S> init = getParser(stream, 0, bestError, new int[0]).parseWith(component); if (init != null) toEvaluate.add(init); Expression<S> bestComplete = null; Expression<S> best = null; while (!toEvaluate.isEmpty()) { Expression<S> nextBest = toEvaluate.poll(); debug(() -> "Checking " + nextBest.getType() + ": " + nextBest); boolean newBest = best == null || nextBest.compareTo(best) < 0; if (newBest) { debug(() -> "Replaced best"); best = nextBest; } if (nextBest.getErrorCount() == 0 && (bestComplete == null || nextBest.compareTo(bestComplete) < 0)) { debug(() -> "Replaced best complete"); bestComplete = nextBest; } if (newBest && isSatisfied(best, stream)) break; debug(() -> "Forking " + nextBest.getType() + ": " + nextBest); adjustDepth(1); Collection<? extends Expression<S>> pForks = nextBest.fork(); adjustDepth(-1); toEvaluate.addAll(pForks); } if (bestComplete != null) return bestComplete; else if (best == null) throw new IllegalStateException("No possibilities?!"); else if (bestError) return best; else return null; // TODO Perhaps throw an exception using the best to give specific information about what might be wrong } private static boolean isSatisfied(Expression<?> best, BranchableStream<?, ?> stream) { return stream.isFullyDiscovered() && best.length() == stream.getDiscoveredLength(); } /** * Debug operation * * @param adjust The amount by which to adjust the session depth */ public void adjustDepth(int adjust) { if (isDebugging) theDebugIndent += adjust; } /** @param debug Provides a message to print during debugging */ public void debug(Supplier<String> debug) { if (!isDebugging) return; StringBuilder str = new StringBuilder(); for (int i = 0; i < theDebugIndent; i++) str.append('\t'); str.append(debug.get()); System.out.println(str.toString()); } ExpressoParser<S> getParser(S stream, int advance, boolean tolerateError, int[] excludedTypes) throws IOException { if (!stream.hasMoreData(advance)) return null; int streamPosition = stream.getPosition() + advance; ExpressoParserImpl<S> parser = theParsers.searchValue( p -> compareParseStates(p.getStream().getPosition(), p.getExcludedTypes(), streamPosition, excludedTypes), BetterSortedSet.SortedSearchFilter.OnlyMatch); if (parser == null) { parser = new ExpressoParserImpl<>(this, (S) stream.advance(advance), tolerateError, excludedTypes, null); theParsers.add(parser); } return parser; } private static int compareParseStates(ExpressoParserImpl<?> p1, ExpressoParserImpl<?> p2) { if (p1 == p2) return 0; return compareParseStates(p1.getStream().getPosition(), p1.getExcludedTypes(), p2.getStream().getPosition(), p2.getExcludedTypes()); } private static int compareParseStates(int position1, int[] excludedTypes1, int position2, int[] excludedTypes2) { int compare = Integer.compare(position1, position2); if (compare == 0) { int i; for (i = 0; i < excludedTypes1.length && i < excludedTypes2.length; i++) { if (excludedTypes1[i] != excludedTypes2[i] || excludedTypes1[i] == -1) { compare = Integer.compare(excludedTypes1[i], excludedTypes2[i]); break; } } if (i == excludedTypes1.length) compare = 1; else if (i == excludedTypes2.length) compare = -1; } return compare; } }
package com.wizzardo.tools.json; import com.wizzardo.tools.misc.Consumer; import com.wizzardo.tools.misc.ExceptionDrivenStringBuilder; import com.wizzardo.tools.misc.Supplier; import com.wizzardo.tools.misc.UTF8; import com.wizzardo.tools.misc.pool.*; import com.wizzardo.tools.reflection.StringReflection; import java.io.OutputStream; import java.io.Writer; public class JsonTools { private static final int[] INT_VALUES = new int[128]; private static final char[] UNESCAPES = new char[128]; private static final char[] ESCAPES = new char[128]; static { for (int i = 0; i < 32; i++) { ESCAPES[i] = 128; } ESCAPES['"'] = '"'; ESCAPES['\\'] = '\\'; ESCAPES['\n'] = 'n'; ESCAPES['\r'] = 'r'; ESCAPES['\b'] = 'b'; ESCAPES['\t'] = 't'; ESCAPES['\f'] = 'f'; for (int i = 0; i < INT_VALUES.length; i++) { INT_VALUES[i] = 128; } INT_VALUES['0'] = 0; INT_VALUES['1'] = 1; INT_VALUES['2'] = 2; INT_VALUES['3'] = 3; INT_VALUES['4'] = 4; INT_VALUES['5'] = 5; INT_VALUES['6'] = 6; INT_VALUES['7'] = 7; INT_VALUES['8'] = 8; INT_VALUES['9'] = 9; INT_VALUES['a'] = 10; INT_VALUES['b'] = 11; INT_VALUES['c'] = 12; INT_VALUES['d'] = 13; INT_VALUES['e'] = 14; INT_VALUES['f'] = 15; INT_VALUES['A'] = 10; INT_VALUES['B'] = 11; INT_VALUES['C'] = 12; INT_VALUES['D'] = 13; INT_VALUES['E'] = 14; INT_VALUES['F'] = 15; UNESCAPES['"'] = '"'; UNESCAPES['\\'] = '\\'; UNESCAPES['b'] = '\b'; UNESCAPES['f'] = '\f'; UNESCAPES['n'] = '\n'; UNESCAPES['r'] = '\r'; UNESCAPES['t'] = '\t'; UNESCAPES['/'] = '/'; UNESCAPES['u'] = 128; } static Pool<ExceptionDrivenStringBuilder> builderPool = new PoolBuilder<ExceptionDrivenStringBuilder>() .supplier(new Supplier<ExceptionDrivenStringBuilder>() { @Override public ExceptionDrivenStringBuilder supply() { return new ExceptionDrivenStringBuilder(); } }).resetter(new Consumer<ExceptionDrivenStringBuilder>() { @Override public void consume(ExceptionDrivenStringBuilder sb) { sb.setLength(0); } }).build(); public static JsonItem parse(String s) { return new JsonItem(parse(s, (Generic<Object>) null)); } public static <T> T parse(String s, Class<T> clazz) { return parse(s, new Generic<T>(clazz)); } public static <T> T parse(String s, Class<T> clazz, Class... generic) { return parse(s, new Generic<T>(clazz, generic)); } public static <T> T parse(String s, Class<T> clazz, Generic... generic) { return parse(s, new Generic<T>(clazz, generic)); } public static <T> T parse(String s, Generic<T> generic) { s = s.trim(); char[] data = StringReflection.chars(s); int offset = 0; if (data.length != s.length()) offset = StringReflection.offset(s); // for java 6 return parse(data, offset, offset + s.length(), generic); } public static JsonItem parse(char[] s) { return new JsonItem(parse(s, 0, s.length, null)); } public static <T> T parse(char[] s, Class<T> clazz, Class... generic) { return parse(s, 0, s.length, new Generic<T>(clazz, generic)); } public static <T> T parse(char[] s, Class<T> clazz, Generic... generic) { return parse(s, 0, s.length, new Generic<T>(clazz, generic)); } public static <T> T parse(char[] s, int from, int to, Generic<T> generic) { // check first char if (s[from] == '{') { JsonBinder binder = Binder.getObjectBinder(generic); JsonObject.parse(s, from, to, binder); return (T) binder.getObject(); } if (s[from] == '[') { JsonBinder binder = Binder.getArrayBinder(generic); JsonArray.parse(s, from, to, binder); return (T) binder.getObject(); } return null; } /** * @return bytes array with UTF-8 json representation of the object */ public static byte[] serializeToBytes(Object src) { Holder<ExceptionDrivenStringBuilder> holder = builderPool.holder(); try { ExceptionDrivenStringBuilder builder = holder.get(); Binder.toJSON(src, Appender.create(builder)); return builder.toBytes(); } finally { holder.close(); } } public static void serialize(Object src, Supplier<byte[]> bytesSupplier, UTF8.BytesConsumer bytesConsumer) { Holder<ExceptionDrivenStringBuilder> holder = builderPool.holder(); try { ExceptionDrivenStringBuilder builder = holder.get(); Binder.toJSON(src, Appender.create(builder)); builder.toBytes(bytesSupplier, bytesConsumer); } finally { holder.close(); } } public static String serialize(Object src) { Holder<ExceptionDrivenStringBuilder> holder = builderPool.holder(); try { ExceptionDrivenStringBuilder builder = holder.get(); Appender sb = Appender.create(builder); Binder.toJSON(src, sb); return sb.toString(); } finally { holder.close(); } } public static void serialize(Object src, OutputStream out) { Appender appender = Appender.create(out); Binder.toJSON(src, appender); appender.flush(); } public static void serialize(Object src, Writer out) { Appender appender = Appender.create(out); Binder.toJSON(src, appender); appender.flush(); } public static void serialize(Object src, StringBuilder out) { Binder.toJSON(src, Appender.create(out)); } public static String unescape(char[] chars, int from, int to) { StringBuilder sb = new StringBuilder(to - from); char ch; int i = from; while (i < to) { ch = chars[i]; if (ch == '\\') { sb.append(chars, from, i - from); i++; if (to <= i) throw new IndexOutOfBoundsException("unexpected end"); ch = UNESCAPES[chars[i]]; if (ch == 0) { throw new IllegalStateException("unexpected escaped char: " + chars[i]); } else if (ch == 128) { if (to < i + 5) throw new IndexOutOfBoundsException("can't decode unicode character"); i += 4; sb.append(decodeUtf(chars, i)); } else { sb.append(ch); } from = i + 1; } i++; } if (from < to) { sb.append(chars, from, to - from); } return sb.toString(); } static String unescape(byte[] bytes, int from, int to, StringParsingContext context) { int cl = context.length; char[] chars = new char[(to - from + cl) * 4]; int i = 0; int cfrom = 0; byte ch; char chr; int offset = 0; while (i < cl) { ch = context.buffer[i]; if (ch == '\\') { offset = UTF8.decode(context.buffer, cfrom, cl - i, chars, offset); i++; if (i >= cl) throw new IndexOutOfBoundsException("unexpected end"); chr = UNESCAPES[context.buffer[i]]; if (chr == 0) { throw new IllegalStateException("unexpected escaped char: " + context.buffer[i]); } else if (chr == 128) { if (i + 5 > cl) throw new IndexOutOfBoundsException("can't decode unicode character"); i += 4; chars[offset++] = decodeUtf(context.buffer, i); } else { chars[offset++] = chr; } cfrom = i + 1; } i++; } if (cfrom < cl) { UTF8.DecodeContext decodeContext = new UTF8.DecodeContext(offset); UTF8.decode(context.buffer, cfrom, cl - cfrom, chars, decodeContext); i = from; while (i < to) { ch = bytes[i]; if (ch == '\\') { if (decodeContext != null) { offset = UTF8.decode(bytes, from, i - from, chars, decodeContext).charsDecoded(); decodeContext = null; } else offset = UTF8.decode(bytes, from, i - from, chars, offset); i++; if (i >= to) throw new IndexOutOfBoundsException("unexpected end"); chr = UNESCAPES[bytes[i]]; if (chr == 0) { throw new IllegalStateException("unexpected escaped char: " + bytes[i]); } else if (chr == 128) { if (i + 5 > to) throw new IndexOutOfBoundsException("can't decode unicode character"); i += 4; chars[offset++] = decodeUtf(bytes, i); } else { chars[offset++] = chr; } from = i + 1; } i++; } if (from < to) { if (decodeContext != null) offset = UTF8.decode(bytes, from, to - from, chars, decodeContext).charsDecoded(); else offset = UTF8.decode(bytes, from, to - from, chars, offset); } return new String(chars, 0, offset); } else { i = from; while (i < to) { ch = bytes[i]; if (ch == '\\') { offset = UTF8.decode(bytes, from, i - from, chars, offset); i++; if (i >= to) throw new IndexOutOfBoundsException("unexpected end"); chr = UNESCAPES[bytes[i]]; if (chr == 0) { throw new IllegalStateException("unexpected escaped char: " + bytes[i]); } else if (chr == 128) { if (i + 5 > to) throw new IndexOutOfBoundsException("can't decode unicode character"); i += 4; chars[offset++] = decodeUtf(bytes, i); } else { chars[offset++] = chr; } from = i + 1; } i++; } if (from < to) { offset = UTF8.decode(bytes, from, to - from, chars, offset); } return new String(chars, 0, offset); } } public static String escape(String s) { Appender sb = Appender.create(); escape(s, sb); return sb.toString(); } static void escape(String s, Appender sb) { char[] chars = StringReflection.chars(s); int to = s.length(); int offset = chars.length == to ? 0 : StringReflection.offset(s); int from = offset; to += from; int l = to - 1; for (int i = from; i < l; i += 2) { from = check(from, i, chars, sb); from = check(from, i + 1, chars, sb); //about 10% faster } if ((l + offset) % 2 == 0) from = check(from, l, chars, sb); if (from < to) append(chars, from, to, sb); } private static int check(int from, int i, char[] chars, Appender sb) { char ch = chars[i]; if (ch < 127) { if (ESCAPES[ch] != 0) { from = append(chars, from, i, sb); escapeChar(ESCAPES[ch], ch, sb); } } else if ((ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { from = append(chars, from, i, sb); appendUnicodeChar(ch, sb); } return from; } static void escape(char ch, Appender sb) { if (ch < 127) { if (ESCAPES[ch] != 0) escapeChar(ESCAPES[ch], ch, sb); else sb.append(ch); } else if ((ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) appendUnicodeChar(ch, sb); else sb.append(ch); } private static void appendUnicodeChar(char ch, Appender sb) { String ss = Integer.toHexString(ch); sb.append("\\u"); for (int k = 0; k < 4 - ss.length(); k++) { sb.append('0'); } sb.append(ss.toUpperCase()); } private static int append(char[] s, int from, int to, Appender sb) { sb.append(s, from, to); return to + 1; } private static void escapeChar(char escaped, char src, Appender sb) { if (escaped == 128) { appendUnicodeChar(src, sb); } else { sb.append('\\'); sb.append(escaped); } } static char decodeUtf(char[] chars, int last) { int value = 0; value += getHexValue(chars[last]); value += getHexValue(chars[last - 1]) * 16; value += getHexValue(chars[last - 2]) * 256; value += getHexValue(chars[last - 3]) * 4096; return (char) value; } static char decodeUtf(byte[] bytes, int last) { int value = 0; value += getHexValue(bytes[last] & 0XFF); value += getHexValue(bytes[last - 1] & 0XFF) * 16; value += getHexValue(bytes[last - 2] & 0XFF) * 256; value += getHexValue(bytes[last - 3] & 0XFF) * 4096; return (char) value; } static int getHexValue(int c) { if (c >= 128) throw new IllegalStateException("unexpected char for hex value: " + c); c = INT_VALUES[c]; if (c == 128) throw new IllegalStateException("unexpected char for hex value"); return c; } }
package org.hummingbirdlang; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.Exception; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.TruffleLanguage; import com.oracle.truffle.api.source.Source; import org.hummingbirdlang.nodes.HBSourceRootNode; import org.hummingbirdlang.parser.ParserWrapper; import org.hummingbirdlang.types.realize.InferenceVisitor; @TruffleLanguage.Registration(name = "Hummingbird", version = "0.1", mimeType = HBLanguage.MIME_TYPE) public final class HBLanguage extends TruffleLanguage<HBContext> { public static final String MIME_TYPE = "application/x-hummingbird"; public HBLanguage() { } @Override protected HBContext createContext(Env env) { BufferedReader in = new BufferedReader(new InputStreamReader(env.in())); PrintWriter out = new PrintWriter(env.out(), true); return new HBContext(env, in, out); } @Override protected CallTarget parse(ParsingRequest request) throws Exception { Source source = request.getSource(); HBSourceRootNode program = ParserWrapper.parse(this, source); System.out.println(program.toString()); InferenceVisitor visitor = new InferenceVisitor(); program.accept(visitor); return Truffle.getRuntime().createCallTarget(program); } // TODO: Fully remove this deprecated implementation.: // @Override // protected CallTarget parse(Source source, Node node, String... argumentNames) throws Exception { // Object program = ParserWrapper.parse(source); // System.out.println(program.toString()); // return null; // Called when some other language is seeking for a global symbol. @Override protected Object findExportedSymbol(HBContext context, String globalName, boolean onlyExplicit) { return null; } @Override protected Object getLanguageGlobal(HBContext context) { // Context is the highest level global. return context; } @Override protected boolean isObjectOfLanguage(Object object) { return false; } }
package org.lantern; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.security.auth.login.CredentialException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Presence.Type; import org.jivesoftware.smackx.packet.VCard; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.lastbamboo.common.p2p.P2PConnectionEvent; import org.lastbamboo.common.p2p.P2PConnectionListener; import org.lastbamboo.common.p2p.P2PConstants; import org.lastbamboo.common.portmapping.NatPmpService; import org.lastbamboo.common.portmapping.PortMapListener; import org.lastbamboo.common.portmapping.PortMappingProtocol; import org.lastbamboo.common.portmapping.UpnpService; import org.lastbamboo.common.stun.client.StunServerRepository; import org.littleshoot.commom.xmpp.XmppP2PClient; import org.littleshoot.commom.xmpp.XmppUtils; import org.littleshoot.p2p.P2P; import org.littleshoot.util.SessionSocketListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import com.hoodcomputing.natpmp.NatPmpException; /** * Handles logging in to the XMPP server and processing trusted users through * the roster. */ public class DefaultXmppHandler implements XmppHandler { private static final Logger LOG = LoggerFactory.getLogger(DefaultXmppHandler.class); /** * These are the centralized proxies this Lantern instance is using. */ private final Set<ProxyHolder> proxySet = new HashSet<ProxyHolder>(); private final Queue<ProxyHolder> proxies = new ConcurrentLinkedQueue<ProxyHolder>(); /** * This is the set of all peer proxies we know about. We may have * established connections with some of them. The main purpose of this is * to avoid exchanging keys multiple times. */ private final Set<URI> peerProxySet = new HashSet<URI>(); private final Set<ProxyHolder> laeProxySet = new HashSet<ProxyHolder>(); private final Queue<ProxyHolder> laeProxies = new ConcurrentLinkedQueue<ProxyHolder>(); private final AtomicReference<XmppP2PClient> client = new AtomicReference<XmppP2PClient>(); static { SmackConfiguration.setPacketReplyTimeout(30 * 1000); } private final Timer updateTimer = LanternHub.timer(); private volatile long lastInfoMessageScheduled = 0L; private final MessageListener typedListener = new MessageListener() { @Override public void processMessage(final Chat ch, final Message msg) { // Note the Chat will always be null here. We try to avoid using // actual Chat instances due to Smack's strange and inconsistent // behavior with message listeners on chats. final String part = msg.getFrom(); LOG.info("Got chat participant: {} with message:\n {}", part, msg.toXML()); if (StringUtils.isNotBlank(part) && part.startsWith(LanternConstants.LANTERN_JID)) { processLanternHubMessage(msg); } final Integer type = (Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE); if (type != null) { LOG.info("Not processing typed message"); processTypedMessage(msg, type); } } }; private String lastJson = ""; private String hubAddress; private final org.lantern.Roster roster = new org.lantern.Roster(this); private GoogleTalkState state; private String lastUserName; private String lastPass; private final NatPmpService natPmpService; private final UpnpService upnpService = new Upnp(); private ClosedBetaEvent closedBetaEvent; private final Object closedBetaLock = new Object(); /** * Creates a new XMPP handler. */ public DefaultXmppHandler() { // This just links connectivity with Google Talk login status when // running in give mode. NatPmpService temp = null; try { temp = new NatPmp(); } catch (final NatPmpException e) { // This will happen when NAT-PMP is not supported on the local // network. LOG.info("Could not map", e); // We just use a dummy one in this case. temp = new NatPmpService() { @Override public void removeNatPmpMapping(int arg0) { } @Override public int addNatPmpMapping( final PortMappingProtocol arg0, int arg1, int arg2, PortMapListener arg3) { return -1; } @Override public void shutdown() { } }; } natPmpService = temp; new GiveModeConnectivityHandler(); LanternUtils.configureXmpp(); prepopulateProxies(); LanternHub.register(this); //setupJmx(); } @Subscribe public void onAuthStatus(final GoogleTalkStateEvent ase) { this.state = ase.getState(); switch (state) { case LOGGED_IN: // We wait until we're logged in before creating our roster. this.roster.loggedIn(); //LanternHub.asyncEventBus().post(new SyncEvent()); synchronized (this.rosterLock) { this.rosterLock.notifyAll(); } break; case LOGGED_OUT: this.roster.reset(); break; case LOGGING_IN: break; case LOGGING_OUT: break; case LOGIN_FAILED: this.roster.reset(); break; } } private void prepopulateProxies() { // Add all the stored proxies. final Collection<String> saved = LanternHub.settings().getProxies(); LOG.info("Proxy set is: {}", saved); for (final String proxy : saved) { // Don't use peer proxies since we're not connected to XMPP yet. if (!proxy.contains("@")) { LOG.info("Adding prepopulated proxy: {}", proxy); addProxy(proxy); } } } @Override public void connect() throws IOException, CredentialException, NotInClosedBetaException { if (!LanternUtils.isConfigured() && LanternHub.settings().isUiEnabled()) { LOG.info("Not connecting when not configured"); return; } LOG.info("Connecting to XMPP servers..."); String email = LanternHub.settings().getEmail(); String pwd = LanternHub.settings().getPassword(); if (StringUtils.isBlank(email)) { if (!LanternHub.settings().isUiEnabled()) { email = askForEmail(); pwd = askForPassword(); LanternHub.settings().setEmail(email); LanternHub.settings().setPassword(pwd); } else { LOG.error("No user name"); throw new IllegalStateException("No user name"); } LanternHub.settingsIo().write(); } if (StringUtils.isBlank(pwd)) { if (!LanternHub.settings().isUiEnabled()) { pwd = askForPassword(); LanternHub.settings().setPassword(pwd); } else { LOG.error("No password."); throw new IllegalStateException("No password"); } LanternHub.settingsIo().write(); } connect(email, pwd); } @Override public void connect(final String email, final String pwd) throws IOException, CredentialException, NotInClosedBetaException { LOG.debug("Connecting to XMPP servers with user name and password..."); this.lastUserName = email; this.lastPass = pwd; this.closedBetaEvent = null; final InetSocketAddress plainTextProxyRelayAddress = new InetSocketAddress("127.0.0.1", LanternUtils.PLAINTEXT_LOCALHOST_PROXY_PORT); final SessionSocketListener sessionListener = new SessionSocketListener() { @Override public void reconnected() { // We need to send a new presence message each time we // reconnect to the XMPP server, as otherwise peers won't // know we're available and we won't get data from the bot. updatePresence(); } @Override public void onSocket(String arg0, Socket arg1) throws IOException { } }; this.client.set(P2P.newXmppP2PHttpClient("shoot", natPmpService, upnpService, new InetSocketAddress(LanternHub.settings().getServerPort()), LanternUtils.newTlsSocketFactory(), LanternUtils.newTlsServerSocketFactory(), //SocketFactory.getDefault(), ServerSocketFactory.getDefault(), plainTextProxyRelayAddress, sessionListener, false)); this.client.get().addConnectionListener(new P2PConnectionListener() { @Override public void onConnectivityEvent(final P2PConnectionEvent event) { LOG.info("Got connectivity event: {}", event); LanternHub.asyncEventBus().post(event); } }); // This is a global, backup listener added to the client. We might // get notifications of messages twice in some cases, but that's // better than the alternative of sometimes not being notified // at all. LOG.info("Adding message listener..."); this.client.get().addMessageListener(typedListener); if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.CONNECTING); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGING_IN)); final String id; if (LanternHub.settings().isGetMode()) { LOG.info("Setting ID for get mode..."); id = "gmail."; } else { LOG.info("Setting ID for give mode"); id = LanternConstants.UNCENSORED_ID; } try { this.client.get().login(email, pwd, id); LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGED_IN)); } catch (final IOException e) { if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.DISCONNECTED); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGIN_FAILED)); LanternHub.settings().setPasswordSaved(false); LanternHub.settings().setStoredPassword(""); LanternHub.settings().setPassword(""); throw e; } catch (final CredentialException e) { if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.DISCONNECTED); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGIN_FAILED)); throw e; } // Note we don't consider ourselves connected in get mode until we // actually get proxies to work with. final XMPPConnection connection = this.client.get().getXmppConnection(); final Collection<String> servers = LanternHub.settings().getStunServers(); if (servers.isEmpty()) { final Collection<InetSocketAddress> googleStunServers = XmppUtils.googleStunServers(connection); StunServerRepository.setStunServers(googleStunServers); LanternHub.settings().setStunServers( new HashSet<String>(toStringServers(googleStunServers))); } // Make sure all connections between us and the server are stored // OTR. LanternUtils.activateOtr(connection); LOG.info("Connection ID: {}", connection.getConnectionID()); // Here we handle allowing the server to subscribe to our presence. connection.addPacketListener(new PacketListener() { @Override public void processPacket(final Packet pack) { final Presence pres = (Presence) pack; LOG.debug("Processing packet!! {}", pres); final String from = pres.getFrom(); LOG.debug("Responding to presence from {} and to {}", from, pack.getTo()); final Type type = pres.getType(); // Allow subscription requests from the lantern bot. if (from.startsWith("lanternctrl@") && from.endsWith("lanternctrl.appspotchat.com")) { if (type == Type.subscribe) { final Presence packet = new Presence(Presence.Type.subscribed); packet.setTo(from); packet.setFrom(pack.getTo()); connection.sendPacket(packet); } else { LOG.info("Non-subscribe packet from hub? {}", pres.toXML()); } } else { switch (type) { case available: return; case error: LOG.warn("Got error packet!! {}", pack.toXML()); return; case subscribe: LOG.info("Adding subscription request from: {}", from); // If we get a subscription request from someone // already on our roster, auto-accept it. if (roster.autoAcceptSubscription(from)) { subscribed(from); } roster.addIncomingSubscriptionRequest(from); break; case subscribed: break; case unavailable: return; case unsubscribe: LOG.info("Removing subscription request from: {}",from); roster.removeIncomingSubscriptionRequest(from); return; case unsubscribed: break; } } } }, new PacketFilter() { @Override public boolean accept(final Packet packet) { if(packet instanceof Presence) { return true; } else { LOG.debug("Not a presence packet: {}", packet.toXML()); } return false; } }); gTalkSharedStatus(); updatePresence(); if (LanternUtils.isInClosedBeta(email)) { LOG.debug("Already in closed beta..."); return; } synchronized (this.closedBetaLock) { if (this.closedBetaEvent == null) { try { this.closedBetaLock.wait(60 * 1000); } catch (final InterruptedException e) { LOG.info("Interrupted? Maybe on shutdown?", e); } } } if (this.closedBetaEvent != null) { if(!this.closedBetaEvent.isInClosedBeta()) { LOG.debug("Not in closed beta..."); notInClosedBeta("Not in closed beta"); } else { LOG.info("Server notified us we're in the closed beta!"); } } else { LOG.warn("No closed beta event -- timed out!!"); notInClosedBeta("No closed beta event!!"); } } private void notInClosedBeta(final String msg) throws NotInClosedBetaException { //connectivityEvent(ConnectivityStatus.DISCONNECTED); disconnect(); throw new NotInClosedBetaException(msg); } private Set<String> toStringServers( final Collection<InetSocketAddress> googleStunServers) { final Set<String> strings = new HashSet<String>(); for (final InetSocketAddress isa : googleStunServers) { strings.add(isa.getHostName()+":"+isa.getPort()); } return strings; } private void connectivityEvent(final ConnectivityStatus cs) { if (LanternHub.settings().isGetMode()) { LanternHub.eventBus().post( new ConnectivityStatusChangeEvent(cs)); } else { LOG.info("Ignoring connectivity event in give mode.."); } } @Override public void clearProxies() { this.proxies.clear(); this.proxySet.clear(); this.peerProxySet.clear(); this.laeProxySet.clear(); this.laeProxies.clear(); } @Override public void disconnect() { LOG.info("Disconnecting!!"); lastJson = ""; LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGING_OUT)); final XmppP2PClient cl = this.client.get(); if (cl != null) { this.client.get().logout(); this.client.set(null); } if (this.proxies.isEmpty()) { connectivityEvent(ConnectivityStatus.DISCONNECTED); } LanternHub.eventBus().post( new GoogleTalkStateEvent(GoogleTalkState.LOGGED_OUT)); peerProxySet.clear(); this.closedBetaEvent = null; } private void processLanternHubMessage(final Message msg) { LOG.debug("Lantern controlling agent response"); this.hubAddress = msg.getFrom(); final String to = XmppUtils.jidToUser(msg.getTo()); LOG.debug("Set hub address to: {}", hubAddress); final String body = msg.getBody(); LOG.debug("Body: {}", body); final Object obj = JSONValue.parse(body); final JSONObject json = (JSONObject) obj; final Boolean inClosedBeta = (Boolean) json.get(LanternConstants.INVITED); if (inClosedBeta != null) { LanternHub.asyncEventBus().post(new ClosedBetaEvent(to, inClosedBeta)); if (!inClosedBeta) { //return; } } else { LanternHub.asyncEventBus().post(new ClosedBetaEvent(to, false)); //return; } final JSONArray servers = (JSONArray) json.get(LanternConstants.SERVERS); final Long delay = (Long) json.get(LanternConstants.UPDATE_TIME); LOG.debug("Server sent delay of: "+delay); if (delay != null) { final long now = System.currentTimeMillis(); final long elapsed = now - lastInfoMessageScheduled; if (elapsed > 10000 && delay != 0L) { lastInfoMessageScheduled = now; updateTimer.schedule(new TimerTask() { @Override public void run() { updatePresence(); } }, delay); LOG.debug("Scheduled next info request in {} milliseconds", delay); } else { LOG.debug("Ignoring duplicate info request scheduling- "+ "scheduled request {} milliseconds ago.", elapsed); } } if (servers == null) { LOG.debug("No servers in message"); } else { final Iterator<String> iter = servers.iterator(); while (iter.hasNext()) { final String server = iter.next(); addProxy(server); } } // This is really a JSONObject, but that itself is a map. final JSONObject update = (JSONObject) json.get(LanternConstants.UPDATE_KEY); if (update != null) { LOG.info("About to propagate update..."); LanternHub.display().asyncExec (new Runnable () { @Override public void run () { final Map<String, Object> event = new HashMap<String, Object>(); event.putAll(update); LanternHub.asyncEventBus().post(new UpdateEvent(event)); } }); } final Long invites = (Long) json.get(LanternConstants.INVITES_KEY); if (invites != null) { LOG.info("Setting invites to: {}", invites); LanternHub.settings().setInvites(invites.intValue()); } } @Subscribe public void onClosedBetaEvent(final ClosedBetaEvent cbe) { LOG.debug("Got closed beta event!!"); this.closedBetaEvent = cbe; if (this.closedBetaEvent.isInClosedBeta()) { LanternUtils.addToClosedBeta(cbe.getTo()); } synchronized (this.closedBetaLock) { // We have to make sure that this event is actually intended for // the user we're currently logged in as! final String to = this.closedBetaEvent.getTo(); LOG.debug("Analyzing closed beta event for: {}", to); if (isLoggedIn()) { final String user = LanternUtils.toEmail( this.client.get().getXmppConnection()); if (user.equals(to)) { LOG.debug("Users match!"); this.closedBetaLock.notifyAll(); } else { LOG.debug("Users don't match {}, {}", user, to); } } } } private void gTalkSharedStatus() { // This is for Google Talk compatibility. Surprising, all we need to // do is grab our Google Talk shared status, signifying support for // their protocol, and then we don't interfere with GChat visibility. final Packet status = XmppUtils.getSharedStatus( this.client.get().getXmppConnection()); LOG.info("Status:\n{}", status.toXML()); } private String askForEmail() { try { System.out.print("Please enter your gmail e-mail, as in johndoe@gmail.com: "); return LanternUtils.readLineCLI(); } catch (final IOException e) { final String msg = "IO error trying to read your email address!"; System.out.println(msg); LOG.error(msg, e); throw new IllegalStateException(msg, e); } } private String askForPassword() { try { System.out.print("Please enter your gmail password: "); return new String(LanternUtils.readPasswordCLI()); } catch (IOException e) { final String msg = "IO error trying to read your email address!"; System.out.println(msg); LOG.error(msg, e); throw new IllegalStateException(msg, e); } } /** * Updates the user's presence. We also include any stats updates in this * message. Note that periodic presence updates are also used on the server * side to verify which clients are actually available. * * We in part send presence updates instead of typical chat messages to * get around these messages showing up in the user's gchat window. */ private void updatePresence() { if (!isLoggedIn()) { LOG.info("Not updating presence when we're not connected"); return; } final XMPPConnection conn = this.client.get().getXmppConnection(); LOG.info("Sending presence available"); // OK, this is bizarre. For whatever reason, we **have** to send the // following packet in order to get presence events from our peers. // DO NOT REMOVE THIS MESSAGE!! See XMPP spec. final Presence pres = new Presence(Presence.Type.available); conn.sendPacket(pres); final Presence forHub = new Presence(Presence.Type.available); forHub.setTo(LanternConstants.LANTERN_JID); //if (!LanternHub.settings().isGetMode()) { final String str = LanternUtils.jsonify(LanternHub.statsTracker()); LOG.debug("Reporting data: {}", str); if (!this.lastJson.equals(str)) { this.lastJson = str; forHub.setProperty("stats", str); LanternHub.statsTracker().resetCumulativeStats(); } else { LOG.info("No new stats to report"); } //} else { // LOG.info("Not reporting any stats in get mode"); conn.sendPacket(forHub); } /* private void sendInfoRequest() { // Send an "info" message to gather proxy data. LOG.info("Sending INFO request"); final Message msg = new Message(); msg.setType(Type.chat); //msg.setType(Type.normal); msg.setTo(LanternConstants.LANTERN_JID); msg.setFrom(this.client.getXmppConnection().getUser()); final JSONObject json = new JSONObject(); final StatsTracker statsTracker = LanternHub.statsTracker(); json.put(LanternConstants.COUNTRY_CODE, CensoredUtils.countryCode()); json.put(LanternConstants.BYTES_PROXIED, statsTracker.getTotalBytesProxied()); json.put(LanternConstants.DIRECT_BYTES, statsTracker.getDirectBytes()); json.put(LanternConstants.REQUESTS_PROXIED, statsTracker.getTotalProxiedRequests()); json.put(LanternConstants.DIRECT_REQUESTS, statsTracker.getDirectRequests()); json.put(LanternConstants.WHITELIST_ADDITIONS, LanternUtils.toJsonArray(Whitelist.getAdditions())); json.put(LanternConstants.WHITELIST_REMOVALS, LanternUtils.toJsonArray(Whitelist.getRemovals())); json.put(LanternConstants.VERSION_KEY, LanternConstants.VERSION); final String str = json.toJSONString(); LOG.info("Reporting data: {}", str); msg.setBody(str); this.client.getXmppConnection().sendPacket(msg); Whitelist.whitelistReported(); //statsTracker.clear(); } */ @Override public void addOrRemovePeer(final Presence p, final String from) { LOG.info("Processing peer: {}", from); final URI uri; try { uri = new URI(from); } catch (final URISyntaxException e) { LOG.error("Could not create URI from: {}", from); return; } if (p.isAvailable()) { LOG.info("Processing available peer"); // OK, we just request a certificate every time we get a present // peer. If we get a response, this peer will be added to active // peer URIs. sendAndRequestCert(uri); } else { LOG.info("Removing JID for peer '"+from); removePeer(uri); } } private void sendErrorMessage(final InetSocketAddress isa, final String message) { final Message msg = new Message(); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.ERROR_TYPE); final String errorMessage = "Error: "+message+" with host: "+isa; msg.setProperty(XmppMessageConstants.MESSAGE, errorMessage); if (isLoggedIn()) { final XMPPConnection conn = this.client.get().getXmppConnection(); conn.sendPacket(msg); } } private void processTypedMessage(final Message msg, final Integer type) { final String from = msg.getFrom(); LOG.info("Processing typed message from {}", from); switch (type) { case (XmppMessageConstants.INFO_REQUEST_TYPE): LOG.info("Handling INFO request from {}", from); processInfoData(msg); sendInfoResponse(from); break; case (XmppMessageConstants.INFO_RESPONSE_TYPE): LOG.info("Handling INFO response from {}", from); processInfoData(msg); break; default: LOG.warn("Did not understand type: "+type); break; } } private void sendInfoResponse(final String from) { final Message msg = new Message(); // The from becomes the to when we're responding. msg.setTo(from); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.INFO_RESPONSE_TYPE); msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress()); msg.setProperty(P2PConstants.CERT, LanternHub.getKeyStoreManager().getBase64Cert()); this.client.get().getXmppConnection().sendPacket(msg); } private void processInfoData(final Message msg) { LOG.info("Processing INFO data from request or response."); final URI uri; try { uri = new URI(msg.getFrom()); } catch (final URISyntaxException e) { LOG.error("Could not create URI from: {}", msg.getFrom()); return; } final String mac = (String) msg.getProperty(P2PConstants.MAC); final String base64Cert = (String) msg.getProperty(P2PConstants.CERT); LOG.info("Base 64 cert: {}", base64Cert); if (StringUtils.isNotBlank(base64Cert)) { LOG.info("Got certificate:\n"+ new String(Base64.decodeBase64(base64Cert))); try { // Add the peer if we're able to add the cert. LanternHub.getKeyStoreManager().addBase64Cert(mac, base64Cert); if (LanternHub.settings().isAutoConnectToPeers()) { final String email = XmppUtils.jidToUser(msg.getFrom()); if (this.roster.isFullyOnRoster(email)) { LanternHub.trustedPeerProxyManager().onPeer(uri); } else { LanternHub.anonymousPeerProxyManager().onPeer(uri); } /* if (LanternHub.getTrustedContactsManager().isTrusted(msg)) { LanternHub.trustedPeerProxyManager().onPeer(uri); } else { LanternHub.anonymousPeerProxyManager().onPeer(uri); } */ } } catch (final IOException e) { LOG.error("Could not add cert??", e); } } else { LOG.error("No cert for peer?"); } } private void addProxy(final String cur) { LOG.info("Considering proxy: {}", cur); if (cur.contains("appspot")) { addLaeProxy(cur); return; } if (!cur.contains("@")) { addGeneralProxy(cur); return; } if (!isLoggedIn()) { LOG.info("Not connected -- ignoring proxy: {}", cur); return; } final String jid = this.client.get().getXmppConnection().getUser().trim(); final String emailId = XmppUtils.jidToUser(jid); LOG.info("We are: {}", jid); LOG.info("Service name: {}", this.client.get().getXmppConnection().getServiceName()); if (jid.equals(cur.trim())) { LOG.info("Not adding ourselves as a proxy!!"); return; } if (cur.startsWith(emailId+"/")) { try { addPeerProxy(new URI(cur)); } catch (final URISyntaxException e) { LOG.error("Error with proxy URI", e); } } else if (cur.contains("@")) { try { addPeerProxy(new URI(cur)); } catch (final URISyntaxException e) { LOG.error("Error with proxy URI", e); } } } private void addPeerProxy(final URI peerUri) { LOG.info("Considering peer proxy"); synchronized (peerProxySet) { // We purely do this to keep track of which peers we've attempted // to establish connections to. This is to avoid exchanging certs // multiple times. // TODO: I believe this excludes exchanging keys with peers who // are on multiple machines when the peer URI is a general JID and // not an instance JID. if (!peerProxySet.contains(peerUri)) { LOG.info("Actually adding peer proxy: {}", peerUri); peerProxySet.add(peerUri); sendAndRequestCert(peerUri); } else { LOG.info("We already know about the peer proxy"); } } } private void sendAndRequestCert(final URI cur) { LOG.info("Requesting cert from {}", cur); final Message msg = new Message(); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.INFO_REQUEST_TYPE); msg.setTo(cur.toASCIIString()); // Set our certificate in the request as well -- we want to make // extra sure these get through! msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress()); msg.setProperty(P2PConstants.CERT, LanternHub.getKeyStoreManager().getBase64Cert()); this.client.get().getXmppConnection().sendPacket(msg); } private void addLaeProxy(final String cur) { LOG.info("Adding LAE proxy"); addProxyWithChecks(this.laeProxySet, this.laeProxies, new ProxyHolder(cur, new InetSocketAddress(cur, 443)), cur); } private void addGeneralProxy(final String cur) { final String hostname = StringUtils.substringBefore(cur, ":"); final int port = Integer.parseInt(StringUtils.substringAfter(cur, ":")); final InetSocketAddress isa = new InetSocketAddress(hostname, port); addProxyWithChecks(proxySet, proxies, new ProxyHolder(hostname, isa), cur); } private void addProxyWithChecks(final Set<ProxyHolder> set, final Queue<ProxyHolder> queue, final ProxyHolder ph, final String fullProxyString) { if (set.contains(ph)) { LOG.info("We already know about proxy "+ph+" in {}", set); // Send the event again in case we've somehow gotten into the // wrong state. LOG.info("Dispatching CONNECTED event"); connectivityEvent(ConnectivityStatus.CONNECTED); return; } final Socket sock = new Socket(); try { sock.connect(ph.isa, 60*1000); LOG.info("Dispatching CONNECTED event"); connectivityEvent(ConnectivityStatus.CONNECTED); // This is a little odd because the proxy could have originally // come from the settings themselves, but it'll remove duplicates, // so no harm done. LanternHub.settings().addProxy(fullProxyString); synchronized (set) { if (!set.contains(ph)) { set.add(ph); queue.add(ph); LOG.info("Queue is now: {}", queue); } } } catch (final IOException e) { LOG.error("Could not connect to: {}", ph); sendErrorMessage(ph.isa, e.getMessage()); onCouldNotConnect(ph.isa); LanternHub.settings().removeProxy(fullProxyString); } finally { IOUtils.closeQuietly(sock); } } @Override public void onCouldNotConnect(final InetSocketAddress proxyAddress) { // This can happen in several scenarios. First, it can happen if you've // actually disconnected from the internet. Second, it can happen if // the proxy is blocked. Third, it can happen when the proxy is simply // down for some reason. LOG.info("COULD NOT CONNECT TO STANDARD PROXY!! Proxy address: {}", proxyAddress); // For now we assume this is because we've lost our connection. //onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress), // this.proxySet, this.proxies); } @Override public void onCouldNotConnectToLae(final InetSocketAddress proxyAddress) { LOG.info("COULD NOT CONNECT TO LAE PROXY!! Proxy address: {}", proxyAddress); // For now we assume this is because we've lost our connection. //onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress), // this.laeProxySet, this.laeProxies); } private void onCouldNotConnect(final ProxyHolder proxyAddress, final Set<ProxyHolder> set, final Queue<ProxyHolder> queue){ LOG.info("COULD NOT CONNECT!! Proxy address: {}", proxyAddress); synchronized (this.proxySet) { set.remove(proxyAddress); queue.remove(proxyAddress); } } @Override public void onCouldNotConnectToPeer(final URI peerUri) { removePeer(peerUri); } @Override public void onError(final URI peerUri) { removePeer(peerUri); } private void removePeer(final URI uri) { // We always remove from both since their trusted status could have // changed removePeerUri(uri); removeAnonymousPeerUri(uri); //if (LanternHub.getTrustedContactsManager().isJidTrusted(uri.toASCIIString())) { LanternHub.trustedPeerProxyManager().removePeer(uri); //} else { // LanternHub.anonymousPeerProxyManager().removePeer(uri); } private void removePeerUri(final URI peerUri) { LOG.info("Removing peer with URI: {}", peerUri); //remove(peerUri, this.establishedPeerProxies); } private void removeAnonymousPeerUri(final URI peerUri) { LOG.info("Removing anonymous peer with URI: {}", peerUri); //remove(peerUri, this.establishedAnonymousProxies); } private void remove(final URI peerUri, final Queue<URI> queue) { LOG.info("Removing peer with URI: {}", peerUri); queue.remove(peerUri); } @Override public InetSocketAddress getLaeProxy() { return getProxy(this.laeProxies); } @Override public InetSocketAddress getProxy() { return getProxy(this.proxies); } @Override public PeerProxyManager getAnonymousPeerProxyManager() { return LanternHub.anonymousPeerProxyManager(); } @Override public PeerProxyManager getTrustedPeerProxyManager() { return LanternHub.trustedPeerProxyManager(); } private InetSocketAddress getProxy(final Queue<ProxyHolder> queue) { synchronized (queue) { if (queue.isEmpty()) { LOG.info("No proxy addresses"); return null; } final ProxyHolder proxy = queue.remove(); queue.add(proxy); LOG.info("FIFO queue is now: {}", queue); return proxy.isa; } } @Override public XmppP2PClient getP2PClient() { return client.get(); } private static final class ProxyHolder { private final String id; private final InetSocketAddress isa; private ProxyHolder(final String id, final InetSocketAddress isa) { this.id = id; this.isa = isa; } @Override public String toString() { return "ProxyHolder [isa=" + isa + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isa == null) ? 0 : isa.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProxyHolder other = (ProxyHolder) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (isa == null) { if (other.isa != null) return false; } else if (!isa.equals(other.isa)) return false; return true; } } @Override public boolean isLoggedIn() { if (this.client.get() == null) { return false; } final XMPPConnection conn = client.get().getXmppConnection(); if (conn == null) { return false; } return conn.isAuthenticated(); } @Override public void sendInvite(final String email) { LOG.info("Sending invite"); if (StringUtils.isBlank(this.hubAddress)) { LOG.error("Blank hub address when sending invite?"); return; } final Set<String> invited = LanternHub.settings().getInvited(); if (invited.contains(email)) { LOG.info("Already invited"); return; } final XMPPConnection conn = this.client.get().getXmppConnection(); final Roster rost = conn.getRoster(); final Presence pres = new Presence(Presence.Type.available); pres.setTo(LanternConstants.LANTERN_JID); // "emails" of the form xxx@public.talk.google.com aren't really // e-mail addresses at all, so don't send 'em. // In theory we might be able to use the Google Plus API to get // actual e-mail addresses -- see: if (email.contains("public.talk.google.com")) { pres.setProperty(LanternConstants.INVITED_EMAIL, ""); } else { pres.setProperty(LanternConstants.INVITED_EMAIL, email); } final RosterEntry entry = rost.getEntry(email); if (entry != null) { final String name = entry.getName(); if (StringUtils.isNotBlank(name)) { pres.setProperty(LanternConstants.INVITEE_NAME, name); } } try { final VCard vcard = PhotoServlet.getVCard(LanternUtils.toEmail(conn)); if (vcard != null) { final String fullName = vcard.getField("FN"); if (StringUtils.isNotBlank(fullName)) { pres.setProperty(LanternConstants.INVITER_NAME, fullName); } else { pres.setProperty(LanternConstants.INVITER_NAME, ""); } } } catch (final CredentialException e) { LOG.warn("Bad credentials?", e); } catch (final XMPPException e) { LOG.warn("XMPP Error?", e); } catch (final IOException e) { LOG.warn("IO Error?", e); } invited.add(email); //pres.setProperty(LanternConstants.INVITER_NAME, value); final Runnable runner = new Runnable() { @Override public void run() { conn.sendPacket(pres); } }; final Thread t = new Thread(runner, "Invite-Thread"); t.setDaemon(true); t.start(); LanternHub.settings().setInvites(LanternHub.settings().getInvites()-1); LanternHub.settingsIo().write(); addToRoster(email); } @Override public void subscribe(final String jid) { LOG.info("Sending subscribe message to: {}", jid); sendTypedPacket(jid, Presence.Type.subscribe); } @Override public void subscribed(final String jid) { LOG.info("Sending subscribe message to: {}", jid); sendTypedPacket(jid, Presence.Type.subscribed); roster.removeIncomingSubscriptionRequest(jid); } @Override public void unsubscribe(final String jid) { LOG.info("Sending unsubscribe message to: {}", jid); sendTypedPacket(jid, Presence.Type.unsubscribe); } @Override public void unsubscribed(final String jid) { LOG.info("Sending unsubscribed message to: {}", jid); sendTypedPacket(jid, Presence.Type.unsubscribed); roster.removeIncomingSubscriptionRequest(jid); } private void sendTypedPacket(final String jid, final Type type) { final Presence packet = new Presence(type); packet.setTo(jid); final XMPPConnection conn = this.client.get().getXmppConnection(); //packet.setFrom(XmppUtils.jidToUser(conn)); //packet.setFrom(conn.getUser()); conn.sendPacket(packet); } @Override public void addToRoster(final String email) { // If the user is not already on our roster, we want to make sure to // send them an invite. If the e-mail address specified does not // correspond with a Jabber ID, then we're out of luck. If it does, // then this will send the roster invite. final XMPPConnection conn = this.client.get().getXmppConnection(); final Roster rost = conn.getRoster(); final RosterEntry entry = rost.getEntry(email); if (entry == null) { LOG.info("Inviting user to join roster: {}", email); try { // Note this also sends a subscription request!! rost.createEntry(email, StringUtils.substringBefore(email, "@"), new String[]{}); } catch (final XMPPException e) { LOG.error("Could not create entry?", e); } } } @Override public void removeFromRoster(final String email) { final XMPPConnection conn = this.client.get().getXmppConnection(); final Roster rost = conn.getRoster(); final RosterEntry entry = rost.getEntry(email); if (entry != null) { LOG.info("Removing user from roster: {}", email); try { rost.removeEntry(entry); } catch (final XMPPException e) { LOG.error("Could not create entry?", e); } } } private final Object rosterLock = new Object(); /** * This is primarily here because the frontend can request the roster * before we have it. We block until the roster comes in. */ private void waitForRoster() { synchronized (rosterLock) { while(!this.roster.populated()) { try { rosterLock.wait(40000); } catch (final InterruptedException e) { } } } } @Override public org.lantern.Roster getRoster() { if (this.roster == null) { waitForRoster(); } return this.roster; } @Override public void resetRoster() { this.roster.reset();; } @Override public String getLastUserName() { return lastUserName; } @Override public String getLastPass() { return lastPass; } private void setupJmx() { final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { final Class<? extends Object> clazz = getClass(); final String pack = clazz.getPackage().getName(); final String oName = pack+":type="+clazz.getSimpleName()+"-"+clazz.getSimpleName(); LOG.info("Registering MBean with name: {}", oName); final ObjectName mxBeanName = new ObjectName(oName); if(!mbs.isRegistered(mxBeanName)) { mbs.registerMBean(this, mxBeanName); } } catch (final MalformedObjectNameException e) { LOG.error("Could not set up JMX", e); } catch (final InstanceAlreadyExistsException e) { LOG.error("Could not set up JMX", e); } catch (final MBeanRegistrationException e) { LOG.error("Could not set up JMX", e); } catch (final NotCompliantMBeanException e) { LOG.error("Could not set up JMX", e); } } @Override public void stop() { LOG.info("Stopping XMPP handler..."); disconnect(); if (upnpService != null) { upnpService.shutdown(); } if (natPmpService != null) { natPmpService.shutdown(); } LOG.info("Finished stoppeding XMPP handler..."); } }
package com.haulmont.cuba.web.gui.data; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaPropertyPath; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.View; import com.haulmont.cuba.gui.data.*; import com.haulmont.cuba.gui.data.impl.CollectionDsHelper; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.*; public class CollectionDsWrapper implements Container, Container.ItemSetChangeNotifier { protected boolean autoRefresh; protected boolean ignoreListeners; protected CollectionDatasource datasource; protected Collection<MetaPropertyPath> properties = new ArrayList<MetaPropertyPath>(); private List<ItemSetChangeListener> itemSetChangeListeners = new ArrayList<ItemSetChangeListener>(); // private PersistenceManagerService persistenceManager; private static Log log = LogFactory.getLog(CollectionDsWrapper.class); protected DsManager dsManager; private static final long serialVersionUID = 1440434590495905389L; public CollectionDsWrapper(CollectionDatasource datasource, DsManager dsManager) { this(datasource, false, dsManager); } public CollectionDsWrapper(CollectionDatasource datasource, Collection<MetaPropertyPath> properties, DsManager dsManager) { this(datasource, properties, false, dsManager); } public CollectionDsWrapper(CollectionDatasource datasource, boolean autoRefresh, DsManager dsManager) { this(datasource, null, autoRefresh, dsManager); } public CollectionDsWrapper( CollectionDatasource datasource, Collection<MetaPropertyPath> properties, boolean autoRefresh, DsManager dsManager ) { this.datasource = datasource; this.dsManager = dsManager; this.autoRefresh = autoRefresh; // this.persistenceManager = ServiceLocator.lookup(PersistenceManagerService.NAME); final View view = datasource.getView(); final MetaClass metaClass = datasource.getMetaClass(); if (properties == null) { createProperties(view, metaClass); } else { this.properties.addAll(properties); } dsManager.addListener(createDatasourceListener()); } protected DatasourceListener createDatasourceListener() { if (datasource instanceof CollectionDatasource.Lazy) return new LazyDataSourceRefreshListener(); else return new DataSourceRefreshListener(); } protected void createProperties(View view, MetaClass metaClass) { properties.addAll(CollectionDsHelper.createProperties(view, metaClass)); } protected void fireItemSetChanged() { if (ignoreListeners) return; ignoreListeners = true; for (ItemSetChangeListener listener : itemSetChangeListeners) { listener.containerItemSetChange(new ItemSetChangeEvent() { public Container getContainer() { return CollectionDsWrapper.this; } }); } } public Item getItem(Object itemId) { CollectionDsHelper.autoRefreshInvalid(datasource, autoRefresh); final Object item = datasource.getItem(itemId); return item == null ? null : getItemWrapper(item); } protected Map<Object, ItemWrapper> itemsCache = new HashMap<Object, ItemWrapper>(); protected synchronized Item getItemWrapper(Object item) { ItemWrapper wrapper = itemsCache.get(item); if (wrapper == null) { wrapper = createItemWrapper(item); itemsCache.put(item, wrapper); } return wrapper; } protected ItemWrapper createItemWrapper(Object item) { return new ItemWrapper(item, properties, dsManager); } public Collection getContainerPropertyIds() { return properties; } public synchronized Collection getItemIds() { CollectionDsHelper.autoRefreshInvalid(datasource, autoRefresh); return datasource.getItemIds(); } public Property getContainerProperty(Object itemId, Object propertyId) { final Item item = getItem(itemId); return item == null ? null : item.getItemProperty(propertyId); } public Class getType(Object propertyId) { MetaPropertyPath propertyPath = (MetaPropertyPath) propertyId; return propertyPath.getRangeJavaClass(); } public synchronized int size() { CollectionDsHelper.autoRefreshInvalid(datasource, autoRefresh); return datasource.size(); } public synchronized boolean containsId(Object itemId) { CollectionDsHelper.autoRefreshInvalid(datasource, autoRefresh); return datasource.containsItem(itemId); } public Item addItem(Object itemId) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public Object addItem() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public boolean removeItem(Object itemId) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { return this.properties.remove(propertyId); } public boolean removeAllItems() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public void addListener(ItemSetChangeListener listener) { this.itemSetChangeListeners.add(listener); } public void removeListener(ItemSetChangeListener listener) { this.itemSetChangeListeners.remove(listener); } protected void checkMaxFetchUI(CollectionDatasource ds) { // String entityName = ds.getMetaClass().getName(); // if (ds.size() >= persistenceManager.getMaxFetchUI(entityName)) { // log.debug("MaxFetchUI threshold exceeded for " + entityName); // String msg = MessageProvider.getMessage(AppConfig.getInstance().getMessagesPack(), "maxFetchUIExceeded"); // App app = App.getInstance(); // app.getAppLog().debug(entityName + ": " + msg); // app.getWindowManager().showNotification(msg, IFrame.NotificationType.HUMANIZED); } protected class DataSourceRefreshListener implements CollectionDatasourceListener<Entity> { public void itemChanged(Datasource ds, Entity prevItem, Entity item) {} public void stateChanged(Datasource<Entity> ds, Datasource.State prevState, Datasource.State state) { final boolean prevIgnoreListeners = ignoreListeners; try { itemsCache.clear(); fireItemSetChanged(); } finally { ignoreListeners = prevIgnoreListeners; } } public void valueChanged(Entity source, String property, Object prevValue, Object value) { Item wrapper = getItemWrapper(source); // MetaProperty worked wrong with properties from inherited superclasses MetaPropertyPath metaPropertyPath = datasource.getMetaClass().getPropertyPath(property); if (metaPropertyPath == null) { return; } Property itemProperty = wrapper.getItemProperty(metaPropertyPath); if (itemProperty instanceof PropertyWrapper) { ((PropertyWrapper) itemProperty).fireValueChangeEvent(); } } public void collectionChanged(CollectionDatasource ds, Operation operation) { final boolean prevIgnoreListeners = ignoreListeners; try { itemsCache.clear(); fireItemSetChanged(); if (!(ds instanceof CollectionDatasource.Lazy)) { checkMaxFetchUI(ds); } } finally { ignoreListeners = prevIgnoreListeners; } } } protected class LazyDataSourceRefreshListener extends DataSourceRefreshListener implements LazyCollectionDatasourceListener<Entity> { public void completelyLoaded(CollectionDatasource.Lazy ds) { checkMaxFetchUI(ds); } } @Override public String toString() { return "{ds=" + (datasource == null ? "null" : datasource.getId() + "}"); } }
package org.lantern; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.SocketFactory; import org.apache.commons.lang.StringUtils; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.util.Base64; /** * {@link SocketFactory} for creating sockets through an HTTP proxy. */ public class ProxySocketFactory extends SocketFactory { private final ProxyInfo proxy; public ProxySocketFactory(final ProxyInfo proxy) { this.proxy = proxy; } @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return httpConnectSocket(host, port); } @Override public Socket createSocket(final String host, final int port, final InetAddress localHost, final int localPort) throws IOException, UnknownHostException { return httpConnectSocket(host, port); } @Override public Socket createSocket(final InetAddress host, final int port) throws IOException { return httpConnectSocket(host.getHostAddress(), port); } @Override public Socket createSocket(final InetAddress address, final int port, final InetAddress localAddress, final int localPort) throws IOException { return httpConnectSocket(address.getHostAddress(), port); } private Socket httpConnectSocket(final String host, final int port) throws IOException { final String proxyHost = proxy.getProxyAddress(); final int proxyPort = proxy.getProxyPort(); final Socket sock = new Socket(); sock.connect(new InetSocketAddress(proxyHost, proxyPort), 50 * 1000); final String url = "CONNECT " + host + ":" + port; String proxyLine; final String user = proxy.getProxyUsername(); if (StringUtils.isBlank(user)) { proxyLine = ""; } else { final String password = proxy.getProxyPassword(); proxyLine = "\r\nProxy-Authorization: Basic " + new String(Base64.encodeBytes((user + ":" + password) .getBytes("UTF-8"))); } sock.getOutputStream().write( (url + " HTTP/1.1\r\nHost: " + url + proxyLine + "\r\n\r\n").getBytes("UTF-8")); final InputStream in = sock.getInputStream(); final StringBuilder got = new StringBuilder(100); int nlchars = 0; while (true) { final int c = in.read(); got.append(c); if (got.length() > 4096) { throw new ProxyException(ProxyInfo.ProxyType.HTTP, "Recieved " + "header of "+got.length()+" characters from " + proxyHost + ", cancelling connection:\n"+got.toString()); } if (c == -1) { throw new ProxyException(ProxyInfo.ProxyType.HTTP); } if ((nlchars == 0 || nlchars == 2) && c == '\r') { nlchars++; } else if ((nlchars == 1 || nlchars == 3) && c == '\n') { nlchars++; } else { nlchars = 0; } if (nlchars == 4) { break; } } if (nlchars != 4) { throw new ProxyException(ProxyInfo.ProxyType.HTTP, "Never " + "received blank line from " + proxyHost + ", cancelling connection"); } final String gotstr = got.toString(); final BufferedReader br = new BufferedReader(new StringReader(gotstr)); final String response = br.readLine(); if (response == null) { throw new ProxyException(ProxyInfo.ProxyType.HTTP, "Empty proxy " + "response from " + proxyHost + ", cancelling"); } final Matcher m = RESPONSE_PATTERN.matcher(response); if (!m.matches()) { throw new ProxyException(ProxyInfo.ProxyType.HTTP, "Unexpected " + "proxy response from " + proxyHost + ": " + response); } final int code = Integer.parseInt(m.group(1)); if (code != HttpURLConnection.HTTP_OK) { throw new ProxyException(ProxyInfo.ProxyType.HTTP); } return sock; } private static final Pattern RESPONSE_PATTERN = Pattern.compile("HTTP/\\S+\\s(\\d+)\\s(.*)\\s*"); }
package org.lightmare.ejb; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManagerFactory; import org.lightmare.cache.ConnectionData; import org.lightmare.cache.ConnectionSemaphore; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.MetaData; import org.lightmare.config.Configuration; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.ejb.handlers.BeanLocalHandler; import org.lightmare.jpa.JPAManager; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Connector class for get ejb beans or call remote procedure in ejb bean (RPC) * by interface class * * @author Levan * */ public class EjbConnector { private static final int RPC_ARGS_LENGTH = 2; /** * Gets {@link MetaData} from {@link MetaContainer} and waits while * {@link MetaData#isInProgress()} * * @param beanName * @return {@link MetaData} * @throws IOException */ private MetaData getMeta(String beanName) throws IOException { MetaData metaData = MetaContainer.getSyncMetaData(beanName); return metaData; } /** * Gets connection for {@link Stateless} bean {@link Class} from cache * * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ private void getEntityManagerFactory(ConnectionData connection) throws IOException { if (connection.getEmf() == null) { String unitName = connection.getUnitName(); if (ObjectUtils.available(unitName)) { ConnectionSemaphore semaphore = JPAManager .getConnection(unitName); connection.setConnection(semaphore); } } } /** * Gets connections for {@link Stateless} bean {@link Class} from cache * * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ private void getEntityManagerFactories(MetaData metaData) throws IOException { Collection<ConnectionData> connections = metaData.getConnections(); if (ObjectUtils.available(connections)) { for (ConnectionData connection : connections) { getEntityManagerFactory(connection); } } } /** * Instantiates bean by class * * @param metaData * @return Bean instance * @throws IOException */ private <T> T getBeanInstance(MetaData metaData) throws IOException { @SuppressWarnings("unchecked") Class<? extends T> beanClass = (Class<? extends T>) metaData .getBeanClass(); T beanInstance = MetaUtils.instantiate(beanClass); return beanInstance; } /** * Creates {@link InvocationHandler} implementation for server mode * * @param metaData * @return {@link InvocationHandler} * @throws IOException */ public <T> InvocationHandler getHandler(MetaData metaData) throws IOException { T beanInstance = getBeanInstance(metaData); getEntityManagerFactories(metaData); BeanHandler handler = new BeanHandler(metaData, beanInstance); handler.configure(); return handler; } /** * Instantiates bean with {@link Proxy} utility * * @param interfaces * @param handler * @return <code>T</code> implementation of bean interface */ private <T> T instatiateBean(Class<T>[] interfaces, InvocationHandler handler, ClassLoader loader) { if (loader == null) { loader = LibraryLoader.getContextClassLoader(); } @SuppressWarnings("unchecked") T beanInstance = (T) Proxy .newProxyInstance(loader, interfaces, handler); return beanInstance; } /** * Instantiates bean with {@link Proxy} utility * * @param interfaceClass * @param handler * @return <code>T</code> implementation of bean interface */ private <T> T instatiateBean(Class<T> interfaceClass, InvocationHandler handler, ClassLoader loader) { Class<?>[] interfaceArray = { interfaceClass }; if (loader == null) { loader = LibraryLoader.getContextClassLoader(); } @SuppressWarnings("unchecked") T beanInstance = (T) Proxy.newProxyInstance(loader, interfaceArray, handler); return beanInstance; } private Class<?>[] setInterfaces(MetaData metaData) { Class<?>[] interfaceClasses = metaData.getInterfaceClasses(); if (ObjectUtils.notAvailable(interfaceClasses)) { List<Class<?>> interfacesList = new ArrayList<Class<?>>(); Class<?>[] interfaces = metaData.getLocalInterfaces(); if (ObjectUtils.available(interfaces)) { interfacesList.addAll(Arrays.asList(interfaces)); } interfaces = metaData.getRemoteInterfaces(); if (ObjectUtils.available(interfaces)) { interfacesList.addAll(Arrays.asList(interfaces)); } int size = interfacesList.size(); interfaceClasses = interfacesList.toArray(new Class[size]); } return interfaceClasses; } /** * * @param metaData * @param rpcArgs * @return <code>T</code> implementation of bean interface * @throws IOException */ @SuppressWarnings("unchecked") public <T> T connectToBean(MetaData metaData, Object... rpcArgs) throws IOException { InvocationHandler handler = getHandler(metaData); Class<?>[] interfaces = setInterfaces(metaData); ClassLoader loader = metaData.getLoader(); T beanInstance = (T) instatiateBean((Class<T>[]) interfaces, handler, loader); return beanInstance; } /** * Creates custom implementation of bean {@link Class} by class name and its * proxy interface {@link Class} instance * * @param interfaceClass * @return <code>T</code> implementation of bean interface * @throws IOException */ public <T> T connectToBean(String beanName, Class<T> interfaceClass, Object... rpcArgs) throws IOException { InvocationHandler handler; Configuration configuration = MetaContainer.CONFIG; ClassLoader loader; if (configuration.isServer()) { MetaData metaData = getMeta(beanName); setInterfaces(metaData); handler = getHandler(metaData); loader = metaData.getLoader(); } else { if (rpcArgs.length != RPC_ARGS_LENGTH) { throw new IOException( "Could not resolve host and port arguments"); } String host = (String) rpcArgs[0]; int port = (Integer) rpcArgs[1]; handler = new BeanLocalHandler(new RPCall(host, port)); loader = null; } T beanInstance = (T) instatiateBean(interfaceClass, handler, loader); return beanInstance; } /** * Creates custom implementation of bean {@link Class} by class name and its * proxy interface name * * @param beanName * @param interfaceName * @param rpcArgs * @return <code>T</code> implementation of bean interface * @throws IOException */ public <T> T connectToBean(String beanName, String interfaceName, Object... rpcArgs) throws IOException { MetaData metaData = getMeta(beanName); ClassLoader loader = metaData.getLoader(); @SuppressWarnings("unchecked") Class<T> interfaceClass = (Class<T>) MetaUtils.classForName( interfaceName, Boolean.FALSE, loader); T beanInstance = (T) connectToBean(beanName, interfaceClass); return beanInstance; } }
package org.mahjong4j.hands; import org.mahjong4j.IllegalMentsuSizeException; import org.mahjong4j.Mahjong4jException; import java.util.ArrayList; import java.util.List; /** * * * @author yu1ro */ public class MentsuComp { private List<Toitsu> toitsuList = new ArrayList<>(7); private List<Shuntsu> shuntsuList = new ArrayList<>(4); private List<Kotsu> kotsuList = new ArrayList<>(4); private List<Kantsu> kantsuList = new ArrayList<>(4); public MentsuComp(List<MahjongMentsu> mentsuList) throws Mahjong4jException { for (MahjongMentsu mentsu : mentsuList) { setMentsu(mentsu); } int checkSum = shuntsuList.size() + kotsuList.size() + kantsuList.size(); boolean isNormal = checkSum == 4 && toitsuList.size() == 1; boolean isChitoitsu = toitsuList.size() == 7 && checkSum == 0; if (!isNormal && !isChitoitsu) { throw new IllegalMentsuSizeException(mentsuList); } } /** * * * @param mentsu */ private void setMentsu(MahjongMentsu mentsu) { if (mentsu instanceof Toitsu) { toitsuList.add((Toitsu) mentsu); } else if (mentsu instanceof Shuntsu) { shuntsuList.add((Shuntsu) mentsu); } else if (mentsu instanceof Kotsu) { kotsuList.add((Kotsu) mentsu); } else if (mentsu instanceof Kantsu) { kantsuList.add((Kantsu) mentsu); } } /** * null * * @return */ public Toitsu getJanto() { if (getToitsuCount() == 1) { return toitsuList.get(0); } return null; } public List<Toitsu> getToitsuList() { return toitsuList; } /** * * 17 * * @return 1 7 */ public int getToitsuCount() { return toitsuList.size(); } public List<Shuntsu> getShuntsuList() { return shuntsuList; } /** * * 0~4 * * @return */ public int getShuntsuCount() { return shuntsuList.size(); } public List<Kotsu> getKotsuList() { return kotsuList; } /** * * 0~4 * * @return */ public int getKotsuCount() { return kotsuList.size(); } public List<Kantsu> getKantsuList() { return kantsuList; } /** * * 0~4 * * @return */ public int getKantsuCount() { return kantsuList.size(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MentsuComp)) return false; MentsuComp that = (MentsuComp) o; if (toitsuList != null ? !toitsuList.equals(that.toitsuList) : that.toitsuList != null) return false; if (shuntsuList != null ? !shuntsuList.equals(that.shuntsuList) : that.shuntsuList != null) return false; if (kotsuList != null ? !kotsuList.equals(that.kotsuList) : that.kotsuList != null) return false; return !(kantsuList != null ? !kantsuList.equals(that.kantsuList) : that.kantsuList != null); } @Override public int hashCode() { int result = toitsuList != null ? toitsuList.hashCode() : 0; result = 31 * result + (shuntsuList != null ? shuntsuList.hashCode() : 0); result = 31 * result + (kotsuList != null ? kotsuList.hashCode() : 0); result = 31 * result + (kantsuList != null ? kantsuList.hashCode() : 0); return result; } }
package org.mitre.synthea.engine; import com.google.gson.Gson; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.math.ode.DerivativeException; import org.mitre.synthea.engine.Components.Exact; import org.mitre.synthea.engine.Components.ExactWithUnit; import org.mitre.synthea.engine.Components.Range; import org.mitre.synthea.engine.Components.RangeWithUnit; import org.mitre.synthea.engine.Transition.ComplexTransition; import org.mitre.synthea.engine.Transition.ComplexTransitionOption; import org.mitre.synthea.engine.Transition.ConditionalTransition; import org.mitre.synthea.engine.Transition.ConditionalTransitionOption; import org.mitre.synthea.engine.Transition.DirectTransition; import org.mitre.synthea.engine.Transition.DistributedTransition; import org.mitre.synthea.engine.Transition.DistributedTransitionOption; import org.mitre.synthea.engine.Transition.LookupTableTransition; import org.mitre.synthea.engine.Transition.LookupTableTransitionOption; import org.mitre.synthea.helpers.ConstantValueGenerator; import org.mitre.synthea.helpers.ExpressionProcessor; import org.mitre.synthea.helpers.RandomValueGenerator; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.helpers.physiology.IoMapper; import org.mitre.synthea.modules.EncounterModule; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.agents.Provider; import org.mitre.synthea.world.concepts.ClinicianSpecialty; import org.mitre.synthea.world.concepts.HealthRecord; import org.mitre.synthea.world.concepts.HealthRecord.CarePlan; import org.mitre.synthea.world.concepts.HealthRecord.Code; import org.mitre.synthea.world.concepts.HealthRecord.EncounterType; import org.mitre.synthea.world.concepts.HealthRecord.Entry; import org.mitre.synthea.world.concepts.HealthRecord.Medication; import org.mitre.synthea.world.concepts.HealthRecord.Report; import org.simulator.math.odes.MultiTable; public abstract class State implements Cloneable { public Module module; public String name; public Long entered; public Entry entry; public Long exited; private Transition transition; // note that these are not Transition objects, because they are JSON lists private String directTransition; // or in this case just a String private List<ConditionalTransitionOption> conditionalTransition; private List<DistributedTransitionOption> distributedTransition; private List<ComplexTransitionOption> complexTransition; private List<LookupTableTransitionOption> lookupTableTransition; public List<String> remarks; protected void initialize(Module module, String name, JsonObject definition) { this.module = module; this.name = name; if (directTransition != null) { this.transition = new DirectTransition(directTransition); } else if (distributedTransition != null) { this.transition = new DistributedTransition(distributedTransition); } else if (conditionalTransition != null) { this.transition = new ConditionalTransition(conditionalTransition); } else if (complexTransition != null) { this.transition = new ComplexTransition(complexTransition); } else if (lookupTableTransition != null) { this.transition = new LookupTableTransition(lookupTableTransition); } else if (!(this instanceof Terminal)) { throw new RuntimeException("State `" + name + "` has no transition.\n"); } } /** * Construct a state object from the given definitions. * * @param module * The module this state belongs to * @param name * The name of the state * @param definition * The JSON definition of the state * @return The constructed State object. The returned object will be of the appropriate subclass * of State, based on the "type" parameter in the JSON definition. * @throws Exception * if the state type does not exist */ public static State build(Module module, String name, JsonObject definition) throws Exception { String className = State.class.getName() + "$" + definition.get("type").getAsString(); Class<?> stateClass = Class.forName(className); Gson gson = Utilities.getGson(); State state = (State) gson.fromJson(definition, stateClass); state.initialize(module, name, definition); return state; } /** * clone() should copy all the necessary variables of this State so that it can be correctly * executed and modified without altering the original copy. So for example, 'entered' and * 'exited' times should not be copied so the clone can be cleanly executed. */ public State clone() { try { State clone = (State) super.clone(); clone.module = this.module; clone.name = this.name; clone.transition = this.transition; clone.remarks = this.remarks; return clone; } catch (CloneNotSupportedException e) { // should not happen, and not something we can handle throw new RuntimeException(e); } } public String transition(Person person, long time) { return transition.follow(person, time); } public Transition getTransition() { return transition; } /** * Process this State with the given Person at the specified time within the simulation. * If this State generates a HealthRecord.Entry during processing, then the resulting data * will reside in the State.entry field. * * @param person * : the person being simulated * @param time * : the date within the simulated world * @return `true` if processing should continue to the next state, `false` if the processing * should halt for this time step. */ public abstract boolean process(Person person, long time); /** * Run the state. This processes the state, setting entered and exit times. * * @param person * the person being simulated * @param time * the date within the simulated world * @return `true` if processing should continue to the next state, `false` if the processing * should halt for this time step. */ public boolean run(Person person, long time) { // System.out.format("State: %s\n", this.name); if (!person.alive(time)) { return false; } if (this.entered == null) { this.entered = time; } boolean exit = process(person, time); if (exit) { // Delay state returns a special value for exited, // to indicate when the delay actually completed. if (this instanceof Delay) { this.exited = ((Delay)this).next; } else { this.exited = time; } } return exit; } public String toString() { return this.getClass().getSimpleName() + " '" + name + "'"; } /** * The Initial state type is the first state that is processed in a generic module. It does not * provide any specific function except to indicate the starting point, so it has no properties * except its type. The Initial state requires the specific name "Initial". In addition, it is the * only state for which there can only be one in the whole module. */ public static class Initial extends State { @Override public boolean process(Person person, long time) { return true; } } /** * The Simple state type indicates a state that performs no additional actions, adds no additional * information to the patient entity, and just transitions to the next state. As an example, this * state may be used to chain conditional or distributed transitions, in order to represent * complex logic. */ public static class Simple extends State { @Override public boolean process(Person person, long time) { return true; } } /** * The CallSubmodule state immediately processes a reusable series of states contained in a * submodule. These states are processes in the same time step, starting with the submodule's * Initial state. Once the submodule's Terminal state is reached, execution of the calling module * resumes. */ public static class CallSubmodule extends State { private String submodule; @Override public CallSubmodule clone() { CallSubmodule clone = (CallSubmodule) super.clone(); clone.submodule = submodule; return clone; } @Override public boolean process(Person person, long time) { // e.g. "submodule": "medications/otc_antihistamine" List<State> moduleHistory = person.history; Module submod = Module.getModuleByPath(submodule); HealthRecord.Encounter encounter = person.getCurrentEncounter(module); if (encounter != null) { person.setCurrentEncounter(submod, encounter); } boolean completed = submod.process(person, time); if (completed) { // add the history from the submodule to this module's history, at the front moduleHistory.addAll(0, person.history); // clear the submodule history person.attributes.remove(submod.name); // reset person.history to this module's history person.history = moduleHistory; // add this state to history to indicate we returned to this module person.history.add(0, this); // start using the current encounter, it may have changed encounter = person.getCurrentEncounter(submod); if (encounter != null) { person.setCurrentEncounter(module, encounter); } return true; } else { // reset person.history to this module's history person.history = moduleHistory; // the submodule is still processing // next time we call this state it should pick up where it left off return false; } } } /** * The Physiology state executes a physiology simulation according to the provided * configuration options. Expressions can be used to map Patient attributes / * VitalSigns to model parameters, and vice versa, or they can be mapped directly. * This is an alternative way to get simulation results applicable for a specific * module. If a simulation is intended to provide VitalSign values, a physiology * value generator should be used instead. */ public static class Physiology extends State { private String model; private String solver; private double stepSize; private double simDuration; private double leadTime; private List<IoMapper> inputs; private List<IoMapper> outputs; private transient PhysiologySimulator simulator; private transient Map<String,String> paramTypes; @Override protected void initialize(Module module, String name, JsonObject definition) { super.initialize(module, name, definition); if (leadTime > simDuration) { throw new IllegalArgumentException( "Simulation lead time cannot be greater than sim duration!"); } setup(); } private void setup() { simulator = new PhysiologySimulator(model, solver, stepSize, simDuration); paramTypes = new HashMap<String, String>(); for (String param : simulator.getParameters()) { // Assume all physiology model inputs are lists of Decimal objects which is typically // the case // TODO: Look into whether SBML supports other parameter types, and if so, how we might map // those types to CQL types paramTypes.put(param, "List<Decimal>"); } for (IoMapper mapper : inputs) { mapper.initialize(paramTypes); } for (IoMapper mapper : outputs) { mapper.initialize(paramTypes); } } @Override public Physiology clone() { super.clone(); Physiology clone = (Physiology) super.clone(); clone.model = model; clone.solver = solver; clone.stepSize = stepSize; clone.simDuration = simDuration; clone.leadTime = leadTime; List<IoMapper> inputList = new ArrayList<IoMapper>(inputs.size()); for (IoMapper mapper : inputs) { inputList.add(new IoMapper(mapper)); } clone.inputs = inputList; List<IoMapper> outputList = new ArrayList<IoMapper>(outputs.size()); for (IoMapper mapper : outputs) { outputList.add(new IoMapper(mapper)); } clone.outputs = outputList; clone.setup(); return clone; } @Override public boolean process(Person person, long time) { Map<String,Double> modelInputs = new HashMap<String,Double>(); for (IoMapper mapper : inputs) { mapper.toModelInputs(person, time, modelInputs); } try { MultiTable results = simulator.run(modelInputs); for (IoMapper mapper : outputs) { switch (mapper.getType()) { default: case ATTRIBUTE: person.attributes.put(mapper.getTo(), mapper.getOutputResult(results, leadTime)); break; case VITAL_SIGN: throw new IllegalArgumentException( "Mapping to VitalSigns is unsupported in the Physiology State. " + "Define a physiology generator instead for \"" + mapper.getTo() + "\"."); } } } catch (DerivativeException ex) { Logger.getLogger(State.class.getName()).log(Level.SEVERE, "Unable to solve simulation \"" + model + "\" at time step " + time + " for person " + person.attributes.get(Person.ID), ex); } return true; } } /** * The Terminal state type indicates the end of the module progression. Once a Terminal state is * reached, no further progress will be made. As such, Terminal states cannot have any transition * properties. If desired, there may be multiple Terminal states with different names to indicate * different ending points; however, this has no actual effect on the records that are produced. */ public static class Terminal extends State { @Override public boolean process(Person person, long time) { return false; } } /** * The Delay state type introduces a pre-configured temporal delay in the module's timeline. As a * simple example, a Delay state may indicate a one-month gap in time between an initial encounter * and a followup encounter. The module will not pass through the Delay state until the proper * amount of time has passed. The Delay state may define an exact time to delay (e.g. 4 days) or a * range of time to delay (e.g. 5 - 7 days). * * <p>Implementation Details Synthea generation occurs in time steps; the default time step is 7 * days. This means that if a module is processed on a given date, the next time it is processed * will be exactly 7 days later. If a delay expiration falls between time steps (e.g. day 3 of a * 7-day time step), then the first time step after the delay expiration will effectively rewind * the clock to the delay expiration time and process states using that time. Once it reaches a * state that it can't pass through, it will process it once more using the original (7-day time * step) time. */ public static class Delay extends State { // next is "transient" in the sense that it represents object state // as opposed to the other fields which represent object definition // hence it is not set in clone() public Long next; private RangeWithUnit<Long> range; private ExactWithUnit<Long> exact; @Override public Delay clone() { Delay clone = (Delay) super.clone(); clone.exact = exact; clone.range = range; return clone; } @Override public boolean process(Person person, long time) { if (this.next == null) { if (exact != null) { // use an exact quantity this.next = time + Utilities.convertTime(exact.unit, exact.quantity); } else if (range != null) { // use a range this.next = time + Utilities.convertTime(range.unit, (long) person.rand(range.low, range.high)); } else { throw new RuntimeException("Delay state has no exact or range: " + this); } } return ((time >= this.next) && person.alive(this.next)); } } /** * The Guard state type indicates a point in the module through which a patient can only pass if * they meet certain logical conditions. For example, a Guard may block a workflow until the * patient reaches a certain age, after which the Guard allows the module to continue to progress. * Depending on the condition(s), a patient may be blocked by a Guard until they die - in which * case they never reach the module's Terminal state. * * <p>The Guard state's allow property provides the logical condition(s) which must be met to * allow the module to continue to the next state. Guard states are similar to conditional * transitions in some ways, but also have an important difference. A conditional transition * tests conditions once and uses the result to immediately choose the next state. A Guard * state will test the same condition on every time-step until the condition passes, at which * point it progresses to the next state. */ public static class Guard extends State { private Logic allow; @Override public Guard clone() { Guard clone = (Guard) super.clone(); clone.allow = allow; return clone; } @Override public boolean process(Person person, long time) { boolean exit = allow.test(person, time); if (exit) { this.exited = time; } return exit; } } /** * The SetAttribute state type sets a specified attribute on the patient entity. In addition to * the assign_to_attribute property on MedicationOrder/ConditionOnset/etc states, this state * allows for arbitrary text or values to be set on an attribute, or for the attribute to be * reset. */ public static class SetAttribute extends State { private String attribute; private Object value; private String expression; private transient ThreadLocal<ExpressionProcessor> threadExpProcessor; @Override protected void initialize(Module module, String name, JsonObject definition) { super.initialize(module, name, definition); // If the ThreadLocal instance hasn't been created yet, create it now if (threadExpProcessor == null) { threadExpProcessor = new ThreadLocal<ExpressionProcessor>(); } // If there's an expression, create the processor for it if (this.expression != null && threadExpProcessor.get() == null) { threadExpProcessor.set(new ExpressionProcessor(this.expression)); } // special handling for integers if (value instanceof Double) { double doubleVal = (double)value; if (doubleVal == Math.rint(doubleVal)) { value = (int) doubleVal; } } } @Override public SetAttribute clone() { SetAttribute clone = (SetAttribute) super.clone(); clone.attribute = attribute; clone.value = value; clone.expression = expression; clone.threadExpProcessor = threadExpProcessor; return clone; } @Override public boolean process(Person person, long time) { if (threadExpProcessor.get() != null) { value = threadExpProcessor.get().evaluate(person, time); } if (value != null) { person.attributes.put(attribute, value); } else if (person.attributes.containsKey(attribute)) { // intentionally clear out the variable person.attributes.remove(attribute); } return true; } } /** * The Counter state type increments or decrements a specified numeric attribute on the patient * entity. In essence, this state counts the number of times it is processed. * * <p>Note: The attribute is initialized with a default value of 0 if not previously set. */ public static class Counter extends State { private String attribute; private String action; private boolean increment; @Override protected void initialize(Module module, String name, JsonObject definition) { super.initialize(module, name, definition); increment = action.equals("increment"); } @Override public Counter clone() { Counter clone = (Counter) super.clone(); clone.attribute = attribute; clone.increment = increment; return clone; } @Override public boolean process(Person person, long time) { int counter = 0; if (person.attributes.containsKey(attribute)) { counter = (int) person.attributes.get(attribute); } if (increment) { counter++; } else { counter } person.attributes.put(attribute, counter); return true; } } /** * The Encounter state type indicates a point in the module where an encounter should take place. * Encounters are important in Synthea because they are generally the mechanism through which the * actual patient record is updated (a disease is diagnosed, a medication is prescribed, etc). The * generic module framework supports integration with scheduled wellness encounters from Synthea's * Encounters module, as well as creation of new stand-alone encounters. * * <p>Scheduled Wellness Encounters vs. Standalone Encounters An Encounter state with the wellness * property set to true will block until the next scheduled wellness encounter occurs. Scheduled * wellness encounters are managed by the Encounters module in Synthea and, depending on the * patient's age, typically occur every 1 - 3 years. When a scheduled wellness encounter finally * does occur, Synthea will search the generic modules for currently blocked Encounter states and * will immediately process them (and their subsequent states). An example where this might be * used is for a condition that onsets between encounters, but isn't found and diagnosed until the * next regularly scheduled wellness encounter. * * <p>An Encounter state without the wellness property set will be processed and recorded in the * patient record immediately. Since this creates an encounter, the encounter_class and one or * more codes must be specified in the state configuration. This is how generic modules can * introduce encounters that are not already scheduled by other modules. * * <p>Encounters and Related Events Encounters are typically the mechanism through which a * patient's record will be updated. This makes sense since most recorded events (diagnoses, * prescriptions, and procedures) should happen in the context of an encounter. When an Encounter * state is successfully processed, Synthea will look through the previously processed states for * un-recorded ConditionOnset or AllergyOnset instances that indicate that Encounter (by name) as * the target_encounter. If Synthea finds any, they will be recorded in the patient's record at * the time of the encounter. This is the mechanism for onsetting a disease before it is * discovered and diagnosed. */ public static class Encounter extends State { private boolean wellness; private String encounterClass; private List<Code> codes; private String reason; @Override public Encounter clone() { Encounter clone = (Encounter) super.clone(); clone.wellness = wellness; clone.encounterClass = encounterClass; clone.reason = reason; clone.codes = codes; return clone; } @Override public boolean process(Person person, long time) { if (wellness) { HealthRecord.Encounter encounter = person.record.currentEncounter(time); entry = encounter; String activeKey = EncounterModule.ACTIVE_WELLNESS_ENCOUNTER + " " + this.module.name; if (person.attributes.containsKey(activeKey)) { person.attributes.remove(activeKey); person.setCurrentEncounter(module, encounter); diagnosePastConditions(person, time); if (!encounter.chronicMedsRenewed && person.chronicMedications.size() > 0) { renewChronicMedicationsAtWellness(person, time); encounter.chronicMedsRenewed = true; } return true; } else { // Block until we're in a wellness encounter... then proceed. return false; } } else { EncounterType type = EncounterType.fromString(encounterClass); HealthRecord.Encounter encounter = EncounterModule.createEncounter(person, time, type, ClinicianSpecialty.GENERAL_PRACTICE, null); entry = encounter; if (codes != null) { encounter.codes.addAll(codes); } person.setCurrentEncounter(module, encounter); encounter.name = this.name; diagnosePastConditions(person, time); if (reason != null) { if (person.attributes.containsKey(reason)) { Entry condition = (Entry) person.attributes.get(reason); encounter.reason = condition.codes.get(0); } else if (person.hadPriorState(reason)) { // loop through the present conditions, the condition "name" will match // the name of the ConditionOnset state (aka "reason") for (Entry entry : person.record.present.values()) { if (reason.equals(entry.name)) { encounter.reason = entry.codes.get(0); break; } } } } return true; } } private void diagnosePastConditions(Person person, long time) { // reminder: history[0] is current state, history[size-1] is Initial for (State state : person.history) { if (state instanceof OnsetState) { OnsetState onset = (OnsetState) state; if (!onset.diagnosed && this.name.equals(onset.targetEncounter)) { onset.diagnose(person, time); } } else if (state instanceof Encounter && state != this && state.name.equals(this.name)) { // a prior instance of hitting this same state. no need to go back any further break; } } } private void renewChronicMedicationsAtWellness(Person person, long time) { // note that this code has some child codes for various different reasons, // eg "medical aim achieved", "ineffective", "avoid interaction", "side effect", etc Code expiredCode = new Code("SNOMED-CT", "182840001", "Drug treatment stopped - medical advice"); // We keep track of the meds we renewed to add them to the chronic list later // as we can't modify the list of chronic meds while iterating. List<Medication> renewedMedications = new ArrayList<Medication>(person.chronicMedications.values().size()); // Go through each chronic medication and "reorder" for (Medication chronicMedication : person.chronicMedications.values()) { // RxNorm code String primaryCode = chronicMedication.type; // Removes from Chronic List as well; but won't affect iterator. person.record.medicationEnd(time, primaryCode, expiredCode); // IMPORTANT: 3rd par is false to prevent modification of chronic meds // list as we iterate over it According to the documentation, the // results of modifying the array (x remove) are undefined Medication medication = person.record.medicationStart(time, primaryCode, false); // Copy over the characteristics from old medication to new medication medication.name = chronicMedication.name; medication.codes.addAll(chronicMedication.codes); medication.reasons.addAll(chronicMedication.reasons); medication.prescriptionDetails = chronicMedication.prescriptionDetails; medication.administration = chronicMedication.administration; // NB: The next one isn't present. Normally done by // person.record.medicationStart, but we are avoiding modifying the // chronic meds list until we are done iterating medication.chronic = true; // increment number of prescriptions prescribed by respective hospital Provider medicationProvider = person.getCurrentProvider(module.name); if (medicationProvider == null) { // no provider associated with encounter or medication order medicationProvider = person.getProvider(EncounterType.WELLNESS, time); } int year = Utilities.getYear(time); medicationProvider.incrementPrescriptions(year); renewedMedications.add(medication); } // Reinitialize the chronic meds list with the meds we just created // Perhaps not technically necessary, as we can just keep the old ones // around, but this is safer. person.chronicMedications.clear(); for (Medication renewedMedication : renewedMedications) { person.chronicMedications.put(renewedMedication.type, renewedMedication); } } public boolean isWellness() { return wellness; } } /** * The EncounterEnd state type indicates the end of the encounter the patient is currently in, for * example when the patient leaves a clinician's office, or is discharged from a hospital. The * time the encounter ended is recorded on the patient's record. * * <p>Note on Wellness Encounters Because wellness encounters are scheduled and initiated outside * the generic modules, and a single wellness encounter may contain observations or medications * from multiple modules, an EncounterEnd state will not record the end time for a wellness * encounter. Hence it is not strictly necessary to use an EncounterEnd state to end the wellness * encounter. Still, it is recommended to use an EncounterEnd state to mark a clear end to the * encounter. */ public static class EncounterEnd extends State { private Code dischargeDisposition; @Override public EncounterEnd clone() { EncounterEnd clone = (EncounterEnd) super.clone(); clone.dischargeDisposition = dischargeDisposition; return clone; } @Override public boolean process(Person person, long time) { HealthRecord.Encounter encounter = person.getCurrentEncounter(module); EncounterType type = EncounterType.fromString(encounter.type); if (type != EncounterType.WELLNESS) { person.record.encounterEnd(time, type); } encounter.discharge = dischargeDisposition; // reset current provider hash person.removeCurrentProvider(module.name); person.setCurrentEncounter(module, null); return true; } } /** * OnsetState is a parent class for ConditionOnset and AllergyOnset, where some common logic can * be shared. It is an implementation detail and should never be referenced directly in a JSON * module. */ private abstract static class OnsetState extends State { public boolean diagnosed; protected List<Code> codes; protected String assignToAttribute; protected String targetEncounter; public OnsetState clone() { OnsetState clone = (OnsetState) super.clone(); clone.codes = codes; clone.assignToAttribute = assignToAttribute; clone.targetEncounter = targetEncounter; return clone; } @Override public boolean process(Person person, long time) { HealthRecord.Encounter encounter = person.getCurrentEncounter(module); if (targetEncounter == null || targetEncounter.trim().length() == 0 || (encounter != null && targetEncounter.equals(encounter.name))) { diagnose(person, time); } else if (assignToAttribute != null && codes != null) { // create a temporary coded entry to use for reference in the attribute, // which will be replaced if the thing is diagnosed HealthRecord.Entry codedEntry = person.record.new Entry(time, codes.get(0).code); codedEntry.codes.addAll(codes); person.attributes.put(assignToAttribute, codedEntry); } return true; } public abstract void diagnose(Person person, long time); } /** * The ConditionOnset state type indicates a point in the module where the patient acquires a * condition. This is not necessarily the same as when the condition is diagnosed and recorded in * the patient's record. In fact, it is possible for a condition to onset but never be discovered. * * <p>If the ConditionOnset state's target_encounter is set to the name of a future encounter, * then the condition will only be diagnosed when that future encounter occurs. */ public static class ConditionOnset extends OnsetState { @Override public void diagnose(Person person, long time) { String primaryCode = codes.get(0).code; entry = person.record.conditionStart(time, primaryCode); entry.name = this.name; if (codes != null) { entry.codes.addAll(codes); } if (assignToAttribute != null) { person.attributes.put(assignToAttribute, entry); } diagnosed = true; } } /** * The ConditionEnd state type indicates a point in the module where a currently active condition * should be ended, for example if the patient has been cured of a disease. * * <p>The ConditionEnd state supports three ways of specifying the condition to end: By `codes[]`, * specifying the system, code, and display name of the condition to end By `condition_onset`, * specifying the name of the ConditionOnset state in which the condition was onset By * `referenced_by_attribute`, specifying the name of the attribute to which a previous * ConditionOnset state assigned a condition */ public static class ConditionEnd extends State { private List<Code> codes; private String conditionOnset; private String referencedByAttribute; @Override public ConditionEnd clone() { ConditionEnd clone = (ConditionEnd) super.clone(); clone.codes = codes; clone.conditionOnset = conditionOnset; clone.referencedByAttribute = referencedByAttribute; return clone; } @Override public boolean process(Person person, long time) { if (conditionOnset != null) { person.record.conditionEndByState(time, conditionOnset); } else if (referencedByAttribute != null) { Entry condition = (Entry) person.attributes.get(referencedByAttribute); condition.stop = time; person.record.conditionEnd(time, condition.type); } else if (codes != null) { codes.forEach(code -> person.record.conditionEnd(time, code.code)); } return true; } } /** * The AllergyOnset state type indicates a point in the module where the patient acquires an * allergy. This is not necessarily the same as when the allergy is diagnosed and recorded in the * patient's record. In fact, it is possible for an allergy to onset but never be discovered. * * <p>If the AllergyOnset state's target_encounter is set to the name of a future encounter, * then the allergy will only be diagnosed when that future encounter occurs. */ public static class AllergyOnset extends OnsetState { @Override public void diagnose(Person person, long time) { String primaryCode = codes.get(0).code; entry = person.record.allergyStart(time, primaryCode); entry.name = this.name; entry.codes.addAll(codes); if (assignToAttribute != null) { person.attributes.put(assignToAttribute, entry); } diagnosed = true; } } /** * The AllergyEnd state type indicates a point in the module where a currently active allergy * should be ended, for example if the patient's allergy subsides with time. * * <p>The AllergyEnd state supports three ways of specifying the allergy to end: By `codes[]`, * specifying the system, code, and display name of the allergy to end By `allergy_onset`, * specifying the name of the AllergyOnset state in which the allergy was onset By * `referenced_by_attribute`, specifying the name of the attribute to which a previous * AllergyOnset state assigned a condition * */ public static class AllergyEnd extends State { private List<Code> codes; private String allergyOnset; private String referencedByAttribute; @Override public AllergyEnd clone() { AllergyEnd clone = (AllergyEnd) super.clone(); clone.codes = codes; clone.allergyOnset = allergyOnset; clone.referencedByAttribute = referencedByAttribute; return clone; } @Override public boolean process(Person person, long time) { if (allergyOnset != null) { person.record.allergyEndByState(time, allergyOnset); } else if (referencedByAttribute != null) { Entry allergy = (Entry) person.attributes.get(referencedByAttribute); allergy.stop = time; person.record.allergyEnd(time, allergy.type); } else if (codes != null) { codes.forEach(code -> person.record.conditionEnd(time, code.code)); } return true; } } /** * The MedicationOrder state type indicates a point in the module where a medication is * prescribed. MedicationOrder states may only be processed during an Encounter, and so must * occur after the target Encounter state and before the EncounterEnd. See the Encounter * section above for more details. The MedicationOrder state supports identifying a previous * ConditionOnset or the name of an attribute as the reason for the prescription. Adding a * 'administration' field allows for the MedicationOrder to also export a * MedicationAdministration into the exported FHIR record. */ public static class MedicationOrder extends State { private List<Code> codes; private String reason; private JsonObject prescription; // TODO make this a Component private String assignToAttribute; private boolean administration; private boolean chronic; @Override public MedicationOrder clone() { MedicationOrder clone = (MedicationOrder) super.clone(); clone.codes = codes; clone.reason = reason; clone.prescription = prescription; clone.assignToAttribute = assignToAttribute; clone.administration = administration; clone.chronic = chronic; return clone; } @Override public boolean process(Person person, long time) { String primaryCode = codes.get(0).code; Medication medication = person.record.medicationStart(time, primaryCode, chronic); entry = medication; medication.name = this.name; medication.codes.addAll(codes); if (reason != null) { // "reason" is an attribute or stateName referencing a previous conditionOnset state if (person.attributes.containsKey(reason)) { Entry condition = (Entry) person.attributes.get(reason); medication.reasons.addAll(condition.codes); } else if (person.hadPriorState(reason)) { // loop through the present conditions, the condition "name" will match // the name of the ConditionOnset state (aka "reason") for (Entry entry : person.record.present.values()) { if (reason.equals(entry.name)) { medication.reasons.addAll(entry.codes); } } } } medication.prescriptionDetails = prescription; medication.administration = administration; if (assignToAttribute != null) { person.attributes.put(assignToAttribute, medication); } // increment number of prescriptions prescribed by respective hospital Provider medicationProvider = person.getCurrentProvider(module.name); if (medicationProvider == null) { // no provider associated with encounter or medication order medicationProvider = person.getProvider(EncounterType.WELLNESS, time); } int year = Utilities.getYear(time); medicationProvider.incrementPrescriptions(year); return true; } } /** * The MedicationEnd state type indicates a point in the module where a currently prescribed * medication should be ended. * * <p>The MedicationEnd state supports three ways of specifying the medication to end: * By `codes[]`, specifying the code system, code, and display name of the medication to end By * `medication_order`, specifying the name of the MedicationOrder state in which the medication * was prescribed By `referenced_by_attribute`, specifying the name of the attribute to which a * previous MedicationOrder state assigned a medication */ public static class MedicationEnd extends State { private List<Code> codes; private String medicationOrder; private String referencedByAttribute; // note that this code has some child codes for various different reasons, // ex "medical aim achieved", "ineffective", "avoid interaction", "side effect", etc private static final Code EXPIRED = new Code("SNOMED-CT", "182840001", "Drug treatment stopped - medical advice"); @Override public MedicationEnd clone() { MedicationEnd clone = (MedicationEnd) super.clone(); clone.codes = codes; clone.medicationOrder = medicationOrder; clone.referencedByAttribute = referencedByAttribute; return clone; } @Override public boolean process(Person person, long time) { if (medicationOrder != null) { person.record.medicationEndByState(time, medicationOrder, EXPIRED); } else if (referencedByAttribute != null) { Medication medication = (Medication) person.attributes.get(referencedByAttribute); medication.stop = time; person.record.medicationEnd(time, medication.type, EXPIRED); } else if (codes != null) { codes.forEach(code -> person.record.medicationEnd(time, code.code, EXPIRED)); } return true; } } /** * The CarePlanStart state type indicates a point in the module where a care plan should be * prescribed. CarePlanStart states may only be processed during an Encounter, and so must occur * after the target Encounter state and before the EncounterEnd. See the Encounter section above * for more details. One or more codes describes the care plan and a list of activities describes * what the care plan entails. */ public static class CarePlanStart extends State { private List<Code> codes; private List<Code> activities; private List<JsonObject> goals; // TODO: make this a Component private String reason; private String assignToAttribute; @Override public CarePlanStart clone() { CarePlanStart clone = (CarePlanStart) super.clone(); clone.codes = codes; clone.activities = activities; clone.goals = goals; clone.reason = reason; clone.assignToAttribute = assignToAttribute; return clone; } @Override public boolean process(Person person, long time) { String primaryCode = codes.get(0).code; CarePlan careplan = person.record.careplanStart(time, primaryCode); entry = careplan; careplan.name = this.name; careplan.codes.addAll(codes); if (activities != null) { careplan.activities.addAll(activities); } if (goals != null) { careplan.goals.addAll(goals); } if (reason != null) { // "reason" is an attribute or stateName referencing a previous conditionOnset state if (person.attributes.containsKey(reason)) { Entry condition = (Entry) person.attributes.get(reason); careplan.reasons.addAll(condition.codes); } else if (person.hadPriorState(reason)) { // loop through the present conditions, the condition "name" will match // the name of the ConditionOnset state (aka "reason") for (Entry entry : person.record.present.values()) { if (reason.equals(entry.name)) { careplan.reasons.addAll(entry.codes); } } } } if (assignToAttribute != null) { person.attributes.put(assignToAttribute, careplan); } return true; } } /** * The CarePlanEnd state type indicates a point in the module where a currently prescribed care * plan should be ended. The CarePlanEnd state supports three ways of specifying the care plan to * end: By `codes[]`, specifying the code system, code, and display name of the care plan to end * By `careplan`, specifying the name of the CarePlanStart state in which the care plan was * prescribed By `referenced_by_attribute`, specifying the name of the attribute to which a * previous CarePlanStart state assigned a care plan */ public static class CarePlanEnd extends State { private List<Code> codes; private String careplan; private String referencedByAttribute; private static final Code FINISHED = new Code("SNOMED-CT", "385658003", "Done"); @Override public CarePlanEnd clone() { CarePlanEnd clone = (CarePlanEnd) super.clone(); clone.codes = codes; clone.careplan = careplan; clone.referencedByAttribute = referencedByAttribute; return clone; } @Override public boolean process(Person person, long time) { if (careplan != null) { person.record.careplanEndByState(time, careplan, FINISHED); } else if (referencedByAttribute != null) { CarePlan careplan = (CarePlan) person.attributes.get(referencedByAttribute); careplan.stop = time; person.record.careplanEnd(time, careplan.type, FINISHED); } else if (codes != null) { codes.forEach(code -> person.record.careplanEnd(time, code.code, FINISHED)); } return true; } } /** * The Procedure state type indicates a point in the module where a procedure should be performed. * Procedure states may only be processed during an Encounter, and so must occur after the target * Encounter state and before the EncounterEnd. See the Encounter section above for more details. * Optionally, you may define a duration of time that the procedure takes. The Procedure also * supports identifying a previous ConditionOnset or an attribute as the reason for the procedure. */ public static class Procedure extends State { private List<Code> codes; private String reason; private RangeWithUnit<Long> duration; private String assignToAttribute; @Override public Procedure clone() { Procedure clone = (Procedure) super.clone(); clone.codes = codes; clone.reason = reason; clone.duration = duration; clone.assignToAttribute = assignToAttribute; return clone; } @Override public boolean process(Person person, long time) { String primaryCode = codes.get(0).code; HealthRecord.Procedure procedure = person.record.procedure(time, primaryCode); entry = procedure; procedure.name = this.name; procedure.codes.addAll(codes); if (reason != null) { // "reason" is an attribute or stateName referencing a previous conditionOnset state if (person.attributes.containsKey(reason)) { Entry condition = (Entry) person.attributes.get(reason); procedure.reasons.addAll(condition.codes); } else if (person.hadPriorState(reason)) { // loop through the present conditions, the condition "name" will match // the name of the ConditionOnset state (aka "reason") for (Entry entry : person.record.present.values()) { if (reason.equals(entry.name)) { procedure.reasons.addAll(entry.codes); } } } } if (duration != null) { double durationVal = person.rand(duration.low, duration.high); procedure.stop = procedure.start + Utilities.convertTime(duration.unit, (long) durationVal); } // increment number of procedures by respective hospital Provider provider; if (person.getCurrentProvider(module.name) != null) { provider = person.getCurrentProvider(module.name); } else { // no provider associated with encounter or procedure provider = person.getProvider(EncounterType.WELLNESS, time); } int year = Utilities.getYear(time); provider.incrementProcedures(year); if (assignToAttribute != null) { person.attributes.put(assignToAttribute, procedure); } return true; } } /** * The VitalSign state type indicates a point in the module where a patient's vital sign is set. * Vital Signs represent the actual physical state of the patient, in contrast to Observations * which are the recording of that physical state. * * <p>Usage Notes In general, the Vital Sign should be used if the value directly affects the * patient's physical condition. For example, high blood pressure directly increases the risk of * heart attack so any conditional logic that would trigger a heart attack should reference a * Vital Sign instead of an Observation. ' On the other hand, if the value only affects the * patient's care, using just an Observation would be more appropriate. For example, it is the * observation of MMSE that can lead to a diagnosis of Alzheimer's; MMSE is an observed value and * not a physical metric, so it should not be stored in a VitalSign. */ public static class VitalSign extends State { private org.mitre.synthea.world.concepts.VitalSign vitalSign; private String unit; private Range<Double> range; private Exact<Double> exact; private String expression; private transient ThreadLocal<ExpressionProcessor> threadExpProcessor; @Override protected void initialize(Module module, String name, JsonObject definition) { super.initialize(module, name, definition); // If the ThreadLocal instance hasn't been created yet, create it now if (threadExpProcessor == null) { threadExpProcessor = new ThreadLocal<ExpressionProcessor>(); } // If there's an expression, create the processor for it if (this.expression != null && threadExpProcessor.get() == null) { threadExpProcessor.set(new ExpressionProcessor(this.expression)); } } @Override public VitalSign clone() { VitalSign clone = (VitalSign) super.clone(); clone.range = range; clone.exact = exact; clone.vitalSign = vitalSign; clone.unit = unit; clone.expression = expression; clone.threadExpProcessor = threadExpProcessor; return clone; } @Override public boolean process(Person person, long time) { if (exact != null) { person.setVitalSign(vitalSign, new ConstantValueGenerator(person, exact.quantity)); } else if (range != null) { person.setVitalSign(vitalSign, new RandomValueGenerator(person, range.low, range.high)); } else if (threadExpProcessor.get() != null) { Number value = (Number) threadExpProcessor.get().evaluate(person, time); person.setVitalSign(vitalSign, value.doubleValue()); } else { throw new RuntimeException( "VitalSign state has no exact quantity or low/high range: " + this); } return true; } } /** * The Observation state type indicates a point in the module where an observation is recorded. * Observations include clinical findings, vital signs, lab tests, etc. Observation states may * only be processed during an Encounter, and so must occur after the target Encounter state and * before the EncounterEnd. See the Encounter section above for more details. * * <p>Observation Categories Common observation categories include: "vital-signs" : * Clinical observations measure the body's basic functions such as such as blood pressure, heart * rate, respiratory rate, height, weight, body mass index, head circumference, pulse oximetry, * temperature, and body surface area. * * <p>"procedure" : Observations generated by other procedures. This category includes * observations resulting from interventional and non-interventional procedures excluding lab and * imaging (e.g. cardiology catheterization, endoscopy, electrodiagnostics, etc.). Procedure * results are typically generated by a clinician to provide more granular information about * component observations made during a procedure, such as where a gastroenterologist reports the * size of a polyp observed during a colonoscopy. * * <p>"laboratory" : The results of observations generated by laboratories. Laboratory results are * typically generated by laboratories providing analytic services in areas such as chemistry, * hematology, serology, histology, cytology, anatomic pathology, microbiology, and/or virology. * These observations are based on analysis of specimens obtained from the patient and submitted * to the laboratory. * * <p>"exam" : Observations generated by physical exam findings including direct observations made * by a clinician and use of simple instruments and the result of simple maneuvers performed * directly on the patient's body. * * <p>"social-history" : The Social History Observations define the patient's occupational, * personal (e.g. lifestyle), social, and environmental history and health risk factors, as well * as administrative data such as marital status, race, ethnicity and religious affiliation. */ public static class Observation extends State { private List<Code> codes; private Range<Double> range; private Exact<Object> exact; private Code valueCode; private String attribute; private org.mitre.synthea.world.concepts.VitalSign vitalSign; private String category; private String unit; private String expression; private transient ThreadLocal<ExpressionProcessor> threadExpProcessor; @Override protected void initialize(Module module, String name, JsonObject definition) { super.initialize(module, name, definition); // If the ThreadLocal instance hasn't been created yet, create it now if (threadExpProcessor == null) { threadExpProcessor = new ThreadLocal<ExpressionProcessor>(); } // If there's an expression, create the processor for it if (this.expression != null) { threadExpProcessor.set(new ExpressionProcessor(this.expression)); } } @Override public Observation clone() { Observation clone = (Observation) super.clone(); clone.codes = codes; clone.range = range; clone.exact = exact; clone.valueCode = valueCode; clone.attribute = attribute; clone.vitalSign = vitalSign; clone.category = category; clone.unit = unit; clone.expression = expression; clone.threadExpProcessor = threadExpProcessor; return clone; } @Override public boolean process(Person person, long time) { String primaryCode = codes.get(0).code; Object value = null; if (exact != null) { value = exact.quantity; } else if (range != null) { value = person.rand(range.low, range.high, range.decimals); } else if (attribute != null) { value = person.attributes.get(attribute); } else if (vitalSign != null) { value = person.getVitalSign(vitalSign, time); } else if (valueCode != null) { value = valueCode; } else if (threadExpProcessor.get() != null) { value = threadExpProcessor.get().evaluate(person, time); } HealthRecord.Observation observation = person.record.observation(time, primaryCode, value); entry = observation; observation.name = this.name; observation.codes.addAll(codes); observation.category = category; observation.unit = unit; return true; } } /** * ObservationGroup is an internal parent class to provide common logic to state types that * package multiple observations into a single entity. It is an implementation detail and should * not be referenced by JSON modules directly. */ private abstract static class ObservationGroup extends State { protected List<Code> codes; protected List<Observation> observations; public ObservationGroup clone() { ObservationGroup clone = (ObservationGroup) super.clone(); clone.codes = codes; clone.observations = observations; return clone; } } /** * The MultiObservation state indicates that some number of Observations should be * grouped together as a single observation. This can be necessary when one observation records * multiple values, for example in the case of Blood Pressure, which is really 2 values, Systolic * and Diastolic Blood Pressure. MultiObservation states may only be processed * during an Encounter, and so must occur after the target Encounter state and before the * EncounterEnd. See the Encounter section above for more details. */ public static class MultiObservation extends ObservationGroup { private String category; @Override public MultiObservation clone() { MultiObservation clone = (MultiObservation) super.clone(); clone.category = category; return clone; } @Override public boolean process(Person person, long time) { for (Observation o : observations) { o.process(person, time); } String primaryCode = codes.get(0).code; HealthRecord.Observation observation = person.record.multiObservation(time, primaryCode, observations.size()); entry = observation; observation.name = this.name; observation.codes.addAll(codes); observation.category = category; return true; } } /** * The DiagnosticReport state indicates that some number of Observations should be * grouped together within a single Diagnostic Report. This can be used when multiple observations * are part of a single panel. DiagnosticReport states may only be processed during an Encounter, * and so must occur after the target Encounter state and before the EncounterEnd. See the * Encounter section above for more details. */ public static class DiagnosticReport extends ObservationGroup { @Override public boolean process(Person person, long time) { for (Observation o : observations) { o.process(person, time); } String primaryCode = codes.get(0).code; Report report = person.record.report(time, primaryCode, observations.size()); entry = report; report.name = this.name; report.codes.addAll(codes); // increment number of labs by respective provider Provider provider; if (person.getCurrentProvider(module.name) != null) { provider = person.getCurrentProvider(module.name); } else { // no provider associated with encounter or procedure provider = person.getProvider(EncounterType.WELLNESS, time); } int year = Utilities.getYear(time); provider.incrementLabs(year); return true; } } /** * The ImagingStudy state indicates a point in the module when an imaging study was performed. * An ImagingStudy consists of one or more Studies, where each Study contains one or more * Instances of an image. ImagingStudy states may only be processed during an Encounter, * and must occur after the target Encounter state and before the EncounterEnd. See the * Encounter section above for more details. */ public static class ImagingStudy extends State { /** The equivalent SNOMED codes that describe this ImagingStudy as a Procedure. */ private Code procedureCode; /** The Series of Instances that represent this ImagingStudy. */ private List<HealthRecord.ImagingStudy.Series> series; /** Minimum and maximum number of series in this study. * Actual number is picked uniformly randomly from this range, copying series data from * the first series provided. */ public int minNumberSeries = 0; public int maxNumberSeries = 0; @Override public ImagingStudy clone() { ImagingStudy clone = (ImagingStudy) super.clone(); clone.procedureCode = procedureCode; clone.series = series; clone.minNumberSeries = minNumberSeries; clone.maxNumberSeries = maxNumberSeries; return clone; } @Override public boolean process(Person person, long time) { // Randomly pick number of series and instances if bounds were provided duplicateSeries(person); duplicateInstances(person); // The modality code of the first series is a good approximation // of the type of ImagingStudy this is String primaryModality = series.get(0).modality.code; entry = person.record.imagingStudy(time, primaryModality, series); // Also add the Procedure equivalent of this ImagingStudy to the patient's record String primaryProcedureCode = procedureCode.code; HealthRecord.Procedure procedure = person.record.procedure(time, primaryProcedureCode); procedure.name = this.name; procedure.codes.add(procedureCode); procedure.stop = procedure.start + TimeUnit.MINUTES.toMillis(30); return true; } private void duplicateSeries(Person person) { if (minNumberSeries > 0 && maxNumberSeries >= minNumberSeries && series.size() > 0) { // Randomly pick the number of series in this study int numberOfSeries = (int) person.rand(minNumberSeries, maxNumberSeries + 1); HealthRecord.ImagingStudy.Series referenceSeries = series.get(0); series = new ArrayList<HealthRecord.ImagingStudy.Series>(); // Create the new series with random series UID for (int i = 0; i < numberOfSeries; i++) { HealthRecord.ImagingStudy.Series newSeries = referenceSeries.clone(); newSeries.dicomUid = Utilities.randomDicomUid(i + 1, 0); series.add(newSeries); } } else { // Ensure series references are distinct (required if no. of instances is picked randomly) List<HealthRecord.ImagingStudy.Series> oldSeries = series; series = new ArrayList<HealthRecord.ImagingStudy.Series>(); for (int i = 0; i < oldSeries.size(); i++) { HealthRecord.ImagingStudy.Series newSeries = oldSeries.get(i).clone(); series.add(newSeries); } } } private void duplicateInstances(Person person) { for (int i = 0; i < series.size(); i++) { HealthRecord.ImagingStudy.Series s = series.get(i); if (s.minNumberInstances > 0 && s.maxNumberInstances >= s.minNumberInstances && s.instances.size() > 0) { // Randomly pick the number of instances in this series int numberOfInstances = (int) person.rand(s.minNumberInstances, s.maxNumberInstances + 1); HealthRecord.ImagingStudy.Instance referenceInstance = s.instances.get(0); s.instances = new ArrayList<HealthRecord.ImagingStudy.Instance>(); // Create the new instances with random instance UIDs for (int j = 0; j < numberOfInstances; j++) { HealthRecord.ImagingStudy.Instance newInstance = referenceInstance.clone(); newInstance.dicomUid = Utilities.randomDicomUid(i + 1, j + 1); s.instances.add(newInstance); } } } } } /** * The Symptom state type adds or updates a patient's symptom. Synthea tracks symptoms in order to * drive a patient's encounters, on a scale of 1-100. A symptom may be tracked for multiple * conditions, in these cases only the highest value is considered. See also the Symptom logical * condition type. */ public static class Symptom extends State { private String symptom; private String cause; private Double probability; private Range<Integer> range; private Exact<Integer> exact; public boolean addressed; @Override protected void initialize(Module module, String name, JsonObject definition) { super.initialize(module, name, definition); if (cause == null) { cause = module.name; } if (probability == null || probability > 1 || probability < 0) { probability = 1.0; } addressed = false; } @Override public Symptom clone() { Symptom clone = (Symptom) super.clone(); clone.symptom = symptom; clone.cause = cause; clone.probability = probability; clone.range = range; clone.exact = exact; clone.addressed = addressed; return clone; } @Override public boolean process(Person person, long time) { if (person.rand() <= probability) { if (exact != null) { person.setSymptom(cause, symptom, exact.quantity, addressed); } else if (range != null) { person.setSymptom(cause, symptom, (int) person.rand(range.low, range.high), addressed); } else { person.setSymptom(cause, symptom, 0, addressed); } } return true; } } /** * The Death state type indicates a point in the module at which the patient dies or the patient * is given a terminal diagnosis (e.g. "you have 3 months to live"). When the Death state is * processed, the patient's death is immediately recorded (the alive? method will return false) * unless range or exact attributes are specified, in which case the patient will die sometime in * the future. In either case the module will continue to progress to the next state(s) for the * current time-step. Typically, the Death state should transition to a Terminal state. * * <p>The Cause of Death listed on a Death Certificate can be specified in three ways: * By `codes[]`, specifying the system, code, and display name of the condition causing death. * By `condition_onset`, specifying the name of the ConditionOnset state in which the condition * causing death was onset. By `referenced_by_attribute`, specifying the name of the attribute to * which a previous ConditionOnset state assigned a condition that caused death. * * <p>Implementation Warning If a Death state is processed after a Delay, it may cause * inconsistencies in the record. This is because the Delay implementation must rewind time to * correctly honor the requested delay duration. If it rewinds time, and then the patient dies at * the rewinded time, then any modules that were processed before the generic module may have * created events and records with a timestamp after the patient's death. */ public static class Death extends State { private List<Code> codes; private String conditionOnset; private String referencedByAttribute; private RangeWithUnit<Integer> range; private ExactWithUnit<Integer> exact; @Override public Death clone() { Death clone = (Death) super.clone(); clone.codes = codes; clone.conditionOnset = conditionOnset; clone.referencedByAttribute = referencedByAttribute; clone.range = range; clone.exact = exact; return clone; } @Override public boolean process(Person person, long time) { Code reason = null; if (codes != null) { reason = codes.get(0); } else if (conditionOnset != null) { if (person.hadPriorState(conditionOnset)) { // loop through the present conditions, the condition "name" will match // the name of the ConditionOnset state (aka "reason") for (Entry entry : person.record.present.values()) { if (entry.name != null && entry.name.equals(conditionOnset)) { reason = entry.codes.get(0); } } } } else if (referencedByAttribute != null) { Entry entry = (Entry) person.attributes.get(referencedByAttribute); if (entry == null) { // condition referenced but not yet diagnosed throw new RuntimeException("Attribute '" + referencedByAttribute + "' was referenced by state '" + name + "' but not set"); } reason = entry.codes.get(0); } if (exact != null) { long timeOfDeath = time + Utilities.convertTime(exact.unit, exact.quantity); person.recordDeath(timeOfDeath, reason); return true; } else if (range != null) { double duration = person.rand(range.low, range.high); long timeOfDeath = time + Utilities.convertTime(range.unit, (long) duration); person.recordDeath(timeOfDeath, reason); return true; } else { person.recordDeath(time, reason); return true; } } } }
package net.trajano.ms.gateway.providers; import java.net.ConnectException; import java.net.URI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import io.vertx.core.Handler; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.http.RequestOptions; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import net.trajano.ms.gateway.internal.Conversions; @Configuration @Component public class Handlers { private static final Logger LOG = LoggerFactory.getLogger(Handlers.class); private static final String TOKEN_PATTERN = "^[A-Za-z0-9]{64}$"; @Value("${authorization.endpoint}") private URI authorizationEndpoint; @Value("${jwks.path}") private String jwksPath; @Autowired private HttpClient httpClient; @Value("${jwks.uri}") private URI jwksUri; public Handler<RoutingContext> failureHandler() { return context -> { LOG.error("Unhandled server exception", context.failure()); if (!context.response().ended()) { if (context.failure() instanceof ConnectException) { context.response().setStatusCode(504) .setStatusMessage("Gateway Timeout") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(new JsonObject() .put("error", "server_error") .put("error_description", "Gateway Timeout") .toBuffer()); } else { context.response().setStatusCode(500) .setStatusMessage("Internal Server Error") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(new JsonObject() .put("error", "server_error") .put("error_description", "Internal Server Error") .toBuffer()); } } }; } /** * Obtains the access token from the request. Since the Authorization header * can have multiple values comma separated, it needs to be broken up first * then we have to locate the Bearer token from the comma separated list. * The bearer token is expected to contain the access token. * * @param contextRequest * request * @return access token */ private String getAccessToken(final HttpServerRequest contextRequest, final HttpServerResponse contextResponse) { final String authorizationHeader = contextRequest.getHeader(HttpHeaders.AUTHORIZATION); if (authorizationHeader == null) { return null; } for (final String authorization : authorizationHeader.split(",")) { final String cleanedAuthorization = authorization.trim(); if (cleanedAuthorization.startsWith("Bearer ")) { return cleanedAuthorization.substring(7); } } return null; } /** * Obtains the client credentials from the request. Since the Authorization * header can have multiple values comma separated, it needs to be broken up * first then we have to locate the Basic authorization value from the comma * separated list. * * @param contextRequest * request * @return basic authorization (including "Basic") */ private String getClientCredentials(final HttpServerRequest contextRequest, final HttpServerResponse contextResponse) { final String authorizationHeader = contextRequest.getHeader(HttpHeaders.AUTHORIZATION); if (authorizationHeader == null) { return null; } for (final String authorization : authorizationHeader.split(",")) { final String cleanedAuthorization = authorization.trim(); if (cleanedAuthorization.startsWith("Basic ")) { return cleanedAuthorization; } } return null; } /** * This handler goes through the authorization to prepopulate the * X-JWT-Assertion header. * * @return handler */ public Handler<RoutingContext> protectedHandler(final String baseUri, final URI endpoint) { return context -> { final HttpServerRequest contextRequest = context.request(); final HttpServerResponse contextResponse = context.response(); if (!contextRequest.uri().startsWith(baseUri)) { throw new IllegalStateException(contextRequest.uri() + " did not start with" + baseUri); } final String accessToken = getAccessToken(contextRequest, contextResponse); if (accessToken == null) { LOG.debug("missing access token"); contextResponse .setStatusCode(401) .setStatusMessage("Unauthorized") .putHeader("WWW-Authenticate", "Bearer") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(new JsonObject() .put("error", "invalid_request") .put("error_description", "Missing access authorization") .toBuffer()); return; } if (!accessToken.matches(TOKEN_PATTERN)) { LOG.debug("invalid token={}", accessToken); contextResponse .setStatusCode(400) .setStatusMessage("Bad Request") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(new JsonObject() .put("error", "invalid_request") .put("error_description", "Token not valid") .toBuffer()); return; } final String clientCredentials = getClientCredentials(contextRequest, contextResponse); if (clientCredentials == null) { contextResponse .setStatusCode(401) .setStatusMessage("Unauthorized") .putHeader("WWW-Authenticate", "Basic") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(new JsonObject() .put("error", "invalid_request") .put("error_description", "Missing client authorization") .toBuffer()); return; } contextRequest.setExpectMultipart(context.parsedHeaders().contentType().isPermitted() && "multipart".equals(context.parsedHeaders().contentType().component())); contextRequest.pause(); LOG.debug("access_token={} client_credentials={}", accessToken, clientCredentials); final RequestOptions clientRequestOptions = Conversions.toRequestOptions(endpoint, contextRequest.uri().substring(baseUri.length())); final HttpClientRequest authorizationRequest = httpClient.post(Conversions.toRequestOptions(authorizationEndpoint), authorizationResponse -> { // Trust the authorization endpoint authorizationResponse.bodyHandler(buffer -> { if (authorizationResponse.statusCode() != 200) { contextResponse.setStatusCode(authorizationResponse.statusCode()); contextResponse.setStatusMessage(authorizationResponse.statusMessage()); authorizationResponse.headers().forEach(h -> contextResponse.putHeader(h.getKey(), h.getValue())); contextResponse.putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); contextResponse.end(buffer); } else { final String idToken = new JsonObject(buffer).getString("id_token"); if (idToken == null) { LOG.error("Unable to get the ID Token from {} given access_token={}", authorizationEndpoint, accessToken); context.response().setStatusCode(500) .setStatusMessage("Internal Server Error") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(new JsonObject() .put("error", "server_error") .put("error_description", "Unable to get assertion from authorization endpoint") .toBuffer()); return; } final HttpClientRequest clientRequest = httpClient.request(contextRequest.method(), clientRequestOptions, clientResponse -> { contextResponse.setChunked(true) .setStatusCode(clientResponse.statusCode()); contextResponse.headers().setAll(clientResponse.headers()); clientResponse.handler(contextResponse::write) .endHandler(v -> contextResponse.end()); }).exceptionHandler(context::fail); clientRequest.setChunked(true) .headers().setAll(contextRequest.headers()); clientRequest.putHeader("X-JWT-Assertion", idToken); clientRequest.putHeader("X-JWKS-URI", jwksUri.toASCIIString()); contextRequest.resume(); contextRequest.handler(clientRequest::write) .endHandler(v -> clientRequest.end()) .exceptionHandler(context::fail); } }).exceptionHandler(context::fail); }).exceptionHandler(context::fail); authorizationRequest .putHeader(HttpHeaders.AUTHORIZATION, clientCredentials) .putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") .putHeader(HttpHeaders.ACCEPT, "application/json") .end("grant_type=authorization_code&code=" + accessToken); }; } /** * This handler deals with refreshing the OAuth token. * * @return handler */ public Handler<RoutingContext> refreshHandler() { return context -> { final HttpServerRequest contextRequest = context.request(); final HttpServerResponse contextResponse = context.response(); contextRequest .handler(buf -> { }) .endHandler(v -> { final String grantType = contextRequest.getFormAttribute("grant_type"); if (grantType == null) { contextResponse.putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .setStatusCode(400) .setStatusMessage("Bad Request") .end(new JsonObject() .put("error", "invalid_grant") .put("error_description", "Missing grant type") .toBuffer()); return; } if (!"refresh_token".equals(grantType)) { contextResponse.putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .setStatusCode(400) .setStatusMessage("Bad Request") .end(new JsonObject() .put("error", "unsupported_grant_type") .put("error_description", "Unsupported grant type") .toBuffer()); return; } final String refreshToken = contextRequest.getFormAttribute("refresh_token"); if (refreshToken == null || !refreshToken.matches(TOKEN_PATTERN)) { contextResponse.putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .setStatusCode(400) .setStatusMessage("Bad Request") .end(new JsonObject() .put("error", "invalid_request") .put("error_description", "Missing grant") .toBuffer()); return; } final HttpClientRequest authorizationRequest = httpClient.post(Conversions.toRequestOptions(authorizationEndpoint), authorizationResponse -> { // Trust the authorization endpoint authorizationResponse.bodyHandler(buffer -> { contextResponse.setStatusCode(authorizationResponse.statusCode()); contextResponse.setStatusMessage(authorizationResponse.statusMessage()); authorizationResponse.headers().forEach(h -> contextResponse.putHeader(h.getKey(), h.getValue())); contextResponse.putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); contextResponse.end(buffer); }); }); authorizationRequest .putHeader(HttpHeaders.AUTHORIZATION, contextRequest.getHeader(HttpHeaders.AUTHORIZATION)) .putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") .putHeader(HttpHeaders.ACCEPT, "application/json") .end("grant_type=refresh_token&refresh_token=" + refreshToken); }); }; } /** * This handler passes the data through * * @return handler */ public Handler<RoutingContext> unprotectedHandler(final String baseUri, final URI endpoint) { return context -> { final HttpServerRequest contextRequest = context.request(); if (!contextRequest.uri().startsWith(baseUri)) { throw new IllegalStateException(contextRequest.uri() + " did not start with" + baseUri); } contextRequest.setExpectMultipart(context.parsedHeaders().contentType().isPermitted() && "multipart".equals(context.parsedHeaders().contentType().component())); final RequestOptions clientRequestOptions = Conversions.toRequestOptions(endpoint, contextRequest.uri().substring(baseUri.length())); final HttpClientRequest clientRequest = httpClient.request(contextRequest.method(), clientRequestOptions, clientResponse -> { contextRequest.response().setChunked(clientResponse.getHeader(HttpHeaders.CONTENT_LENGTH) == null) .setStatusCode(clientResponse.statusCode()) .headers().setAll(clientResponse.headers()); contextRequest.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); clientResponse.handler(contextRequest.response()::write) .endHandler((v) -> contextRequest.response().end()); }).exceptionHandler(context::fail) .setChunked(true); clientRequest.headers().setAll(contextRequest.headers()); contextRequest.handler(clientRequest::write) .endHandler((v) -> clientRequest.end()); }; } }
package org.nybatis.core.file; import org.nybatis.core.exception.unchecked.ClassNotExistException; import org.nybatis.core.exception.unchecked.IoException; import org.nybatis.core.file.handler.ZipFileHandler; import org.nybatis.core.file.handler.implement.ExcelHandlerApachePoi; import org.nybatis.core.log.NLogger; import org.nybatis.core.model.NList; import org.nybatis.core.file.handler.FileFinder; import org.nybatis.core.util.StringUtil; import org.nybatis.core.worker.WorkerReadLine; import org.nybatis.core.worker.WorkerWriteBuffer; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.UnicodeExtraFieldPolicy; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.CopyOption; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * File Utility * * @author nayasis@gmail.com * */ public class FileUtil { /** * Delete file or directory * * @param filePath file path or directory path * @throws IoException when fail to opertation */ public static void delete( Path filePath ) throws IoException { if( filePath == null || isNotExist(filePath) ) return; try { if( isDirectory(filePath) ) { Files.walkFileTree( filePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile( Path file, BasicFileAttributes attributes ) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed( Path file, IOException e ) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory( Path dir, IOException e ) throws IOException { if ( e != null) throw e; Files.delete( dir ); return FileVisitResult.CONTINUE; } }); } else { Files.delete( filePath ); } } catch( IOException e ) { throw new IoException( e ); } } /** * Delete file or directory * * @param filePath file path or directory path * @throws IoException when fail to opertation */ public static void delete( String filePath ) throws IoException { if( filePath != null ) delete( Paths.get(filePath) ); } /** * . * * @param filePath ( ) * @return */ public static String getExtention( String filePath ) { if( filePath == null ) return ""; int index = filePath.lastIndexOf( '.' ); if( index < 0 ) return ""; String ext = filePath.substring( index + 1 ); if( ext.contains( File.pathSeparator ) ) return ""; return ext; } public static String getExtention( File file ) { if( file == null ) return ""; return getExtention( file.getName() ); } public static String getExtention( Path path ) { if( path == null ) return ""; return getExtention( path.getFileName().toString() ); } /** * ( ) . * * * @param searchDir * @param includeFile * @param includeDirectory * @param scanDepth * <pre> * -1 : infinite * 0 : in searchDir itself * 1 : from searchDir to 1 depth sub directory * 2 : from searchDir to 2 depth sub directory * ... * </pre> * @param matchingPattern (glob , ) * <pre> * ** : * * : like * * 1. **.xml : searchDir xml * 2. *.xml : searchDir 1depth xml * 3. c:\home\*\*.xml : 'c:\home\ 1 depth xml * 4. c:\home\**\*.xml : 'c:\home\ xml * * 1. * It matches zero , one or more than one characters. While matching, it will not cross directories boundaries. * 2. ** It does the same as * but it crosses the directory boundaries. * 3. ? It matches only one character for the given name. * 4. \ It helps to avoid characters to be interpreted as special characters. * 5. [] In a set of characters, only single character is matched. If (-) hyphen is used then, it matches a range of characters. Example: [efg] matches "e","f" or "g" . [a-d] matches a range from a to d. * 6. {} It helps to matches the group of sub patterns. * * 1. *.java when given path is java , we will get true by PathMatcher.matches(path). * 2. *.* if file contains a dot, pattern will be matched. * 3. *.{java,txt} If file is either java or txt, path will be matched. * 4. abc.? matches a file which start with abc and it has extension with only single character. * * </pre> * * @return ( ) * @throws IoException */ public static List<Path> getList( String searchDir, boolean includeFile, boolean includeDirectory, int scanDepth, String... matchingPattern ) { if( StringUtil.isEmpty( searchDir ) ) return new ArrayList<>(); return getList( Paths.get( searchDir ), includeFile, includeDirectory, scanDepth, matchingPattern ) ; } /** * ( ) . * * * @param searchDir * @param includeFile * @param includeDirectory * @param scanDepth * <pre> * -1 : infinite * 0 : in searchDir itself * 1 : from searchDir to 1 depth sub directory * 2 : from searchDir to 2 depth sub directory * ... * </pre> * @param matchingPattern (glob , ) * <pre> * ** : * * : like * * 1. **.xml : searchDir xml * 2. *.xml : searchDir 1depth xml * 3. c:\home\*\*.xml : 'c:\home\ 1 depth xml * 4. c:\home\**\*.xml : 'c:\home\ xml * * 1. * It matches zero , one or more than one characters. While matching, it will not cross directories boundaries. * 2. ** It does the same as * but it crosses the directory boundaries. * 3. ? It matches only one character for the given name. * 4. \ It helps to avoid characters to be interpreted as special characters. * 5. [] In a set of characters, only single character is matched. If (-) hyphen is used then, it matches a range of characters. Example: [efg] matches "e","f" or "g" . [a-d] matches a range from a to d. * 6. {} It helps to matches the group of sub patterns. * * 1. *.java when given path is java , we will get true by PathMatcher.matches(path). * 2. *.* if file contains a dot, pattern will be matched. * 3. *.{java,txt} If file is either java or txt, path will be matched. * 4. abc.? matches a file which start with abc and it has extension with only single character. * * </pre> * * @return ( ) * @throws IoException */ public static List<Path> getList( Path searchDir, boolean includeFile, boolean includeDirectory, int scanDepth, String... matchingPattern ) { if( isNotExist( searchDir ) ) return new ArrayList<>(); Path rootDir = isFile( searchDir ) ? searchDir.getParent() : searchDir; FileFinder finder = new FileFinder( includeFile, includeDirectory, matchingPattern ); scanDepth = ( scanDepth < 0 ) ? Integer.MAX_VALUE : ++scanDepth; try { Files.walkFileTree( rootDir, EnumSet.noneOf( FileVisitOption.class ), scanDepth, finder ); } catch( IOException e ) { throw new IoException( e ); } return finder.getFindResult(); } public static boolean isExist( Path path ) { return path != null && Files.exists( path ); } /** * File Directory . * * @param path * @return */ public static boolean isExist( String path ) { return isExist( Paths.get(path) ); } public static boolean isExist( File file ) { return file != null && isExist( file.toPath() ); } public static boolean isNotExist( Path path ) { return path != null && Files.notExists( path ); } public static boolean isNotExist( String path ) { return isNotExist( Paths.get(path) ); } public static boolean isNotExist( File file ) { return file != null && isNotExist( file.toPath() ); } public static boolean isFile( Path path ) { return path != null && Files.isRegularFile( path ); } public static boolean isFile( String path ) { return isFile( Paths.get(path) ); } public static boolean isFile( File file ) { return file != null && isFile( file.toPath() ); } public static boolean isDirectory( Path path ) { return path != null && Files.isDirectory( path ); } public static boolean isDirectory( String path ) { return isDirectory( Paths.get(path) ); } public static boolean isDirectory( File file ) { return file != null && isDirectory( file.toPath() ); } /** * . * * @param filePath * @throws IoException */ public static File makeDir( String filePath ) throws IoException { if( filePath == null ) return null; return makeDir( Paths.get( filePath ) ); } public static File makeDir( File dir ) throws IoException { if( dir == null ) return null; return makeDir( dir.getAbsolutePath() ); } public static File makeDir( Path filePath ) throws IoException { if( filePath == null ) return null; if( Files.exists( filePath ) ) return filePath.toFile(); try { return Files.createDirectories( filePath ).toFile(); } catch( IOException e ) { throw new IoException( e ); } } public static File makeFile( String filePath ) throws IoException { if( filePath == null ) return null; return makeFile( Paths.get(filePath) ); } public static File makeFile( Path filePath ) throws IoException { if( filePath == null ) return null; if( Files.exists( filePath ) ) { return filePath.toFile(); } else { makeDir( filePath.getParent().toString() ); } try { return Files.createFile( filePath ).toFile(); } catch( IOException e ) { throw new IoException( e ); } } public static File makeFile( File file ) throws IoException { if( file == null ) return null; return makeFile( file.getAbsolutePath() ); } /** * Move file or directory * * @param source file or directory path to move * @param target file or directory path of target * @param overwrite overwrite if the target file exists * @throws IoException if an I/O error occurs */ public static void move( String source, String target, boolean overwrite ) throws IoException { Path sourcePath = Paths.get( source ); Path targetPath = Paths.get( target ); move( sourcePath, targetPath, overwrite ); } /** * Move file or directory * * @param source file or directory path to move * @param target file or directory path of target * @param overwrite overwrite if the target file exists * @throws IoException if an I/O error occurs */ public static void move( Path source, Path target, boolean overwrite ) throws IoException { CopyOption[] option = overwrite ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] {}; try { if( Files.isDirectory(source) ) { Files.move( source, target, option ); } else { if( Files.isDirectory(target) ) { Files.move( source, target.resolve( source.getFileName() ), option ); } else { Files.move( source, target, option ); } } } catch( IOException e ) { throw new IoException( e ); } } /** * Copy file or directory * * @param source file or directory path to move * @param target file or directory path of target * @param overwrite overwrite if the target file exists * @throws IoException if an I/O error occurs */ public static void copy( String source, String target, boolean overwrite ) throws IoException { Path sourcePath = Paths.get( source ); Path targetPath = Paths.get( target ); copy( sourcePath, targetPath, overwrite ); } /** * Copy file or directory * * @param source file or directory path to copy * @param target file or directory path of target * @param overwrite overwrite if the target file exists * @throws IoException if an I/O error occurs */ public static void copy( Path source, Path target, boolean overwrite ) throws IoException { CopyOption[] option = overwrite ? new CopyOption[] { StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] { StandardCopyOption.COPY_ATTRIBUTES }; try { if( Files.isDirectory(source) ) { makeDir( target ); for( Path path : getList( source, true, true, -1 ) ) { Files.copy( path, target.resolve( source.relativize( path ) ), option ); } } else { if( Files.isDirectory(target) ) { Files.copy( source, target.resolve( source.getFileName() ), option ); } else { Files.copy( source, target, option ); } } } catch( IOException e ) { throw new IoException( e ); } } /** * object . * * @param filePath object * @return object * @throws ClassNotExistException object * @throws IoException */ @SuppressWarnings( "unchecked" ) public static <T> T readObject( String filePath ) throws ClassNotExistException, IoException { try( InputStream file = new FileInputStream( filePath ); InputStream buffer = new GZIPInputStream( file ); ObjectInput input = new ObjectInputStream( buffer ) ) { return (T) input.readObject(); } catch( ClassNotFoundException e ) { throw new ClassNotExistException( e ); } catch( IOException e ) { throw new IoException( e ); } } /** * Read serialized objects data stored in file * * @param file file stored serialized objects data. * @return object * @throws ClassNotExistException object * @throws IoException */ public static <T> T readObject( File file ) throws ClassNotExistException, IoException { return readObject( file.getPath() ); } /** * . * * @param filePath ( ) * @return ( ) */ public static String removeExtention( String filePath ) { if( filePath == null ) return filePath; int index = filePath.lastIndexOf( '.' ); if( index < 0 ) return filePath; String ext = filePath.substring( index + 1 ); if( ext.contains( File.pathSeparator ) ) return filePath; return filePath.substring( 0, index ); } public static String readFrom( String filePath ) throws IoException { return readFrom( filePath, "UTF-8" ); } public static String readFrom( String filePath, String charset ) throws IoException { StringBuilder sb = new StringBuilder(); readFrom( filePath, new WorkerReadLine() { public void execute( String readLine ) { sb.append( readLine ).append( '\n' ); } }, charset ); return sb.toString(); } public static String readFrom( File file, String charset ) throws IoException { return readFrom( file.getPath(), charset ); } public static String readFrom( File file ) throws IoException { return readFrom( file.getPath(), "UTF-8" ); } public static void readFrom( Path filePath, WorkerReadLine worker ) throws IoException { readFrom( filePath, worker, "UTF-8" ); } public static void readFrom( Path filePath, WorkerReadLine worker, String charset ) throws IoException { readFrom( filePath.toString(), worker, charset ); } public static void readFrom( File filePath, WorkerReadLine worker, String charset ) throws IoException { readFrom( filePath.toString(), worker, charset ); } public static void readFrom( File filePath, WorkerReadLine worker ) throws IoException { readFrom( filePath.toString(), worker, "UTF-8" ); } public static void readFrom( String filePath, WorkerReadLine worker ) throws IoException { readFrom( filePath, worker, "UTF-8" ); } public static void readFrom( String filePath, WorkerReadLine worker, String charset ) throws IoException { try( FileInputStream fis = new FileInputStream( filePath ); BufferedReader br = new BufferedReader( new InputStreamReader( fis, charset ) ) ) { String line; while( ( line = br.readLine() ) != null ) { worker.execute( line ); } } catch( IOException e ) { throw new IoException( e ); } } public static void writeTo( String filePath, WorkerWriteBuffer handler, String charset ) throws IoException { makeFile( filePath ); try( FileOutputStream fos = new FileOutputStream( filePath ); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( fos, charset ) ) ) { handler.execute( writer ); } catch( IOException e ) { throw new IoException(e); } } public static void writeTo( String filePath, WorkerWriteBuffer handler ) throws IoException { writeTo( filePath, handler, "UTF-8" ); } /** * . * * @param filePath * @param text * @throws IOException */ public static void writeTo( String filePath, final String text ) throws IoException { writeTo( filePath, new WorkerWriteBuffer() { public void execute( BufferedWriter writer ) throws IOException { writer.write( text ); } } ); } public static void writeTo( File file, final String text ) throws IoException { writeTo( file.getAbsolutePath(), text ); } public static void writeTo( File file, byte[] bytes ) throws IoException { makeFile( file ); FileOutputStream stream = null; try { stream = new FileOutputStream( file ); stream.write(bytes); } catch( IOException e ) { throw new IoException(e); } finally { if( stream != null ) try { stream.close(); } catch( IOException e ) {} } } /** * Object . * * @param filePath * @param object object * @throws IoException */ public static void writeObject( String filePath, Object object ) throws IoException { makeFile( filePath ); try( OutputStream file = new FileOutputStream( filePath ); OutputStream buffer = new GZIPOutputStream( file ); ObjectOutput output = new ObjectOutputStream( buffer ) ) { output.writeObject( object ); output.flush(); output.close(); } catch( IOException e ) { throw new IoException( e ); } } /** * Object . * * @param file * @param object object * @throws IOException */ public static void writeObject( File file, Object object ) throws IoException { writeObject( file.getPath(), object ); } public static void writeToCsv( String file, NList data, String delimiter, String charset ) throws IoException { writeTo( file, new WorkerWriteBuffer() { public void execute( BufferedWriter writer ) throws IOException { writer.write( StringUtil.join( data.getAliases(), delimiter ) ); writer.write( '\n' ); for( int row = 0, rowCnt = data.size(); row < rowCnt; row++ ) { List<String> temp = new ArrayList<>(); for( int col = 0, colCnt = data.keySize(); col < colCnt; col++ ) { temp.add( data.getString( col, row ) ); } writer.write( StringUtil.join( temp, delimiter ) ); writer.write( '\n' ); } } }, charset ); } /** * . * * <pre> * FileUtil.convertToAbsolutePath( "/home/user/nayasis", "../test/abc" ); * * -> "/home/user/test/abc" * </pre> * * @param basePath * @param targetPath * @return * @throws FileNotFoundException */ public static String convertToAbsolutePath( String basePath, String targetPath ) throws FileNotFoundException { Path pathBase = getDirectory( Paths.get(basePath) ); return pathBase.resolve( targetPath ).normalize().toString(); } /** * . * * <pre> * FileUtil.convertToRelativePath( "/home/user/nayasis", "/home/user/test/abc" ); * * -> "../test/abc" * </pre> * * @param basePath * @param targetPath * @return * @throws FileNotFoundException * @throws IllegalArgumentException Root (basePath C , targetPath D ) */ public static String convertToRelativePath( String basePath, String targetPath ) throws FileNotFoundException { Path pathBase = getDirectory( Paths.get(basePath) ); return pathBase.relativize( Paths.get( targetPath ) ).toString(); } /** * Get working directory * * @param path File or Directory * @return return parent directory if path is file, return itself it path is directory. * @throws FileNotFoundException paht is not invalid */ public static File getDirectory( File path ) throws FileNotFoundException { return getDirectory( path.toPath() ).toFile(); } /** * Get working directory * * @param path File or Directory * @return return parent directory if path is file, return itself it path is directory. * @throws FileNotFoundException paht is not invalid */ public static Path getDirectory( Path path ) throws FileNotFoundException { if( ! isExist(path) ) throw new FileNotFoundException( StringUtil.format( "path : {}", path ) ); return isDirectory(path) ? path : path.getParent(); } /** * Zip file or directory * * @param fileOrDirectoryToZip file or directory to zip * @param targetFile archive file * @param charset characterset (default : UTF-8) */ public static void zip( File fileOrDirectoryToZip, File targetFile, Charset charset ) { getZipFileHandler().zip( fileOrDirectoryToZip, targetFile, charset ); } /** * Unzip file or directory * * @param fileToUnzip file to unzip * @param targetDirectory directory to unzip * @param charset characterset (default : UTF-8) */ public static void unzip( File fileToUnzip, File targetDirectory, Charset charset ) { getZipFileHandler().unzip( fileToUnzip, targetDirectory, charset ); } private static ZipFileHandler getZipFileHandler() { try { return new ZipFileHandler(); } catch( Throwable e ) { String errorMessage = "FileUtil can not use [Apache Common Compress Library] because it is not imported.\n" + "\t- Maven dependency is like below.\n" + "\t\t<dependency>\n" + "\t\t <groupId>org.apache.commons</groupId>\n" + "\t\t <artifactId>commons-compress</artifactId>\n" + "\t\t <version>1.8</version>\n" + "\t\t</dependency>\n"; NLogger.warn( errorMessage ); } return new ZipFileHandler(); } // private String toPath(File root, File dir){ // String path = dir.getAbsolutePath(); // path = path.substring(root.getAbsolutePath().length()).replace(File.separatorChar, '/'); // if ( path.startsWith("/")) path = path.substring(1); // if ( dir.isDirectory() && !path.endsWith("/")) path += "/" ; // return path ; // } }
/** * * * <h3>Plume-lib Util: Utility libraries for Java</h3> * * <h3 id="Collections_and_iterators">Collections and iterators</h3> * * <dl> * <dt>{@link org.plumelib.util.ArraysPlume ArraysPlume} * <dd>Utilities for manipulating arrays and collections. This complements java.util.Arrays and * java.util.Collections. * <dt>{@link org.plumelib.util.CollectionsPlume CollectionsPlume} * <dd>Utilities for manipulating collections, iterators, lists, maps, and sets. * <dt>{@link org.plumelib.util.CombinationIterator CombinationIterator} * <dd>Given a set of collections, return all combinations that take one element from each * collection. * <dt>{@link org.plumelib.util.LimitedSizeSet LimitedSizeSet} * <dd>Stores up to some maximum number of unique values, at which point its rep is nulled, in * order to save space. * <dt>{@link org.plumelib.util.LimitedSizeIntSet LimitedSizeIntSet} * <dd>Stores up to some maximum number of unique integer values, at which point its rep is * nulled, in order to save space. More efficient than {@code LimitedSizeSet<Integer>}. * <dt>{@link org.plumelib.util.OrderedPairIterator OrderedPairIterator} * <dd>Given two sequences/iterators/whatever, OrderedPairIterator returns a new * sequence/iterator/whatever that pairs the matching elements of the inputs, according to * their respective sort orders. (This operation is sometimes called "zipping".) * <dt>{@link org.plumelib.util.WeakHasherMap WeakHasherMap} * <dd>WeakHashMap is a modified version of WeakHashMap from JDK 1.2.2, that adds a constructor * that takes a {@link org.plumelib.util.Hasher Hasher} argument. * <dt>{@link org.plumelib.util.WeakIdentityHashMap WeakIdentityHashMap} * <dd>WeakIdentityHashMap is a modified version of WeakHashMap from JDK 1.5, that uses * System.identityHashCode() rather than the object's hash code. * </dl> * * <h3 id="Text_processing">Text processing</h3> * * <dl> * <dt>{@link org.plumelib.util.StringsPlume} * <dd>Utility methods that manipulate Strings: replacement; prefixing and indentation; splitting * and joining; quoting and escaping; whitespace; comparisons; StringTokenizer; debugging * variants of toString; diagnostic output; miscellaneous. * <dt>{@link org.plumelib.util.EntryReader EntryReader} * <dd>Class that reads "entries" from a file. In the simplest case, entries can be lines. It * supports: include files, comments, and multi-line entries (paragraphs). The syntax of each * of these is customizable. * <dt>{@link org.plumelib.util.RegexUtil RegexUtil} * <dd>Utility methods for regular expressions, most notably for testing whether a string is a * regular expression. * <dt>{@link org.plumelib.util.FileIOException FileIOException} * <dd>Extends IOException by also reporting a file name and line number at which the exception * occurred. * <dt>{@link org.plumelib.util.FileWriterWithName FileWriterWithName} * <dd>Just like {@code FileWriter}, but adds a {@code getFileName()} method and overrides {@code * toString()} to give the file name. * <!-- * <dt>{link org.plumelib.util.CountingPrintWriter CountingPrintWriter} * <dd>Prints formatted representations of objects to a text-output stream counting the number of * bytes and characters printed. * --> * <!-- * <dt>{link org.plumelib.util.Digest Digest} * <dd>Computes a message digest for a file. * --> * </dl> * * <h3 id="Math">Math</h3> * * <dl> * <dt>{@link org.plumelib.util.MathPlume MathPlume} * <dd>Mathematical utilities. * <dt>{@link org.plumelib.util.FuzzyFloat FuzzyFloat} * <dd>Routines for doing approximate ('fuzzy') floating point comparisons. Those are comparisons * that only require the floating point numbers to be relatively close to one another to be * equal, rather than exactly equal. * </dl> * * <h3 id="Random_selection">Random selection</h3> * * <dl> * <dt>{@link org.plumelib.util.RandomSelector RandomSelector} * <dd>Selects k elements uniformly at random from an arbitrary iterator, using <em>O(k)</em> * space. * <dt>{@link org.plumelib.util.MultiRandSelector MultiRandSelector} * <dd>Like RandomSelector, performs a uniform random selection over an iterator. However, the * objects in the iteration may be partitioned so that the random selection chooses the same * number from each group. * </dl> * * <h3 id="Determinism">Determinism and immutability</h3> * * <dl> * <dt>{@link org.plumelib.util.DeterministicObject DeterministicObject} * <dd>A version of {@code Object} with a deterministic {@code hashCode()} method. Instantiate * this instead of {@code Object} to remove a source of nondeterminism from your programs. * <dt>{@link org.plumelib.util.ClassDeterministic ClassDeterministic} * <dd>Deterministic versions of {@code java.lang.Class} methods, which return arrays in sorted * order. * <dt>{@link org.plumelib.util.ClassDeterministic UniqueId} * <dd>An interface for objects that have a unique ID. If you are tempted to print the value of * {@code System.identityHashCode()}, consider using this instead. * <dt>{@link org.plumelib.util.ClassDeterministic UniqueIdMap} * <dd>Provides a unique ID (like the {@link org.plumelib.util.ClassDeterministic UniqueId} class) * for classes that you cannot modify. * <dt>{@link org.plumelib.util.ImmutableTypes ImmutableTypes} * <dd>Indicates which types in the JDK are immutable. * </dl> * * <h3 id="interfaces">Utility interfaces</h3> * * <dl> * <dt>{@link org.plumelib.util.Filter Filter} * <dd>Interface for things that make boolean decisions. This is inspired by {@code * java.io.FilenameFilter}. * <dt>{@link org.plumelib.util.Partitioner Partitioner} * <dd>A Partitioner accepts Objects and assigns them to an equivalence class. * </dl> * * <h3 id="system">JVM runtime system</h3> * * <dl> * <dt>{@link org.plumelib.util.DumpHeap DumpHeap} * <dd>Dumps the heap into a {@code .hprof} file. * <dt>{@link org.plumelib.util.SystemPlume SystemPlume} * <dd>Utility methods relating to the JVM runtime system: sleep and garbage collection. * </dl> * * <h3 id="miscellaneous">Miscellaneous</h3> * * <dl> * <dt>{@link org.plumelib.util.GraphPlume GraphPlume} * <dd>Graph utility methods. This class does not model a graph: all methods are static. * <dt>{@link org.plumelib.util.Intern Intern} * <dd>Utilities for interning objects. Interning is also known as canonicalization or * hash-consing: it returns a single representative object that {@code .equals()} the object, * and the client discards the argument and uses the result instead. * <dt>{@link org.plumelib.util.Pair Pair} * <dd>Mutable pair class: type-safely holds two objects of possibly-different types. * <dt>{@link org.plumelib.util.WeakIdentityPair WeakIdentityPair} * <dd>Immutable pair class: type-safely holds two objects of possibly-different types. Differs * from {@code Pair} in the following ways: is immutable, cannot hold null, holds its elements * with weak pointers, and its equals() method uses object equality to compare its elements. * <dt>{@link org.plumelib.util.UtilPlume UtilPlume} * <dd>Utility methods that do not belong elsewhere in the plume package: BitSet; File; * directories; file names; reading and writing; hashing; ProcessBuilder; properties; Stream; * Throwable. * </dl> */ package org.plumelib.util;
package org.nakedobjects.object.reflect; import org.nakedobjects.object.NakedObjectSpecification; import org.nakedobjects.object.NakedObjects; /** * Details the intial states of, and the labels for, the parameters for an * action method. */ public class ActionParameterSetImpl implements org.nakedobjects.object.ActionParameterSet { private final Object[] defaultValues; private final String[] labels; private final boolean[] required; private Object[][] options; public ActionParameterSetImpl(final Object[] defaultValues, final Object[][] options, final String[] labels, final boolean[] required) { this(defaultValues, labels, required); this.options = options; } public ActionParameterSetImpl(final Object[] defaultValues, final String[] labels, final boolean[] required) { super(); this.defaultValues = defaultValues; this.labels = labels; this.required = required; } public Object[] getDefaultParameterValues() { return defaultValues; } public Object[][] getOptions() { return options; } public String[] getParameterLabels() { return labels; } public boolean[] getRequiredParameters() { return required; } public void checkParameters(String name, NakedObjectSpecification requiredTypes[]) { for (int i = 0; i < requiredTypes.length; i++) { NakedObjectSpecification specification = requiredTypes[i]; if(defaultValues[i] == null) { continue; } NakedObjectSpecification parameterSpec = NakedObjects.getSpecificationLoader().loadSpecification( defaultValues[i].getClass()); if (!parameterSpec.isOfType(specification)) { throw new ReflectionException("Parameter " + (i + 1) + " in " + name + " is not of required type; expected type " + specification.getFullName() + " but got " + parameterSpec.getFullName() + ". Check the related about method"); } } } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.text.ParseException; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.util.Dates; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Defines a recurrence. * @version 2.0 * @author Ben Fortuna */ public class Recur implements Serializable { private static final long serialVersionUID = -7333226591784095142L; private static final String FREQ = "FREQ"; private static final String UNTIL = "UNTIL"; private static final String COUNT = "COUNT"; private static final String INTERVAL = "INTERVAL"; private static final String BYSECOND = "BYSECOND"; private static final String BYMINUTE = "BYMINUTE"; private static final String BYHOUR = "BYHOUR"; private static final String BYDAY = "BYDAY"; private static final String BYMONTHDAY = "BYMONTHDAY"; private static final String BYYEARDAY = "BYYEARDAY"; private static final String BYWEEKNO = "BYWEEKNO"; private static final String BYMONTH = "BYMONTH"; private static final String BYSETPOS = "BYSETPOS"; private static final String WKST = "WKST"; // frequencies.. public static final String SECONDLY = "SECONDLY"; public static final String MINUTELY = "MINUTELY"; public static final String HOURLY = "HOURLY"; public static final String DAILY = "DAILY"; public static final String WEEKLY = "WEEKLY"; public static final String MONTHLY = "MONTHLY"; public static final String YEARLY = "YEARLY"; private static Log log = LogFactory.getLog(Recur.class); private String frequency; private Date until; private int count = -1; private int interval = -1; private NumberList secondList; private NumberList minuteList; private NumberList hourList; private WeekDayList dayList; private NumberList monthDayList; private NumberList yearDayList; private NumberList weekNoList; private NumberList monthList; private NumberList setPosList; private String weekStartDay; private Map experimentalValues = new HashMap(); /** * Constructs a new instance from the specified string value. * @param aValue * a string representation of a recurrence. * @throws ParseException * thrown when the specified string contains an invalid * representation of an UNTIL date value */ public Recur(final String aValue) throws ParseException { for (StringTokenizer t = new StringTokenizer(aValue, ";="); t .hasMoreTokens();) { String token = t.nextToken(); if (FREQ.equals(token)) { frequency = t.nextToken(); } else if (UNTIL.equals(token)) { String untilString = t.nextToken(); try { until = new DateTime(untilString); // UNTIL must be specified in UTC time.. ((DateTime) until).setUtc(true); } catch (ParseException pe) { until = new Date(untilString); } } else if (COUNT.equals(token)) { count = Integer.parseInt(t.nextToken()); } else if (INTERVAL.equals(token)) { interval = Integer.parseInt(t.nextToken()); } else if (BYSECOND.equals(token)) { secondList = new NumberList(t.nextToken()); } else if (BYMINUTE.equals(token)) { minuteList = new NumberList(t.nextToken()); } else if (BYHOUR.equals(token)) { hourList = new NumberList(t.nextToken()); } else if (BYDAY.equals(token)) { dayList = new WeekDayList(t.nextToken()); } else if (BYMONTHDAY.equals(token)) { monthDayList = new NumberList(t.nextToken()); } else if (BYYEARDAY.equals(token)) { yearDayList = new NumberList(t.nextToken()); } else if (BYWEEKNO.equals(token)) { weekNoList = new NumberList(t.nextToken()); } else if (BYMONTH.equals(token)) { monthList = new NumberList(t.nextToken()); } else if (BYSETPOS.equals(token)) { setPosList = new NumberList(t.nextToken()); } else if (WKST.equals(token)) { weekStartDay = t.nextToken(); } // assume experimental value.. else { experimentalValues.put(token, t.nextToken()); } } } /** * @param frequency * @param until */ public Recur(final String frequency, final Date until) { this.frequency = frequency; this.until = until; } /** * @param frequency * @param count */ public Recur(final String frequency, final int count) { this.frequency = frequency; this.count = count; } /** * @return Returns the dayList. */ public final WeekDayList getDayList() { if (dayList == null) { dayList = new WeekDayList(); } return dayList; } /** * @return Returns the hourList. */ public final NumberList getHourList() { if (hourList == null) { hourList = new NumberList(); } return hourList; } /** * @return Returns the minuteList. */ public final NumberList getMinuteList() { if (minuteList == null) { minuteList = new NumberList(); } return minuteList; } /** * @return Returns the monthDayList. */ public final NumberList getMonthDayList() { if (monthDayList == null) { monthDayList = new NumberList(); } return monthDayList; } /** * @return Returns the monthList. */ public final NumberList getMonthList() { if (monthList == null) { monthList = new NumberList(); } return monthList; } /** * @return Returns the secondList. */ public final NumberList getSecondList() { if (secondList == null) { secondList = new NumberList(); } return secondList; } /** * @return Returns the setPosList. */ public final NumberList getSetPosList() { if (setPosList == null) { setPosList = new NumberList(); } return setPosList; } /** * @return Returns the weekNoList. */ public final NumberList getWeekNoList() { if (weekNoList == null) { weekNoList = new NumberList(); } return weekNoList; } /** * @return Returns the yearDayList. */ public final NumberList getYearDayList() { if (yearDayList == null) { yearDayList = new NumberList(); } return yearDayList; } /** * @return Returns the count. */ public final int getCount() { return count; } /** * @return Returns the experimentalValues. */ public final Map getExperimentalValues() { return experimentalValues; } /** * @return Returns the frequency. */ public final String getFrequency() { return frequency; } /** * @return Returns the interval. */ public final int getInterval() { return interval; } /** * @return Returns the until. */ public final Date getUntil() { return until; } /** * @return Returns the weekStartDay. */ public final String getWeekStartDay() { return weekStartDay; } /** * @param weekStartDay The weekStartDay to set. */ public final void setWeekStartDay(final String weekStartDay) { this.weekStartDay = weekStartDay; } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); b.append(FREQ); b.append('='); b.append(frequency); if (weekStartDay != null) { b.append(';'); b.append(WKST); b.append('='); b.append(weekStartDay); } if (interval >= 1) { b.append(';'); b.append(INTERVAL); b.append('='); b.append(interval); } if (until != null) { b.append(';'); b.append(UNTIL); b.append('='); // Note: date-time representations should always be in UTC time. b.append(until); } if (count >= 1) { b.append(';'); b.append(COUNT); b.append('='); b.append(count); } if (!getMonthList().isEmpty()) { b.append(';'); b.append(BYMONTH); b.append('='); b.append(monthList); } if (!getWeekNoList().isEmpty()) { b.append(';'); b.append(BYWEEKNO); b.append('='); b.append(weekNoList); } if (!getYearDayList().isEmpty()) { b.append(';'); b.append(BYYEARDAY); b.append('='); b.append(yearDayList); } if (!getMonthDayList().isEmpty()) { b.append(';'); b.append(BYMONTHDAY); b.append('='); b.append(monthDayList); } if (!getDayList().isEmpty()) { b.append(';'); b.append(BYDAY); b.append('='); b.append(dayList); } if (!getHourList().isEmpty()) { b.append(';'); b.append(BYHOUR); b.append('='); b.append(hourList); } if (!getMinuteList().isEmpty()) { b.append(';'); b.append(BYMINUTE); b.append('='); b.append(minuteList); } if (!getSecondList().isEmpty()) { b.append(';'); b.append(BYSECOND); b.append('='); b.append(secondList); } if (!getSetPosList().isEmpty()) { b.append(';'); b.append(BYSETPOS); b.append('='); b.append(setPosList); } return b.toString(); } /** * Returns a list of start dates in the specified period represented by this recur. * Any date fields not specified by this recur are retained from the period start, * and as such you should ensure the period start is initialised correctly. * @param periodStart the start of the period * @param periodEnd the end of the period * @param value the type of dates to generate (i.e. date/date-time) * @return a list of dates */ public final DateList getDates(final Date periodStart, final Date periodEnd, final Value value) { return getDates(periodStart, periodStart, periodEnd, value); } /** * Returns a list of start dates in the specified period represented * by this recur. This method includes a base date argument, which * indicates the start of the fist occurrence of this recurrence. * * The base date is used to inject default values to return a set of dates in * the correct format. For example, if the search start date (start) is * Wed, Mar 23, 12:19PM, but the recurrence is Mon - Fri, 9:00AM - 5:00PM, * the start dates returned should all be at 9:00AM, and not 12:19PM. * * @return a list of dates represented by this recur instance * @param base the start date of this Recurrence's first instance * @param periodStart the start of the period * @param periodEnd the end of the period * @param value the type of dates to generate (i.e. date/date-time) */ public final DateList getDates(final Date seed, final Date periodStart, final Date periodEnd, final Value value) { DateList dates = new DateList(value); if ((seed instanceof DateTime) && ((DateTime) seed).isUtc()) { dates.setUtc(true); } Calendar cal = Dates.getCalendarInstance(seed); cal.setTime(seed); int invalidCandidateCount = 0; while (!((getUntil() != null && cal.getTime().after(getUntil())) || (periodEnd != null && cal.getTime().after(periodEnd)) || (getCount() >= 1 && (dates.size() + invalidCandidateCount) >= getCount()))) { DateList candidates = getCandidates(Dates.getInstance(cal.getTime(), value), value); for (Iterator i = candidates.iterator(); i.hasNext();) { Date candidate = (Date) i.next(); // don't count candidates that occur before the seed date.. if (!candidate.before(seed)) { // candidates exclusive of periodEnd.. if (candidate.before(periodStart) || !candidate.before(periodEnd)) { invalidCandidateCount++; } else if (getCount() >= 1 && (dates.size() + invalidCandidateCount) >= getCount()) { break; } else if (!(getUntil() != null && candidate.after(getUntil()))) { dates.add(candidate); } } } increment(cal); } // sort final list.. Collections.sort(dates); return dates; } /** * Increments the specified calendar according to the * frequency and interval specified in this recurrence * rule. * @param cal a java.util.Calendar to increment */ private void increment(final Calendar cal) { // initialise interval.. int calInterval = (getInterval() >= 1) ? getInterval() : 1; if (SECONDLY.equals(getFrequency())) { cal.add(Calendar.SECOND, calInterval); } else if (MINUTELY.equals(getFrequency())) { cal.add(Calendar.MINUTE, calInterval); } else if (HOURLY.equals(getFrequency())) { cal.add(Calendar.HOUR_OF_DAY, calInterval); } else if (DAILY.equals(getFrequency())) { cal.add(Calendar.DAY_OF_YEAR, calInterval); } else if (WEEKLY.equals(getFrequency())) { cal.add(Calendar.WEEK_OF_YEAR, calInterval); } else if (MONTHLY.equals(getFrequency())) { cal.add(Calendar.MONTH, calInterval); } else if (YEARLY.equals(getFrequency())) { cal.add(Calendar.YEAR, calInterval); } } /** * Returns a list of possible dates generated from the applicable * BY* rules, using the specified date as a seed. * @param date the seed date * @param value the type of date list to return * @return a DateList */ private DateList getCandidates(final Date date, final Value value) { DateList dates = new DateList(value); dates.add(date); dates = getMonthVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMONTH processing: " + dates); } dates = getWeekNoVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYWEEKNO processing: " + dates); } dates = getYearDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYYEARDAY processing: " + dates); } dates = getMonthDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMONTHDAY processing: " + dates); } dates = getDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYDAY processing: " + dates); } dates = getHourVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYHOUR processing: " + dates); } dates = getMinuteVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMINUTE processing: " + dates); } dates = getSecondVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYSECOND processing: " + dates); } dates = applySetPosRules(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after SETPOS processing: " + dates); } return dates; } /** * Applies BYSETPOS rules to <code>dates</code>. Valid positions are from * 1 to the size of the date list. Invalid positions are ignored. * * @param dates */ private DateList applySetPosRules(final DateList dates) { // return if no SETPOS rules specified.. if (getSetPosList().isEmpty()) { return dates; } // sort the list before processing.. Collections.sort(dates); DateList setPosDates = new DateList(dates.getType()); int size = dates.size(); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); int pos = setPos.intValue(); if (pos > 0 && pos <= size) { setPosDates.add(dates.get(pos - 1)); } else if (pos < 0 && pos >= -size) { setPosDates.add(dates.get(size + pos)); } } return setPosDates; } /** * Applies BYMONTH rules specified in this Recur instance to the * specified date list. If no BYMONTH rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMonthVariants(final DateList dates) { if (getMonthList().isEmpty()) { return dates; } DateList monthlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getMonthList().iterator(); j.hasNext();) { Integer month = (Integer) j.next(); // Java months are zero-based.. cal.set(Calendar.MONTH, month.intValue() - 1); monthlyDates.add(Dates.getInstance(cal.getTime(), monthlyDates.getType())); } } return monthlyDates; } /** * Applies BYWEEKNO rules specified in this Recur instance to the * specified date list. If no BYWEEKNO rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getWeekNoVariants(final DateList dates) { if (getWeekNoList().isEmpty()) { return dates; } DateList weekNoDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getWeekNoList().iterator(); j.hasNext();) { Integer weekNo = (Integer) j.next(); cal.set(Calendar.WEEK_OF_YEAR, Dates.getAbsWeekNo(cal.getTime(), weekNo.intValue())); weekNoDates.add(Dates.getInstance(cal.getTime(), weekNoDates.getType())); } } return weekNoDates; } /** * Applies BYYEARDAY rules specified in this Recur instance to the * specified date list. If no BYYEARDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getYearDayVariants(final DateList dates) { if (getYearDayList().isEmpty()) { return dates; } DateList yearDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getYearDayList().iterator(); j.hasNext();) { Integer yearDay = (Integer) j.next(); cal.set(Calendar.DAY_OF_YEAR, Dates.getAbsYearDay(cal.getTime(), yearDay.intValue())); yearDayDates.add(Dates.getInstance(cal.getTime(), yearDayDates.getType())); } } return yearDayDates; } /** * Applies BYMONTHDAY rules specified in this Recur instance to the * specified date list. If no BYMONTHDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMonthDayVariants(final DateList dates) { if (getMonthDayList().isEmpty()) { return dates; } DateList monthDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getMonthDayList().iterator(); j.hasNext();) { Integer monthDay = (Integer) j.next(); cal.set(Calendar.DAY_OF_MONTH, Dates.getAbsMonthDay(cal.getTime(), monthDay.intValue())); monthDayDates.add(Dates.getInstance(cal.getTime(), monthDayDates.getType())); } } return monthDayDates; } /** * Applies BYDAY rules specified in this Recur instance to the * specified date list. If no BYDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getDayVariants(final DateList dates) { if (getDayList().isEmpty()) { return dates; } DateList weekDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); for (Iterator j = getDayList().iterator(); j.hasNext();) { WeekDay weekDay = (WeekDay) j.next(); weekDayDates.addAll(getAbsWeekDays(date, dates.getType(), weekDay)); } } return weekDayDates; } /** * Returns a list of applicable dates corresponding to the specified * week day in accordance with the frequency specified by this recurrence * rule. * @param date * @param weekDay * @return */ private List getAbsWeekDays(final Date date, final Value type, final WeekDay weekDay) { Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); DateList days = new DateList(type); int calDay = WeekDay.getCalendarDay(weekDay); if (calDay == -1) { // a matching weekday cannot be identified.. return days; } if (DAILY.equals(getFrequency())) { if (cal.get(Calendar.DAY_OF_WEEK) == calDay) { days.add(Dates.getInstance(cal.getTime(), type)); } } else if (WEEKLY.equals(getFrequency()) || !getWeekNoList().isEmpty()) { //int weekNo = cal.get(Calendar.WEEK_OF_YEAR); // construct a list of possible week days.. // cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_WEEK, 1); } int weekNo = cal.get(Calendar.WEEK_OF_YEAR); while (cal.get(Calendar.WEEK_OF_YEAR) == weekNo) { days.add(Dates.getInstance(cal.getTime(), type)); cal.add(Calendar.DAY_OF_WEEK, Dates.DAYS_PER_WEEK); } } else if (MONTHLY.equals(getFrequency()) || !getMonthList().isEmpty()) { int month = cal.get(Calendar.MONTH); // construct a list of possible month days.. cal.set(Calendar.DAY_OF_MONTH, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_MONTH, 1); } while (cal.get(Calendar.MONTH) == month) { days.add(Dates.getInstance(cal.getTime(), type)); cal.add(Calendar.DAY_OF_MONTH, Dates.DAYS_PER_WEEK); } } else if (YEARLY.equals(getFrequency())) { int year = cal.get(Calendar.YEAR); // construct a list of possible year days.. cal.set(Calendar.DAY_OF_YEAR, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_YEAR, 1); } while (cal.get(Calendar.YEAR) == year) { days.add(Dates.getInstance(cal.getTime(), type)); cal.add(Calendar.DAY_OF_YEAR, Dates.DAYS_PER_WEEK); } } DateList weekDays = new DateList(days.getType()); sublist(days, weekDay.getOffset(), weekDays); return weekDays; } /** * Returns a single-element sublist containing the element of * <code>list</code> at <code>offset</code>. Valid offsets are from 1 * to the size of the list. If an invalid offset is supplied, all elements * from <code>list</code> are added to <code>sublist</code>. * * @param list * @param offset * @param sublist */ private void sublist(final List list, final int offset, final List sublist) { int size = list.size(); if (offset < 0 && offset >= -size) { sublist.add(list.get(size + offset)); } else if (offset > 0 && offset <= size) { sublist.add(list.get(offset - 1)); } else { sublist.addAll(list); } } /** * Applies BYHOUR rules specified in this Recur instance to the specified * date list. If no BYHOUR rules are specified the date list is returned * unmodified. * * @param dates * @return */ private DateList getHourVariants(final DateList dates) { if (getHourList().isEmpty()) { return dates; } DateList hourlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getHourList().iterator(); j.hasNext();) { Integer hour = (Integer) j.next(); cal.set(Calendar.HOUR_OF_DAY, hour.intValue()); hourlyDates.add(Dates.getInstance(cal.getTime(), hourlyDates.getType())); } } return hourlyDates; } /** * Applies BYMINUTE rules specified in this Recur instance to the * specified date list. If no BYMINUTE rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMinuteVariants(final DateList dates) { if (getMinuteList().isEmpty()) { return dates; } DateList minutelyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getMinuteList().iterator(); j.hasNext();) { Integer minute = (Integer) j.next(); cal.set(Calendar.MINUTE, minute.intValue()); minutelyDates.add(Dates.getInstance(cal.getTime(), minutelyDates.getType())); } } return minutelyDates; } /** * Applies BYSECOND rules specified in this Recur instance to the * specified date list. If no BYSECOND rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getSecondVariants(final DateList dates) { if (getSecondList().isEmpty()) { return dates; } DateList secondlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); Calendar cal = Dates.getCalendarInstance(date); cal.setTime(date); for (Iterator j = getSecondList().iterator(); j.hasNext();) { Integer second = (Integer) j.next(); cal.set(Calendar.SECOND, second.intValue()); secondlyDates.add(Dates.getInstance(cal.getTime(), secondlyDates.getType())); } } return secondlyDates; } /** * @param count The count to set. */ public final void setCount(final int count) { this.count = count; this.until = null; } /** * @param frequency The frequency to set. */ public final void setFrequency(final String frequency) { this.frequency = frequency; } /** * @param interval The interval to set. */ public final void setInterval(final int interval) { this.interval = interval; } /** * @param until The until to set. */ public final void setUntil(final Date until) { this.until = until; this.count = -1; } }
package org.usfirst.frc.team4828; public class Ports { // PWM public static final int INTAKE = 9; public static final int CLIMBER_1 = 8; public static final int CLIMBER_2 = 7; public static final int AGITATOR = 6; // Drivetrain public static final int DT_FRONT_LEFT = 1; public static final int DT_BACK_LEFT = 2; public static final int DT_FRONT_RIGHT = 3; public static final int DT_BACK_RIGHT = 4; // Shooter public static final int SERVO_LEFT_MASTER = 3; public static final int SERVO_LEFT_SLAVE = 2; public static final int SERVO_RIGHT_MASTER = 0; public static final int SERVO_RIGHT_SLAVE = 1; public static final int MOTOR_LEFT = 5; public static final int MOTOR_RIGHT = 6; public static final int INDEXER_RIGHT = 10; // use port 0 on the navx as port 10 public static final int INDEXER_LEFT = 11; // use port 1 on the navx as port 11 // Sensors public static final int US_CHANNEL = 0; // Analog public static final int HALLEFFECT_PORT = 1; // Switch public static final int DIPSWITCH_1 = 6; public static final int DIPSWITCH_2 = 5; public static final int DIPSWITCH_3 = 4; public static final int DIPSWITCH_4 = 3; public static final int LEFT_GEAR_GOBBLER = 4; public static final int RIGHT_GEAR_GOBBLER = 5; public static final int PUSH_GEAR_GOBBLER = 19; private Ports() { throw new InstantiationError ("This is a static class, why are you trying to instantiate it"); } }
package com.siberia.plugin; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.os.Message; import android.util.Log; import android.net.nsd.NsdServiceInfo; import com.siberia.plugin.NsdHelper; public class Discovery extends CordovaPlugin { public static final String TAG = "Discovery"; NsdHelper mNsdHelper; private Handler mHandler; // ChatConnection mConnection; // CallbackContextHandler ccHandler; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("initChat")) { Log.d(TAG, "initChat"); // this.initChat(callbackContext); } else if (action.equals("advertizeChat")) { Log.d(TAG, "advertizeChat"); // this.advertizeChat(callbackContext); } else if (action.equals("identify")) { Log.d(TAG, "identify"); this.discoverServices(callbackContext); } else if (action.equals("connectChat")) { Log.d(TAG, "connectChat"); // this.connectChat(callbackContext); } else if (action.equals("sendChatMessage")) { Log.d(TAG, "sendChatMessage"); // String messageString = args.getString(0); // this.sendChatMessage(callbackContext, messageString); } else { callbackContext.error(String.format("Discovery - invalid action:", action)); return false; } // PluginResult.Status status = PluginResult.Status.NO_RESULT; // PluginResult pluginResult = new PluginResult(status); // pluginResult.setKeepCallback(true); // callbackContext.sendPluginResult(pluginResult); return true; } // private void initChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // try { // mHandler = new Handler() { // @Override // public void handleMessage(Message msg) { // String type = msg.getData().getString("type"); // String message = msg.getData().getString("msg"); // JSONObject data = new JSONObject(); // try { // data.put("type", new String(type)); // data.put("data", new String(message)); // } catch(JSONException e) { // PluginResult result = new PluginResult(PluginResult.Status.OK, data); // result.setKeepCallback(true); // cbc.sendPluginResult(result); // // mConnection = new ChatConnection(ccHandler); // mConnection = new ChatConnection(mHandler); // // mNsdHelper = new NsdHelper(cordova.getActivity(), ccHandler); // mNsdHelper = new NsdHelper(cordova.getActivity(), mHandler); // mNsdHelper.initializeNsd(); // } catch(Exception e) { // callbackContext.error("Error " + e); // private void advertizeChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // if(mConnection.getLocalPort() > -1) { // mNsdHelper.registerService(mConnection.getLocalPort()); // } else { // cbc.error("ServerSocket isn't bound."); private void identify(CallbackContext callbackContext) { final CallbackContext cbc = callbackContext; mNsdHelper.discoverServices(); } // private void connectChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // NsdServiceInfo service = mNsdHelper.getChosenServiceInfo(); // if (service != null) { // mConnection.connectToServer(service.getHost(), // service.getPort()); // } else { // cbc.error("No service to connect to!"); // private void sendChatMessage(CallbackContext callbackContext, String messageString) { // mConnection.sendMessage(messageString); }
package org.jfree.chart.axis; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.util.ParamChecks; import org.jfree.ui.RectangleEdge; import org.jfree.util.PublicCloneable; /** * A record that contains the space required at each edge of a plot. */ public class AxisSpace implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2490732595134766305L; /** The top space. */ private double top; /** The bottom space. */ private double bottom; /** The left space. */ private double left; /** The right space. */ private double right; /** * Creates a new axis space record. */ public AxisSpace() { this.top = 0.0; this.bottom = 0.0; this.left = 0.0; this.right = 0.0; } /** * Returns the space reserved for axes at the top of the plot area. * * @return The space (in Java2D units). */ public double getTop() { return this.top; } /** * Sets the space reserved for axes at the top of the plot area. * * @param space the space (in Java2D units). */ public void setTop(double space) { this.top = space; } /** * Returns the space reserved for axes at the bottom of the plot area. * * @return The space (in Java2D units). */ public double getBottom() { return this.bottom; } /** * Sets the space reserved for axes at the bottom of the plot area. * * @param space the space (in Java2D units). */ public void setBottom(double space) { this.bottom = space; } /** * Returns the space reserved for axes at the left of the plot area. * * @return The space (in Java2D units). */ public double getLeft() { return this.left; } /** * Sets the space reserved for axes at the left of the plot area. * * @param space the space (in Java2D units). */ public void setLeft(double space) { this.left = space; } /** * Returns the space reserved for axes at the right of the plot area. * * @return The space (in Java2D units). */ public double getRight() { return this.right; } /** * Sets the space reserved for axes at the right of the plot area. * * @param space the space (in Java2D units). */ public void setRight(double space) { this.right = space; } /** * Adds space to the top, bottom, left or right edge of the plot area. * * @param space the space (in Java2D units). * @param edge the edge (<code>null</code> not permitted). */ public void add(double space, RectangleEdge edge) { ParamChecks.nullNotPermitted(edge, "edge"); if (edge == RectangleEdge.TOP) { this.top += space; } else if (edge == RectangleEdge.BOTTOM) { this.bottom += space; } else if (edge == RectangleEdge.LEFT) { this.left += space; } else if (edge == RectangleEdge.RIGHT) { this.right += space; } else { throw new IllegalStateException("Unrecognised 'edge' argument."); } } /** * Ensures that this object reserves at least as much space as another. * * @param space the other space. */ public void ensureAtLeast(AxisSpace space) { this.top = Math.max(this.top, space.top); this.bottom = Math.max(this.bottom, space.bottom); this.left = Math.max(this.left, space.left); this.right = Math.max(this.right, space.right); } /** * Ensures there is a minimum amount of space at the edge corresponding to * the specified axis location. * * @param space the space. * @param edge the location. */ public void ensureAtLeast(double space, RectangleEdge edge) { if (edge == RectangleEdge.TOP) { if (this.top < space) { this.top = space; } } else if (edge == RectangleEdge.BOTTOM) { if (this.bottom < space) { this.bottom = space; } } else if (edge == RectangleEdge.LEFT) { if (this.left < space) { this.left = space; } } else if (edge == RectangleEdge.RIGHT) { if (this.right < space) { this.right = space; } } else { throw new IllegalStateException( "AxisSpace.ensureAtLeast(): unrecognised AxisLocation." ); } } /** * Shrinks an area by the space attributes. * * @param area the area to shrink. * @param result an optional carrier for the result. * * @return The result. */ public Rectangle2D shrink(Rectangle2D area, Rectangle2D result) { if (result == null) { result = new Rectangle2D.Double(); } result.setRect( area.getX() + this.left, area.getY() + this.top, area.getWidth() - this.left - this.right, area.getHeight() - this.top - this.bottom ); return result; } /** * Expands an area by the amount of space represented by this object. * * @param area the area to expand. * @param result an optional carrier for the result. * * @return The result. */ public Rectangle2D expand(Rectangle2D area, Rectangle2D result) { if (result == null) { result = new Rectangle2D.Double(); } result.setRect( area.getX() - this.left, area.getY() - this.top, area.getWidth() + this.left + this.right, area.getHeight() + this.top + this.bottom ); return result; } /** * Calculates the reserved area. * * @param area the area. * @param edge the edge. * * @return The reserved area. */ public Rectangle2D reserved(Rectangle2D area, RectangleEdge edge) { Rectangle2D result = null; if (edge == RectangleEdge.TOP) { result = new Rectangle2D.Double( area.getX(), area.getY(), area.getWidth(), this.top ); } else if (edge == RectangleEdge.BOTTOM) { result = new Rectangle2D.Double( area.getX(), area.getMaxY() - this.top, area.getWidth(), this.bottom ); } else if (edge == RectangleEdge.LEFT) { result = new Rectangle2D.Double( area.getX(), area.getY(), this.left, area.getHeight() ); } else if (edge == RectangleEdge.RIGHT) { result = new Rectangle2D.Double( area.getMaxX() - this.right, area.getY(), this.right, area.getHeight() ); } return result; } /** * Returns a clone of the object. * * @return A clone. * * @throws CloneNotSupportedException This class won't throw this exception, * but subclasses (if any) might. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests this object for equality with another object. * * @param obj the object to compare against. * * @return <code>true</code> or <code>false</code>. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AxisSpace)) { return false; } AxisSpace that = (AxisSpace) obj; if (this.top != that.top) { return false; } if (this.bottom != that.bottom) { return false; } if (this.left != that.left) { return false; } if (this.right != that.right) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { int result = 23; long l = Double.doubleToLongBits(this.top); result = 37 * result + (int) (l ^ (l >>> 32)); l = Double.doubleToLongBits(this.bottom); result = 37 * result + (int) (l ^ (l >>> 32)); l = Double.doubleToLongBits(this.left); result = 37 * result + (int) (l ^ (l >>> 32)); l = Double.doubleToLongBits(this.right); result = 37 * result + (int) (l ^ (l >>> 32)); return result; } /** * Returns a string representing the object (for debugging purposes). * * @return A string. */ public String toString() { return super.toString() + "[left=" + this.left + ",right=" + this.right + ",top=" + this.top + ",bottom=" + this.bottom + "]"; } }
package org.util.concurrent.futures; import java.util.ArrayDeque; import java.util.List; import java.util.Queue; import java.util.concurrent.*; import java.util.function.BiFunction; import java.util.function.Supplier; /** * @author ahmad */ public final class Do { private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final ThreadFactory DEFAULT_THREAD_FACTORY = Executors.defaultThreadFactory(); private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CPU_COUNT + 1, CPU_COUNT * 4 + 1, 15L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> { Thread t = DEFAULT_THREAD_FACTORY.newThread(r); t.setDaemon(true); return t; }); private static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static final class SerialExecutor implements Executor { private final Queue<Runnable> tasks = new ArrayDeque<>(); private Runnable activeTask; public synchronized void execute(final Runnable r) { tasks.offer(() -> { try { r.run(); } finally { scheduleNext(); } }); if (activeTask == null) { scheduleNext(); } } private synchronized void scheduleNext() { if ((activeTask = tasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(activeTask); } } } public static void executeSerial(Runnable runnable) { SERIAL_EXECUTOR.execute(runnable); } public static void executeAsync(Runnable runnable) { THREAD_POOL_EXECUTOR.execute(runnable); } public static Promise<Void> runSerial(Runnable runnable) { return new PromiseImpl<>(CompletableFuture.runAsync(runnable, SERIAL_EXECUTOR)); } public static Promise<Void> runAsync(Runnable runnable) { return new PromiseImpl<>(CompletableFuture.runAsync(runnable, THREAD_POOL_EXECUTOR)); } public static <V> Promise<V> supplySerial(Supplier<V> supplier) { return new PromiseImpl<>(CompletableFuture.supplyAsync(supplier, SERIAL_EXECUTOR)); } public static <V> Promise<V> supplyAsync(Supplier<V> supplier) { return new PromiseImpl<>(CompletableFuture.supplyAsync(supplier, THREAD_POOL_EXECUTOR)); } public static <V> Promise<V> combine(List<? extends Promise<? extends V>> promises, BiFunction<? super V, ? super V, ? extends V> combiner) { if (promises.isEmpty()) { return new PromiseImpl<>(new CompletableFuture<>()); } CompletableFuture<V> future = null; for (Promise<? extends V> promise : promises) { @SuppressWarnings("unchecked") CompletableFuture<V> d = ((PromiseImpl) promise).delegate; future = future == null ? d : future.thenCombine(d, combiner); } return new PromiseImpl<>(future); } public static Promise<Void> combine(List<? extends Promise<? extends Void>> promises) { if (promises.isEmpty()) { return new PromiseImpl<>(new CompletableFuture<>()); } CompletableFuture[] futures = new CompletableFuture[promises.size()]; for (int i = 0, n = promises.size(); i < n; i++) { futures[i] = ((PromiseImpl) promises.get(i)).delegate; } return new PromiseImpl<>(CompletableFuture.allOf(futures)); } }
package org.jfree.chart.axis; import org.jfree.ui.TextAnchor; /** * A value tick. */ public abstract class ValueTick extends Tick { /** The value. */ private double value; /** * The tick type (major or minor). * * @since 1.0.7 */ private TickType tickType; /** * Creates a new value tick. * * @param value the value. * @param label the label. * @param textAnchor the part of the label that is aligned to the anchor * point. * @param rotationAnchor defines the rotation point relative to the label. * @param angle the rotation angle (in radians). */ public ValueTick(double value, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle) { this(TickType.MAJOR, value, label, textAnchor, rotationAnchor, angle); this.value = value; } /** * Creates a new value tick. * * @param tickType the tick type (major or minor, <code>null</code> not * permitted). * @param value the value. * @param label the label. * @param textAnchor the part of the label that is aligned to the anchor * point. * @param rotationAnchor defines the rotation point relative to the label. * @param angle the rotation angle (in radians). * * @since 1.0.7 */ public ValueTick(TickType tickType, double value, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle) { super(label, textAnchor, rotationAnchor, angle); this.value = value; this.tickType = tickType; } /** * Returns the value. * * @return The value. */ public double getValue() { return this.value; } /** * Returns the tick type (major or minor). * * @return The tick type. * * @since 1.0.7 */ public TickType getTickType() { return this.tickType; } /** * Tests this tick for equality with an arbitrary object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ValueTick)) { return false; } ValueTick that = (ValueTick) obj; if (this.value != that.value) { return false; } if (!this.tickType.equals(that.tickType)) { return false; } return super.equals(obj); } }
package org.vietabroader.view; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vietabroader.GoogleAPIUtils; import org.vietabroader.controller.AuthenticationController; import org.vietabroader.controller.SpreadsheetConnectController; import org.vietabroader.model.GlobalState; import org.vietabroader.model.VASpreadsheet; import org.vietabroader.view.verifier.ColumnVerifier; import org.vietabroader.view.verifier.RowVerifier; import javax.swing.*; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.MatteBorder; import javax.swing.border.TitledBorder; import java.awt.*; import java.net.URI; import java.util.List; import java.util.Observer; import java.util.Observable; /* Main view of the app. This view observes the changes in GlobalState singleton. Prefix rules: btn: JButton lbl: JLabel txt: JTextField spn: JSpinner cbb: JComboBox pan: JPanel prg: JProgressBar */ public class MainView extends JFrame implements Observer { /** * Panel with title */ private static class TitledPanel extends JPanel { private TitledPanel(String title) { this.setLayout(new GridBagLayout()); this.setBorder(new CompoundBorder( new TitledBorder(title), new EmptyBorder(8, 2, 8, 2)) // Inner padding of each panel ); } } /** * This label cuts off text that is too long. Full text can be seen in tooltip. */ private static class MessageLabel extends JLabel { private final int CUT_OFF = 60; MessageLabel(String text) { super(text); } @Override public void setText(String text) { String cutOff = text; if (cutOff.length() > CUT_OFF) { cutOff = cutOff.substring(0, CUT_OFF) + "..."; } super.setText(cutOff); setToolTipText(text); } } private static final Logger logger = LoggerFactory.getLogger(GoogleAPIUtils.class); private final String QR_GENERATOR_URL = "https://vietabroader-qr.appspot.com/"; private final String BUTTON_TEXT_SIGN_IN = "Sign In"; private final String BUTTON_TEXT_SIGN_OUT = "Sign Out"; private final String LABEL_TEXT_SIGN_IN = "Please sign in with your Google account"; private final String BUTTON_TEXT_CONNECT = "Connect"; private final Dimension BUTTON_DIM_AUTHENTICATE = new Dimension(100, 30); private final Dimension LABEL_DIM_EMAIL = new Dimension(300, 15); private final JButton btnAuthenticate = new JButton(BUTTON_TEXT_SIGN_IN); private final JLabel lblAuthMessage = new JLabel(LABEL_TEXT_SIGN_IN); private final JButton btnConnect = new JButton(BUTTON_TEXT_CONNECT); private final JTextField txtSpreadsheetID = new JTextField(15); private final MessageLabel lblSpreadsheetMessage = new MessageLabel(" "); private final MessageLabel lblSheetMessage = new MessageLabel(" "); private final JComboBox<String> cbbSheet = new JComboBox<>(); private final JProgressBar prgIndicator = new JProgressBar(); public MainView() { initUI(); resetOnSignedOut(); initControllers(); } private void resetOnSignedOut() { lblSpreadsheetMessage.setBackground(Color.LIGHT_GRAY); lblSpreadsheetMessage.setForeground(Color.BLACK); lblSpreadsheetMessage.setText(" "); lblSheetMessage.setBackground(Color.LIGHT_GRAY); lblSheetMessage.setForeground(Color.BLACK); lblSheetMessage.setText(" "); btnAuthenticate.setText(BUTTON_TEXT_SIGN_IN); lblAuthMessage.setText(LABEL_TEXT_SIGN_IN); cbbSheet.removeAllItems(); } private void initUI() { JPanel panelMain = new JPanel(); panelMain.setLayout(new GridBagLayout()); getContentPane().add(panelMain); GridBagConstraints c = new GridBagConstraints(); // Sign in panel c.gridwidth = 2; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(4, 4, 4, 4); // Outer margin of each panel panelMain.add(createSignInPanel(), c); // Spreadsheet connect panel c.gridy = 2; panelMain.add(createSpreadsheetPanel(), c); c.gridy = 3; c.fill = GridBagConstraints.HORIZONTAL; lblSpreadsheetMessage.setBorder(BorderFactory.createLoweredSoftBevelBorder()); lblSpreadsheetMessage.setOpaque(true); panelMain.add(lblSpreadsheetMessage, c); // Sheet workspace panel c.gridy = 4; panelMain.add(createWorkspacePanel(), c); c.gridy = 5; c.fill = GridBagConstraints.HORIZONTAL; lblSheetMessage.setBorder(BorderFactory.createLoweredSoftBevelBorder()); lblSheetMessage.setOpaque(true); panelMain.add(lblSheetMessage, c); // QR generating and reading panel c.gridy = 6; c.gridwidth = 1; c.weightx = 1 / 2.0; c.gridx = 0; c.fill = GridBagConstraints.BOTH; panelMain.add(createGeneratePanel(), c); c.gridx = 1; panelMain.add(createWebcamPanel(), c); c.gridy = 7; c.gridx = 0; c.gridwidth = 2; c.insets = new Insets(0, 0, 0, 0); panelMain.add(createFooterPanel(), c); this.setTitle("VAQR"); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setResizable(false); this.pack(); this.setLocationRelativeTo(null); } private JPanel createSignInPanel() { TitledPanel panel = new TitledPanel("Account"); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); btnAuthenticate.setPreferredSize(BUTTON_DIM_AUTHENTICATE); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; panel.add(btnAuthenticate, c); lblAuthMessage.setPreferredSize(LABEL_DIM_EMAIL); c.gridx = 1; c.gridy = 0; panel.add(lblAuthMessage, c); return panel; } private JPanel createSpreadsheetPanel() { TitledPanel panel = new TitledPanel("Spreadsheet"); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.LINE_START; panel.add(new JLabel("Spreadsheet ID: "), c); c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; panel.add(txtSpreadsheetID, c); c.anchor = GridBagConstraints.CENTER; c.gridx = 2; panel.add(btnConnect); return panel; } private JPanel createWorkspacePanel() { TitledPanel panel = new TitledPanel("Workspace"); // Sheet selection GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_END; panel.add(new JLabel("Sheet: "), c); c.gridx = 1; c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL; panel.add(cbbSheet, c); // Row range specification c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.LINE_END; c.weightx = 1/6.0; panel.add(new JLabel("Row: "), c); c.gridx = 1; c.anchor = GridBagConstraints.CENTER; c.weightx = 2/6.0; final JTextField txtRowFrom = new JTextField("1",5); txtRowFrom.setInputVerifier(new RowVerifier()); txtRowFrom.setToolTipText("Enter a positive integer"); panel.add(txtRowFrom, c); c.gridx = 2; c.weightx = 1/6.0; panel.add(new JLabel("to"), c); c.gridx = 3; c.weightx = 2/6.0; final JTextField txtRowTo = new JTextField("1",5); txtRowTo.setInputVerifier(new RowVerifier()); txtRowTo.setToolTipText("Enter a positive integer"); panel.add(txtRowTo, c); // Key columns and refresh button c = new GridBagConstraints(); c.gridy = 2; c.gridwidth = 4; c.fill = GridBagConstraints.HORIZONTAL; JPanel panCol = createColumnPanel(); panel.add(panCol, c); return panel; } private JPanel createColumnPanel() { JPanel panelMain = new JPanel(); TitledPanel panel = new TitledPanel("Key Columns"); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1 / 4; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; final JPanel panKey = createOneColumn("Key"); panel.add(panKey, c); c.gridx = 1; final JPanel panSecret = createOneColumn("Secret"); panSecret.setEnabled(false); panel.add(panSecret, c); c.gridx = 2; final JPanel panQR = createOneColumn("QR"); panel.add(panQR, c); c.gridx = 3; final JPanel panOutput = createOneColumn("Output"); panel.add(panOutput, c); c = new GridBagConstraints(); panelMain.add(panel, c); c.gridx = 1; JButton btnRefresh = new JButton("Refresh"); c.anchor = GridBagConstraints.CENTER; btnRefresh.setPreferredSize(new Dimension(100, 50)); panelMain.add(btnRefresh, c); return panelMain; } private JPanel createOneColumn(String label) { final JTextField txtCol = new JTextField("A",5); JPanel panel = new JPanel() { @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); txtCol.setEnabled(enabled); } }; panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1; c.gridy = 0; c.anchor = GridBagConstraints.CENTER; panel.add(new JLabel(label), c); c.gridy = 1; c.fill = GridBagConstraints.HORIZONTAL; txtCol.setInputVerifier(new ColumnVerifier()); txtCol.setToolTipText("Enter a valid column name. Ex: A, AB, ..."); panel.add(txtCol, c); return panel; } private JPanel createGeneratePanel() { TitledPanel panel = new TitledPanel("Generate QR Code"); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.CENTER; JButton btnGenerator = new JButton("Go to QR Generator"); btnGenerator.setPreferredSize(new Dimension(160, 60)); panel.add(btnGenerator, c); btnGenerator.addActionListener(e -> { try { Desktop.getDesktop().browse(new URI(QR_GENERATOR_URL)); } catch (Exception ex) { logger.error("Cannot open QR Generator", ex); } }); return panel; } private JPanel createWebcamPanel() { TitledPanel panel = new TitledPanel("Scan QR Code"); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.CENTER; JButton btnWebcam = new JButton("Start Webcam"); btnWebcam.setPreferredSize(new Dimension(150, 60)); panel.add(btnWebcam, c); btnWebcam.addActionListener(e -> { WebcamView camView = new WebcamView(); camView.setVisible(true); }); return panel; } private JPanel createFooterPanel() { JPanel panel = new JPanel(new GridBagLayout()); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1/2.0; c.insets = new Insets(5, 10, 5, 10); c.gridx = 0; c.anchor = GridBagConstraints.LINE_START; JLabel lblCopyright = new JLabel("\u00a9 VietAbroader 2017"); lblCopyright.setForeground(Color.GRAY); panel.add(lblCopyright, c); c.gridx = 1; c.anchor = GridBagConstraints.LINE_END; prgIndicator.setIndeterminate(false); panel.add(prgIndicator, c); return panel; } /** * Initialize controllers */ private void initControllers() { AuthenticationController authController = new AuthenticationController(); authController.setButtonAuthenticate(btnAuthenticate).control(); SpreadsheetConnectController spreadSheetConnectController = new SpreadsheetConnectController(); spreadSheetConnectController.setButtonConnect(btnConnect) .setTextSpreadsheetID(txtSpreadsheetID) .setLabelSpreadsheetMessage(lblSpreadsheetMessage) .setProgressIndicator(prgIndicator) .control(); } /** * Handle global state change */ @Override public void update(Observable o, Object arg) { logger.debug("Global state changed"); GlobalState currentState = (GlobalState) o; GlobalState.Status currentStatus = currentState.getStatus(); switch (currentStatus) { case SIGNED_OUT: resetOnSignedOut(); break; case SIGNED_IN: btnAuthenticate.setText(BUTTON_TEXT_SIGN_OUT); lblAuthMessage.setText(currentState.getUserEmail()); break; case CONNECTED: VASpreadsheet currentSpreadsheet = currentState.getSpreadsheet(); String spreadsheetTitle = currentSpreadsheet.getSpreadsheetTitle(); lblSpreadsheetMessage.setBackground(Color.GREEN); lblSpreadsheetMessage.setForeground(Color.BLACK); lblSpreadsheetMessage.setText("Connected to: " + spreadsheetTitle); List<String> sheets = currentSpreadsheet.getSheetTitles(); cbbSheet.removeAllItems(); sheets.forEach(cbbSheet::addItem); break; case QR_READING: break; } } }
package netflix.ocelli.rxnetty; import io.netty.buffer.ByteBuf; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import netflix.ocelli.Host; import netflix.ocelli.Instance; import netflix.ocelli.InstanceCollector; import netflix.ocelli.InstanceSubject; import netflix.ocelli.LoadBalancer; import netflix.ocelli.functions.Delays; import netflix.ocelli.functions.Metrics; import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer; import netflix.ocelli.util.RxUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.functions.Func1; public class ServerPoolTest { private HttpServer<ByteBuf, ByteBuf> httpServer; @Before public void setUp() throws Exception { httpServer = RxNetty.createHttpServer(0, new RequestHandler<ByteBuf, ByteBuf>() { @Override public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { return response.close(); } }); httpServer.start(); } @After public void tearDown() throws Exception { if (null != httpServer) { try { httpServer.shutdown(); } catch (Exception e) { } } } @Test public void testSimple() throws Exception { final InstanceSubject<Host> instances = InstanceSubject.create(); final Map<Host, HttpInstanceImpl> lookup = new HashMap<Host, HttpInstanceImpl>(); final LoadBalancer<HttpClient<ByteBuf, ByteBuf>> lb = LoadBalancer.fromSource( instances .map(new Func1<Instance<Host>, Instance<HttpInstanceImpl>>() { @Override public Instance<HttpInstanceImpl> call(Instance<Host> t1) { return Instance.create( new HttpInstanceImpl(t1.getValue(), Metrics.quantile(0.95), t1.getLifecycle()), t1.getLifecycle()); } }) .doOnNext(InstanceCollector.toMap(lookup, HttpInstanceImpl.byHost()))) .withQuarantiner(HttpInstanceImpl.connector(), Delays.immediate()) // Convert from HttpServer to an HttpClient while managing event subscriptions .convertTo(HttpInstanceImpl.toClient()) .build(RoundRobinLoadBalancer.<HttpClient<ByteBuf, ByteBuf>>create()); // Case 1: Simple add Host host = new Host("127.0.0.1", httpServer.getServerPort()); instances.add(host); // Case 2: Attempt an operation HttpClientResponse<ByteBuf> resp = lb.toBlocking().first() .submit(HttpClientRequest.createGet("/")) .timeout(1, TimeUnit.SECONDS) .toBlocking() .first(); Assert.assertEquals(200, resp.getStatus().code()); HttpInstanceImpl s1 = lookup.get(host); Assert.assertNotNull(s1); Assert.assertEquals(1, s1.getMetricListener().getIncarnationCount()); // Case 3: Remove the server instances.remove(host); try { lb.toBlocking().first(); Assert.fail("Should have failed with no element"); } catch (NoSuchElementException e) { } // Case 4: Add a bad host and confirm retry counts Host badHost = new Host("127.0.0.2.1", 0); instances.add(badHost); AtomicInteger attemptCount = new AtomicInteger(); try { resp = lb .doOnNext(RxUtil.increment(attemptCount)) .concatMap(new Func1<HttpClient<ByteBuf, ByteBuf>, Observable<HttpClientResponse<ByteBuf>>>() { @Override public Observable<HttpClientResponse<ByteBuf>> call(HttpClient<ByteBuf, ByteBuf> client) { return client.submit(HttpClientRequest.createGet("/")); } }) .retry(1) .timeout(1, TimeUnit.SECONDS) .toBlocking() .first(); Assert.fail("Should have failed with connect timeout exception"); } catch (Exception e) { Assert.assertEquals(2, attemptCount.get()); } HttpInstanceImpl s2 = lookup.get(badHost); Assert.assertEquals(3, s2.getMetricListener().getIncarnationCount()); // httpServer.start(); // .map(Instance.transform(new Func1<Host, HttpClientHolder<ByteBuf, ByteBuf>>() { // @Override // public HttpClientHolder<ByteBuf, ByteBuf> call(Host host) { // return new HttpClientHolder<ByteBuf, ByteBuf>( // RxNetty.createHttpClient(host.getHostName(), host.getPort()), // Metrics.memoize(10L)); // // Execute a single request // HttpClientResponse<ByteBuf> response = lb // .toObservable() // .flatMap(new Func1<HttpClientHolder<ByteBuf, ByteBuf>, Observable<HttpClientResponse<ByteBuf>>>() { // @Override // public Observable<HttpClientResponse<ByteBuf>> call(HttpClientHolder<ByteBuf, ByteBuf> t1) { // return t1 // .getClient() // .submit(HttpClientRequest.createGet("/")); // .delaySubscription(2, TimeUnit.SECONDS) // .toBlocking() // .toFuture() // .get(3, TimeUnit.SECONDS); // // Force failure // lb.next().fail(); // // Execute a single request // try { // response = lb // .toObservable() // .flatMap(new Func1<HttpClientHolder<ByteBuf, ByteBuf>, Observable<HttpClientResponse<ByteBuf>>>() { // @Override // public Observable<HttpClientResponse<ByteBuf>> call(HttpClientHolder<ByteBuf, ByteBuf> t1) { // return t1 // .getClient() // .submit(HttpClientRequest.createGet("/")); // .toBlocking() // .toFuture() // .get(1, TimeUnit.SECONDS); // catch (ExecutionException e) { // Assert.assertSame(e.getCause().getClass(), NoSuchElementException.class); // TimeUnit.SECONDS.sleep(2); // // Execute a single request // response = lb // .toObservable() // .flatMap(new Func1<HttpClientHolder<ByteBuf, ByteBuf>, Observable<HttpClientResponse<ByteBuf>>>() { // @Override // public Observable<HttpClientResponse<ByteBuf>> call(HttpClientHolder<ByteBuf, ByteBuf> t1) { // return t1 // .getClient() // .submit(HttpClientRequest.createGet("/")); // .toBlocking() // .toFuture() // .get(2, TimeUnit.SECONDS); // Assert.assertEquals("Unexpected response status.", HttpResponseStatus.OK, response.getStatus()); // instances.remove(host); // try { // response = lb // .toObservable() // .flatMap(new Func1<HttpClientHolder<ByteBuf, ByteBuf>, Observable<HttpClientResponse<ByteBuf>>>() { // @Override // public Observable<HttpClientResponse<ByteBuf>> call(HttpClientHolder<ByteBuf, ByteBuf> t1) { // return t1 // .getClient() // .submit(HttpClientRequest.createGet("/")); // .toBlocking() // .toFuture() // .get(1, TimeUnit.SECONDS); // catch (ExecutionException e) { // Assert.assertSame(e.getCause().getClass(), NoSuchElementException.class); } }
package org.yinwang.rubysonar; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import org.jetbrains.annotations.NotNull; import org.yinwang.rubysonar.ast.Function; import org.yinwang.rubysonar.ast.Node; import org.yinwang.rubysonar.ast.Str; import org.yinwang.rubysonar.types.Type; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class JSONDump { private static Logger log = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); private static Set<String> seenDef = new HashSet<>(); private static Set<String> seenRef = new HashSet<>(); @NotNull private static String dirname(@NotNull String path) { File f = new File(path); if (f.getParent() != null) { return f.getParent(); } else { return path; } } private static Analyzer newAnalyzer(String projectDir, List<String> srcpath, List<String> inclpaths) { Analyzer idx = new Analyzer(); idx.addPath(projectDir); idx.addPaths(inclpaths); idx.analyze(srcpath); idx.finish(); return idx; } private static String kindName(Binding.Kind kind) { if (kind == Binding.Kind.CLASS_METHOD) { return "method"; } else { return kind.toString().toLowerCase(); } } private static void writeSymJson(@NotNull Binding binding, JsonGenerator json) throws IOException { if (binding.start < 0) { return; } String name = binding.node.name; boolean isExported = !( Binding.Kind.VARIABLE == binding.kind || Binding.Kind.PARAMETER == binding.kind || Binding.Kind.SCOPE == binding.kind || Binding.Kind.ATTRIBUTE == binding.kind || (name != null && (name.length() == 0 || name.startsWith("lambda%")))); String path = binding.qname.replace("%20", "."); if (!seenDef.contains(path)) { seenDef.add(path); json.writeStartObject(); json.writeStringField("name", name); json.writeStringField("path", path); json.writeStringField("file", binding.file); json.writeNumberField("identStart", binding.start); json.writeNumberField("identEnd", binding.end); json.writeNumberField("defStart", binding.bodyStart); json.writeNumberField("defEnd", binding.bodyEnd); json.writeBooleanField("exported", isExported); json.writeStringField("kind", kindName(binding.kind)); if (binding.kind == Binding.Kind.METHOD || binding.kind == Binding.Kind.CLASS_METHOD) { // get args expression Type t = binding.type; if (t.isUnionType()) { t = t.asUnionType().firstUseful(); } if (t != null && t.isFuncType()) { Function func = t.asFuncType().func; if (func != null) { String signature = func.getArgList(); if (!signature.equals("")) { signature = "(" + signature + ")"; } json.writeStringField("signature", signature); } } } Str docstring = binding.findDocString(); if (docstring != null) { json.writeStringField("docstring", docstring.value); } json.writeEndObject(); } } private static void writeRefJson(Node ref, Binding binding, JsonGenerator json) throws IOException { if (binding.file != null) { String path = binding.qname.replace("%20", "."); if (binding.start >= 0 && ref.start >= 0) { json.writeStartObject(); json.writeStringField("sym", path); json.writeStringField("symFile", binding.node.file); json.writeStringField("file", ref.file); json.writeNumberField("start", ref.start); json.writeNumberField("end", ref.end); json.writeBooleanField("builtin", false); json.writeEndObject(); } } } /* * Precondition: srcpath and inclpaths are absolute paths */ private static void graph(String projectDir, List<String> srcpath, List<String> inclpaths, OutputStream symOut, OutputStream refOut) throws Exception { Analyzer idx = newAnalyzer(projectDir, srcpath, inclpaths); idx.multilineFunType = true; JsonFactory jsonFactory = new JsonFactory(); JsonGenerator symJson = jsonFactory.createGenerator(symOut); JsonGenerator refJson = jsonFactory.createGenerator(refOut); JsonGenerator[] allJson = {symJson, refJson}; for (JsonGenerator json : allJson) { json.writeStartArray(); } for (Binding b : idx.getAllBindings()) { if (b.file != null && b.file.startsWith(projectDir)) { writeSymJson(b, symJson); writeRefJson(b.node, b, refJson); // self reference } for (Node ref : b.refs) { if (ref.file != null && ref.file.startsWith(projectDir)) { String key = ref.file + ":" + ref.start; if (!seenRef.contains(key)) { writeRefJson(ref, b, refJson); seenRef.add(key); } } } } for (JsonGenerator json : allJson) { json.writeEndArray(); json.close(); } } private static void info(Object msg) { System.out.println(msg); } private static void usage() { info("Usage: java org.yinwang.rubysonar.dump <source-path> <include-paths> <out-root> [verbose]"); info(" <source-path> is path to source unit (package directory or module file) that will be graphed"); info(" <include-paths> are colon-separated paths to included libs"); info(" <out-root> is the prefix of the output files. There are 3 output files: <out-root>-doc, <out-root>-sym, <out-root>-ref"); info(" [verbose] if set, then verbose logging is used (optional)"); } public static void main(String[] args) throws Exception { log.setLevel(Level.SEVERE); String projectDir; String outroot; List<String> inclpaths; List<String> srcpath = new ArrayList<>(); if (args.length >= 3) { projectDir = args[0]; outroot = args[1]; inclpaths = Arrays.asList(args[2].split(":")); srcpath.addAll(Arrays.asList(args).subList(3, args.length)); } else { usage(); return; } OutputStream symOut = null, refOut = null; try { symOut = new BufferedOutputStream(new FileOutputStream(outroot + "-sym")); refOut = new BufferedOutputStream(new FileOutputStream(outroot + "-ref")); _.msg("graphing: " + srcpath); graph(projectDir, srcpath, inclpaths, symOut, refOut); symOut.flush(); refOut.flush(); } catch (FileNotFoundException e) { System.err.println("Could not find file: " + e); return; } finally { if (symOut != null) { symOut.close(); } if (refOut != null) { refOut.close(); } } log.info("SUCCESS"); } }
package org.openlca.core.math.data_quality; import java.util.List; import gnu.trove.map.hash.TLongObjectHashMap; import org.openlca.core.database.IDatabase; import org.openlca.core.database.NativeSql; import org.openlca.core.matrix.IndexFlow; import org.openlca.core.matrix.ProcessProduct; import org.openlca.core.results.BaseResult; class DQData2 { private final DQCalculationSetup setup; private final BaseResult result; /** * We store the process data in a byte matrix where the data quality * indicators are mapped to the rows and the process products to the * columns. */ private byte[][] processData; /** * For the exchange data we store a flow*product matrix for each * indicator that holds the respective data quality scores of that * indicator. */ private BMatrix[] exchangeData; static DQData2 of(IDatabase db, DQCalculationSetup setup, BaseResult result) { var data = new DQData2(setup, result); data.loadProcessData(db); data.loadExchangeData(db); return data; } private DQData2(DQCalculationSetup setup, BaseResult result) { this.setup = setup; this.result = result; } private void loadProcessData(IDatabase db) { var system = setup.processSystem; if (system == null) return; var n = system.indicators.size(); processData = new byte[n][]; for (int i = 0; i < n; i++) { processData[i] = new byte[result.techIndex.size()]; } // query the process table var techIndex = result.techIndex; var sql = "select id, f_dq_system, dq_entry " + "from tbl_processes"; NativeSql.on(db).query(sql, r -> { // check that we have a valid entry long systemID = r.getLong(2); if (systemID != system.id) return true; var dqEntry = r.getString(3); if (dqEntry == null) return true; var providers = techIndex.getProviders(r.getLong(1)); if (providers.isEmpty()) return true; // store the values of the entry int[] values = system.toValues(dqEntry); int _n = Math.min(n, values.length); for (int i = 0; i < _n; i++) { byte[] data = processData[i]; byte value = (byte) values[i]; for (var provider : providers) { int col = techIndex.getIndex(provider); data[col] = value; } } return true; }); } private void loadExchangeData(IDatabase db) { var system = setup.exchangeSystem; if (system == null || result.flowIndex == null) return; // allocate a BMatrix for each indicator var n = system.indicators.size(); exchangeData = new BMatrix[n]; var techIndex = result.techIndex; var flowIndex = result.flowIndex; for (int i = 0; i < n; i++) { exchangeData[i] = new BMatrix( flowIndex.size(), techIndex.size()); } // collect the processes (providers) of the result with a // matching data quality system var providers = new TLongObjectHashMap<List<ProcessProduct>>(); var sql = "select id, f_exchange_dq_system from tbl_processes"; NativeSql.on(db).query(sql, r -> { long sysID = r.getLong(2); if (sysID != system.id) return true; var processID = r.getLong(1); var products = result.techIndex.getProviders(processID); if (products.isEmpty()) return true; providers.put(processID, products); return true; }); // now, scan the exchanges table and collect all // matching data quality entries sql = "select f_owner, f_flow, f_location, dq_entry from tbl_exchanges"; NativeSql.on(db).query(sql, r -> { // check that we have a valid entry var products = providers.get(r.getLong(1)); if (products == null) return true; long flowID = r.getLong(2); long locationID = r.getLong(3); var dqEntry = r.getString(4); if (dqEntry == null) return true; int row = flowIndex.of(flowID, locationID); if (row < 0) return true; // store the values int[] values = system.toValues(dqEntry); int _n = Math.min(n, values.length); for (int i = 0; i < _n; i++) { var data = exchangeData[i]; byte value = (byte) values[i]; for (var product : products) { int col = techIndex.getIndex(product); data.set(row, col, value); } } return true; }); } /** * Get the process data quality entry for the given product. */ public int[] get(ProcessProduct product) { if (processData == null) return null; int col = result.techIndex.getIndex(product); if (col < 0) return null; int[] values = new int[processData.length]; for (int row = 0; row < processData.length; row++) { values[row] = processData[row][col]; } return values; } /** * Get the exchange data quality entry for the given product and flow. */ public int[] get(ProcessProduct product, IndexFlow flow) { if (exchangeData == null) return null; int row = result.flowIndex.of(flow); int col = result.techIndex.getIndex(product); if (row < 0 || col < 0) return null; int[] values = new int[exchangeData.length]; for (int k = 0; k < exchangeData.length; k++) { values[k] = exchangeData[k].get(row, col); } return values; } private static class BMatrix { private final int rows; private final byte[] data; BMatrix(int rows, int columns) { this.rows = rows; this.data = new byte[rows * columns]; } void set(int row, int col, int value) { data[index(row, col)] = (byte) value; } int get(int row, int col) { return data[index(row, col)]; } int index(int row, int column) { return row + rows * column; } } }
package pro.beam.api.resource; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import pro.beam.api.resource.channel.BeamChannel; import com.google.gson.annotations.SerializedName; import pro.beam.api.resource.channel.BeamResource; public class BeamUser implements Serializable { public Date createdAt; public String email; public int id; public BeamChannel channel; public int points; public Date resetTime; public Social social; public Date updatedAt; public String username; public boolean verified; public ArrayList<BeamResource> avatars; public enum Role { @SerializedName("Banned") BANNED, @SerializedName("Muted") MUTED, @SerializedName("User") USER, @SerializedName("Pro") PRO, @SerializedName("Subscriber") SUBSCRIBER, @SerializedName("Mod") MOD, @SerializedName("Global Mod") GLOBAL_MOD, @SerializedName("Admin") ADMIN, @SerializedName("Staff") STAFF, @SerializedName("Founder") FOUNDER } public class Social implements Serializable { public String facebook; public String twitter; public String youtube; } }
package scrum.client.admin; import ilarkesto.gwt.client.AWidget; import ilarkesto.gwt.client.GwtLogger; import ilarkesto.gwt.client.ToolbarWidget; import scrum.client.ScrumGwtApplication; import scrum.client.common.FieldsWidget; import scrum.client.common.GroupWidget; import scrum.client.test.WidgetsTesterWidget; import scrum.client.workspace.Ui; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.PasswordTextBox; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; public class LoginWidget extends AWidget { private TextBox username; private PasswordTextBox password; @Override protected Widget onInitialization() { username = new TextBox(); username.setText("admin"); password = new PasswordTextBox(); password.setText("geheim"); ToolbarWidget toolbar = new ToolbarWidget(true); toolbar.addButton("Login").addClickListener(new ClickListener() { public void onClick(Widget sender) { login(); } }); FieldsWidget fieldsWidget = new FieldsWidget(); fieldsWidget.addWidget("Username", username); fieldsWidget.addWidget("Password", password); fieldsWidget.addWidget(null, toolbar.update()); SimplePanel wrapper = new SimplePanel(); wrapper.setStyleName("LoginWidget"); wrapper.setWidget(new GroupWidget("Login", fieldsWidget)); // TODO remove this FlowPanel test = new FlowPanel(); test.add(wrapper); test.add(new WidgetsTesterWidget().update()); return test; // return wrapper; } @Override protected void onUpdate() {} private void login() { ScrumGwtApplication.get().getUi().lock("Checking login data..."); ScrumGwtApplication.get().callLogin(username.getText(), password.getText(), new Runnable() { public void run() { GwtLogger.DEBUG("Login response received"); if (ScrumGwtApplication.get().getUser() == null) { GwtLogger.DEBUG("LOGIN FAILED!"); ScrumGwtApplication.get().getUi().unlock(); } else { GwtLogger.DEBUG("Login succeded:", ScrumGwtApplication.get().getUi()); Ui.get().showProjectSelector(); } } }); } }
package se.kth.hopsworks.util; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; import javax.ejb.EJB; import javax.ejb.Singleton; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import se.kth.hopsworks.certificates.CertsFacade; @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class Settings { private final static Logger LOGGER = Logger.getLogger(Settings.class. getName()); @PersistenceContext(unitName = "kthfsPU") private EntityManager em; @EJB private CertsFacade certsFacade; @PostConstruct public void init() { try { //Generate glassfish certificate and persist to db if(!isGlassfishCertGenerated()){ LOGGER.log(Level.INFO, "Attempting to generate super user certificate"); LocalhostServices.createServiceCertificates(getIntermediateCaDir(), getHdfsSuperUser()); certsFacade.putServiceCerts(getHdfsSuperUser()); //Updated variables table Variables variable = findById(VARIABLE_GLASSFISH_CERT_CENERATED); variable.setValue("true"); em.persist(variable); em.flush(); LOGGER.log(Level.INFO, "Super user certificate was generated successfully"); } else { LOGGER.log(Level.INFO, "Super user certificate is already generated"); } } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Error while generating superuser cert", ex); } } public static String AGENT_EMAIL = "kagent@hops.io"; public static final String SITE_EMAIL = "admin@kth.se"; /** * Global Variables taken from the DB */ private static final String VARIABLE_KIBANA_IP = "kibana_ip"; private static final String VARIABLE_LIVY_IP = "livy_ip"; private static final String VARIABLE_JHS_IP = "jhs_ip"; private static final String VARIABLE_OOZIE_IP = "oozie_ip"; private static final String VARIABLE_SPARK_HISTORY_SERVER_IP = "spark_history_server_ip"; private static final String VARIABLE_ELASTIC_IP = "elastic_ip"; private static final String VARIABLE_SPARK_USER = "spark_user"; private static final String VARIABLE_YARN_SUPERUSER = "yarn_user"; private static final String VARIABLE_HDFS_SUPERUSER = "hdfs_user"; private static final String VARIABLE_ZEPPELIN_DIR = "zeppelin_dir"; private static final String VARIABLE_ZEPPELIN_PROJECTS_DIR = "zeppelin_projects_dir"; private static final String VARIABLE_ZEPPELIN_SYNC_INTERVAL = "zeppelin_sync_interval"; private static final String VARIABLE_ZEPPELIN_USER = "zeppelin_user"; private static final String VARIABLE_SPARK_DIR = "spark_dir"; private static final String VARIABLE_FLINK_DIR = "flink_dir"; private static final String VARIABLE_FLINK_USER = "flink_user"; private static final String VARIABLE_NDB_DIR = "ndb_dir"; private static final String VARIABLE_MYSQL_DIR = "mysql_dir"; private static final String VARIABLE_HADOOP_DIR = "hadoop_dir"; private static final String VARIABLE_HOPSWORKS_DIR = "hopsworks_dir"; private static final String VARIABLE_YARN_DEFAULT_QUOTA = "yarn_default_quota"; private static final String VARIABLE_HDFS_DEFAULT_QUOTA = "hdfs_default_quota"; private static final String VARIABLE_MAX_NUM_PROJ_PER_USER = "max_num_proj_per_user"; private static final String VARIABLE_ADAM_USER = "adam_user"; private static final String VARIABLE_ADAM_DIR = "adam_dir"; private static final String VARIABLE_TWOFACTOR_AUTH = "twofactor_auth"; private static final String VARIABLE_KAFKA_DIR = "kafka_dir"; private static final String VARIABLE_KAFKA_USER = "kafka_user"; private static final String VARIABLE_ZK_DIR = "zk_dir"; private static final String VARIABLE_ZK_USER = "zk_user"; private static final String VARIABLE_ZK_IP = "zk_ip"; private static final String VARIABLE_KAFKA_IP = "kafka_ip"; private static final String VARIABLE_DRELEPHANT_IP = "drelephant_ip"; private static final String VARIABLE_DRELEPHANT_DB = "drelephant_db"; private static final String VARIABLE_DRELEPHANT_PORT = "drelephant_port"; private static final String VARIABLE_YARN_WEB_UI_IP = "yarn_ui_ip"; private static final String VARIABLE_YARN_WEB_UI_PORT = "yarn_ui_port"; private static final String VARIABLE_FILE_PREVIEW_IMAGE_SIZE = "file_preview_image_size"; private static final String VARIABLE_FILE_PREVIEW_TXT_SIZE = "file_preview_txt_size"; private static final String VARIABLE_GVOD_REST_ENDPOINT = "gvod_rest_endpoint"; private static final String VARIABLE_PUBLIC_SEARCH_ENDPOINT = "public_search_endpoint"; private static final String VARIABLE_REST_PORT = "rest_port"; public static final String ERASURE_CODING_CONFIG = "erasure-coding-site.xml"; private static final String VARIABLE_KAFKA_NUM_PARTITIONS = "kafka_num_partitions"; private static final String VARIABLE_KAFKA_NUM_REPLICAS = "kafka_num_replicas"; private static final String VARIABLE_HOPSWORKS_SSL_MASTER_PASSWORD = "hopsworks_master_password"; private static final String VARIABLE_GLASSFISH_CERT_CENERATED = "glassfish_cert"; private String setVar(String varName, String defaultValue) { Variables userName = findById(varName); if (userName != null && userName.getValue() != null && (userName.getValue().isEmpty() == false)) { String user = userName.getValue(); if (user != null && user.isEmpty() == false) { return user; } } return defaultValue; } private String setStrVar(String varName, String defaultValue) { Variables var = findById(varName); if (var != null && var.getValue() != null) { String val = var.getValue(); if (val != null && val.isEmpty() == false) { return val; } } return defaultValue; } private String setDirVar(String varName, String defaultValue) { Variables dirName = findById(varName); if (dirName != null && dirName.getValue() != null && (new File(dirName.getValue()).isDirectory())) { String val = dirName.getValue(); if (val != null && val.isEmpty() == false) { return val; } } return defaultValue; } private String setIpVar(String varName, String defaultValue) { Variables ip = findById(varName); if (ip != null && ip.getValue() != null && Ip.validIp(ip.getValue())) { String val = ip.getValue(); if (val != null && val.isEmpty() == false) { return val; } } return defaultValue; } private String setDbVar(String varName, String defaultValue) { Variables ip = findById(varName); if (ip != null && ip.getValue() != null) { // TODO - check this is a valid DB name String val = ip.getValue(); if (val != null && val.isEmpty() == false) { return val; } } return defaultValue; } private int setIntVar(String varName, int defaultValue) { Variables ip = findById(varName); if (ip != null && ip.getValue() != null) { String val = ip.getValue(); if (val != null && val.isEmpty() == false) { return Integer.parseInt(val); } } return defaultValue; } private long setLongVar(String varName, long defaultValue) { Variables ip = findById(varName); if (ip != null && ip.getValue() != null) { String val = ip.getValue(); if (val != null && val.isEmpty() == false) { return Long.parseLong(val); } } return defaultValue; } private boolean cached = false; private void populateCache() { if (!cached) { TWOFACTOR_AUTH = setVar(VARIABLE_TWOFACTOR_AUTH, TWOFACTOR_AUTH); HDFS_SUPERUSER = setVar(VARIABLE_HDFS_SUPERUSER, HDFS_SUPERUSER); YARN_SUPERUSER = setVar(VARIABLE_YARN_SUPERUSER, YARN_SUPERUSER); SPARK_USER = setVar(VARIABLE_SPARK_USER, SPARK_USER); SPARK_DIR = setDirVar(VARIABLE_SPARK_DIR, SPARK_DIR); FLINK_USER = setVar(VARIABLE_FLINK_USER, FLINK_USER); FLINK_DIR = setDirVar(VARIABLE_FLINK_DIR, FLINK_DIR); ZEPPELIN_USER = setVar(VARIABLE_ZEPPELIN_USER, ZEPPELIN_USER); ZEPPELIN_DIR = setDirVar(VARIABLE_ZEPPELIN_DIR, ZEPPELIN_DIR); ZEPPELIN_PROJECTS_DIR = setDirVar(VARIABLE_ZEPPELIN_PROJECTS_DIR, ZEPPELIN_PROJECTS_DIR); ZEPPELIN_SYNC_INTERVAL = setLongVar(VARIABLE_ZEPPELIN_SYNC_INTERVAL, ZEPPELIN_SYNC_INTERVAL); ADAM_USER = setVar(VARIABLE_ADAM_USER, ADAM_USER); ADAM_DIR = setDirVar(VARIABLE_ADAM_DIR, ADAM_DIR); MYSQL_DIR = setDirVar(VARIABLE_MYSQL_DIR, MYSQL_DIR); HADOOP_DIR = setDirVar(VARIABLE_HADOOP_DIR, HADOOP_DIR); HOPSWORKS_INSTALL_DIR = setDirVar(VARIABLE_HOPSWORKS_DIR, HOPSWORKS_INSTALL_DIR); NDB_DIR = setDirVar(VARIABLE_NDB_DIR, NDB_DIR); ELASTIC_IP = setIpVar(VARIABLE_ELASTIC_IP, ELASTIC_IP); JHS_IP = setIpVar(VARIABLE_JHS_IP, JHS_IP); LIVY_IP = setIpVar(VARIABLE_LIVY_IP, LIVY_IP); OOZIE_IP = setIpVar(VARIABLE_OOZIE_IP, OOZIE_IP); SPARK_HISTORY_SERVER_IP = setIpVar(VARIABLE_SPARK_HISTORY_SERVER_IP, SPARK_HISTORY_SERVER_IP); ZK_IP = setIpVar(VARIABLE_ZK_IP, ZK_IP); ZK_USER = setVar(VARIABLE_ZK_USER, ZK_USER); ZK_DIR = setDirVar(VARIABLE_ZK_DIR, ZK_DIR); DRELEPHANT_IP = setIpVar(VARIABLE_DRELEPHANT_IP, DRELEPHANT_IP); DRELEPHANT_PORT = setIntVar(VARIABLE_DRELEPHANT_PORT, DRELEPHANT_PORT); DRELEPHANT_DB = setDbVar(VARIABLE_DRELEPHANT_DB, DRELEPHANT_DB); KIBANA_IP = setIpVar(VARIABLE_KIBANA_IP, KIBANA_IP); KAFKA_IP = setIpVar(VARIABLE_KAFKA_IP, KAFKA_IP); KAFKA_USER = setVar(VARIABLE_KAFKA_USER, KAFKA_USER); KAFKA_DIR = setDirVar(VARIABLE_KAFKA_DIR, KAFKA_DIR); KAFKA_DEFAULT_NUM_PARTITIONS = setDirVar(VARIABLE_KAFKA_NUM_PARTITIONS, KAFKA_DEFAULT_NUM_PARTITIONS); KAFKA_DEFAULT_NUM_REPLICAS = setDirVar(VARIABLE_KAFKA_NUM_REPLICAS, KAFKA_DEFAULT_NUM_REPLICAS); YARN_DEFAULT_QUOTA = setDirVar(VARIABLE_YARN_DEFAULT_QUOTA, YARN_DEFAULT_QUOTA); YARN_WEB_UI_IP = setIpVar(VARIABLE_YARN_WEB_UI_IP, YARN_WEB_UI_IP); YARN_WEB_UI_PORT = setIntVar(VARIABLE_YARN_WEB_UI_PORT, YARN_WEB_UI_PORT); HDFS_DEFAULT_QUOTA_MBs = setDirVar(VARIABLE_HDFS_DEFAULT_QUOTA, HDFS_DEFAULT_QUOTA_MBs); MAX_NUM_PROJ_PER_USER = setDirVar(VARIABLE_MAX_NUM_PROJ_PER_USER, MAX_NUM_PROJ_PER_USER); HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD = setVar(VARIABLE_HOPSWORKS_SSL_MASTER_PASSWORD, HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD); GLASSFISH_CERT_GENERATED = setVar(VARIABLE_GLASSFISH_CERT_CENERATED, GLASSFISH_CERT_GENERATED); FILE_PREVIEW_IMAGE_SIZE = setIntVar(VARIABLE_FILE_PREVIEW_IMAGE_SIZE, 10000000); FILE_PREVIEW_TXT_SIZE = setIntVar(VARIABLE_FILE_PREVIEW_TXT_SIZE, 100); GVOD_REST_ENDPOINT = setStrVar(VARIABLE_GVOD_REST_ENDPOINT, GVOD_REST_ENDPOINT); PUBLIC_SEARCH_ENDPOINT = setStrVar(VARIABLE_PUBLIC_SEARCH_ENDPOINT, PUBLIC_SEARCH_ENDPOINT); REST_PORT = setIntVar(VARIABLE_REST_PORT, REST_PORT); cached = true; } } private void checkCache() { if (!cached) { populateCache(); } } private static String GLASSFISH_DIR = "/srv/glassfish"; public static synchronized String getGlassfishDir() { return GLASSFISH_DIR; } private String TWOFACTOR_AUTH = "false"; public synchronized String getTwoFactorAuth() { checkCache(); return TWOFACTOR_AUTH; } /** * Default Directory locations */ private String SPARK_DIR = "/srv/spark"; public static final String SPARK_EXAMPLES_DIR = "/examples/jars"; public static final String HOPS_VERSION = "2.4.0"; public static final String SPARK_HISTORY_SERVER_ENV = "spark.yarn.historyServer.address"; public static final String SPARK_NUMBER_EXECUTORS_ENV = "spark.executor.instances"; public static final String SPARK_DYNAMIC_ALLOC_ENV = "spark.dynamicAllocation.enabled"; public static final String SPARK_DYNAMIC_ALLOC_MIN_EXECS_ENV = "spark.dynamicAllocation.minExecutors"; public static final String SPARK_DYNAMIC_ALLOC_MAX_EXECS_ENV = "spark.dynamicAllocation.maxExecutors"; public static final String SPARK_DYNAMIC_ALLOC_INIT_EXECS_ENV = "spark.dynamicAllocation.initialExecutors"; public static final String SPARK_SHUFFLE_SERVICE = "spark.shuffle.service.enabled"; public static final String SPARK_DRIVER_MEMORY_ENV = "spark.driver.memory"; public static final String SPARK_DRIVER_CORES_ENV = "spark.driver.cores"; public static final String SPARK_EXECUTOR_MEMORY_ENV = "spark.executor.memory"; public static final String SPARK_EXECUTOR_CORES_ENV = "spark.executor.cores"; public static final String SPARK_EXECUTOR_EXTRACLASSPATH = "spark.executor.extraClassPath"; public static final String SPARK_CACHE_FILENAMES = "spark.yarn.cache.filenames"; public static final String SPARK_CACHE_SIZES = "spark.yarn.cache.sizes"; public static final String SPARK_CACHE_TIMESTAMPS = "spark.yarn.cache.timestamps"; public static final String SPARK_CACHE_VISIBILITIES = "spark.yarn.cache.visibilities"; public static final String SPARK_CACHE_TYPES = "spark.yarn.cache.types"; public synchronized String getSparkDir() { checkCache(); return SPARK_DIR; } private String SPARK_CONF_DIR = SPARK_DIR + "/conf"; public synchronized String getSparkConfDir(){ checkCache(); return SPARK_CONF_DIR; } private String SPARK_CONF_FILE = SPARK_CONF_DIR + "/spark-defaults.conf"; public synchronized String getSparkConfFile() { //checkCache(); return SPARK_CONF_FILE; } private String ADAM_USER = "glassfish"; public synchronized String getAdamUser() { checkCache(); return ADAM_USER; } private String FLINK_DIR = "/srv/flink"; public synchronized String getFlinkDir() { checkCache(); return FLINK_DIR; } private final String FLINK_CONF_DIR = "conf"; public String getFlinkConfDir() { String flinkDir = getFlinkDir(); return flinkDir + File.separator + FLINK_CONF_DIR; } private final String FLINK_CONF_FILE = "flink-conf.yaml"; public String getFlinkConfFile() { return getFlinkConfDir() + File.separator + FLINK_CONF_FILE; } private String MYSQL_DIR = "/usr/local/mysql"; public synchronized String getMySqlDir() { checkCache(); return MYSQL_DIR; } private String NDB_DIR = "/var/lib/mysql-cluster"; public synchronized String getNdbDir() { checkCache(); return NDB_DIR; } private String ADAM_DIR = "/srv/adam"; public synchronized String getAdamDir() { checkCache(); return ADAM_DIR; } private String HADOOP_DIR = "/srv/hadoop"; public synchronized String getHadoopDir() { checkCache(); return HADOOP_DIR; } private static String HOPSWORKS_INSTALL_DIR = "/srv/glassfish"; public synchronized String getHopsworksInstallDir() { checkCache(); return HOPSWORKS_INSTALL_DIR; } public synchronized String getHopsworksDomainDir() { checkCache(); return HOPSWORKS_INSTALL_DIR + "/domain1"; } public synchronized String getIntermediateCaDir() { checkCache(); return getHopsworksDomainDir() + Settings.CA_DIR; } //User under which yarn is run private String YARN_SUPERUSER = "glassfish"; public synchronized String getYarnSuperUser() { checkCache(); return YARN_SUPERUSER; } private String HDFS_SUPERUSER = "glassfish"; public synchronized String getHdfsSuperUser() { checkCache(); return HDFS_SUPERUSER; } private String SPARK_USER = "glassfish"; public synchronized String getSparkUser() { checkCache(); return SPARK_USER; } private String FLINK_USER = "glassfish"; public synchronized String getFlinkUser() { checkCache(); return FLINK_USER; } private String ZEPPELIN_USER = "glassfish"; public synchronized String getZeppelinUser() { checkCache(); return ZEPPELIN_USER; } private String HIWAY_DIR = "/home/glassfish"; public synchronized String getHiwayDir() { checkCache(); return HIWAY_DIR; } private String YARN_DEFAULT_QUOTA = "60000"; public synchronized String getYarnDefaultQuota() { checkCache(); return YARN_DEFAULT_QUOTA; } private String YARN_WEB_UI_IP = "127.0.0.1"; private int YARN_WEB_UI_PORT = 8088; public synchronized String getYarnWebUIAddress() { checkCache(); return YARN_WEB_UI_IP + ":" + YARN_WEB_UI_PORT; } private String HDFS_DEFAULT_QUOTA_MBs = "200000"; public synchronized long getHdfsDefaultQuotaInMBs() { checkCache(); return Long.parseLong(HDFS_DEFAULT_QUOTA_MBs); } private String MAX_NUM_PROJ_PER_USER = "5"; public synchronized Integer getMaxNumProjPerUser() { checkCache(); int num = 5; try { num = Integer.parseInt(MAX_NUM_PROJ_PER_USER); } catch (NumberFormatException ex) { // should print to log here } return num; } //Hadoop locations public synchronized String getHadoopConfDir() { return hadoopConfDir(getHadoopDir()); } private static String hadoopConfDir(String hadoopDir) { return hadoopDir + "/" + HADOOP_CONF_RELATIVE_DIR; } public static String getHadoopConfDir(String hadoopDir) { return hadoopConfDir(hadoopDir); } public synchronized String getYarnConfDir() { return getHadoopConfDir(); } public static String getYarnConfDir(String hadoopDir) { return hadoopConfDir(hadoopDir); } //Default configuration file names public static final String DEFAULT_YARN_CONFFILE_NAME = "yarn-site.xml"; public static final String DEFAULT_HADOOP_CONFFILE_NAME = "core-site.xml"; public static final String DEFAULT_HDFS_CONFFILE_NAME = "hdfs-site.xml"; public static final String DEFAULT_SPARK_CONFFILE_NAME = "spark-defaults.conf"; //Environment variable keys //TODO: Check if ENV_KEY_YARN_CONF_DIR should be replaced with ENV_KEY_YARN_CONF public static final String ENV_KEY_YARN_CONF_DIR = "hdfs"; public static final String ENV_KEY_HADOOP_CONF_DIR = "HADOOP_CONF_DIR"; public static final String ENV_KEY_YARN_CONF = "YARN_CONF_DIR"; public static final String ENV_KEY_SPARK_CONF_DIR = "SPARK_CONF_DIR"; //YARN constants public static final int YARN_DEFAULT_APP_MASTER_MEMORY = 1024; public static final String YARN_DEFAULT_OUTPUT_PATH = "Logs/Yarn/"; public static final String HADOOP_COMMON_HOME_KEY = "HADOOP_COMMON_HOME"; public static final String HADOOP_HOME_KEY = "HADOOP_HOME"; // private static String HADOOP_COMMON_HOME_VALUE = HADOOP_DIR; public static final String HADOOP_HDFS_HOME_KEY = "HADOOP_HDFS_HOME"; // private static final String HADOOP_HDFS_HOME_VALUE = HADOOP_DIR; public static final String HADOOP_YARN_HOME_KEY = "HADOOP_YARN_HOME"; // private static final String HADOOP_YARN_HOME_VALUE = HADOOP_DIR; public static final String HADOOP_CONF_DIR_KEY = "HADOOP_CONF_DIR"; // public static final String HADOOP_CONF_DIR_VALUE = HADOOP_CONF_DIR; public static final String HADOOP_CONF_RELATIVE_DIR = "etc/hadoop"; public static final String SPARK_CONF_RELATIVE_DIR = "conf"; public static final String YARN_CONF_RELATIVE_DIR = HADOOP_CONF_RELATIVE_DIR; //Spark constants public static final String SPARK_STAGING_DIR = ".sparkStaging"; //public static final String SPARK_LOCRSC_SPARK_JAR = "__spark__.jar"; public static final String SPARK_JARS = "spark.yarn.jars"; public static final String SPARK_ARCHIVE = "spark.yarn.archive"; // Subdirectory where Spark libraries will be placed. public static final String LOCALIZED_LIB_DIR = "__spark_libs__"; public static final String LOCALIZED_CONF_DIR = "__spark_conf__"; public static final String SPARK_LOCRSC_APP_JAR = "__app__.jar"; // Distribution-defined classpath to add to processes public static final String ENV_DIST_CLASSPATH = "SPARK_DIST_CLASSPATH"; public static final String SPARK_AM_MAIN = "org.apache.spark.deploy.yarn.ApplicationMaster"; public static final String SPARK_DEFAULT_OUTPUT_PATH = "Logs/Spark/"; public static final String SPARK_CONFIG_FILE = "conf/spark-defaults.conf"; public static final int SPARK_MIN_EXECS = 1; public static final int SPARK_MAX_EXECS = 300; public static final int SPARK_INIT_EXECS = 1; //Flink constants public static final String FLINK_DEFAULT_OUTPUT_PATH = "Logs/Flink/"; public static final String FLINK_DEFAULT_CONF_FILE = "flink-conf.yaml"; public static final String FLINK_DEFAULT_LOG4J_FILE = "log4j.properties"; public static final String FLINK_DEFAULT_LOGBACK_FILE = "logback.xml"; public static final String FLINK_LOCRSC_FLINK_JAR = "flink.jar"; public static final String FLINK_LOCRSC_APP_JAR = "app.jar"; public static final String FLINK_AM_MAIN = "org.apache.flink.yarn.ApplicationMaster"; public static final int FLINK_APP_MASTER_MEMORY = 768; public static final String FLINK_KAFKA_CERTS_DIR = "/srv/glassfish/domain1/config"; //Zeppelin constants public static final String JAVA_HOME = "/usr/lib/jvm/default-java"; public synchronized String getLocalFlinkJarPath() { return getFlinkDir()+ "/flink.jar"; } public synchronized String getHdfsFlinkJarPath() { return hdfsFlinkJarPath(getFlinkUser()); } private static String hdfsFlinkJarPath(String flinkUser) { return "hdfs:///user/" + flinkUser + "/flink.jar"; } public static String getHdfsFlinkJarPath(String flinkUser) { return hdfsFlinkJarPath(flinkUser); } public synchronized String getFlinkDefaultClasspath() { return flinkDefaultClasspath(getFlinkDir()); } private static String flinkDefaultClasspath(String flinkDir) { //ADAM constants public static final String ADAM_MAINCLASS = "org.bdgenomics.adam.cli.ADAMMain"; // public static final String ADAM_DEFAULT_JAR_HDFS_PATH = "hdfs:///user/adam/repo/adam-cli.jar"; //Or: "adam-cli/target/appassembler/repo/org/bdgenomics/adam/adam-cli/0.15.1-SNAPSHOT/adam-cli-0.15.1-SNAPSHOT.jar" public static final String ADAM_DEFAULT_OUTPUT_PATH = "Logs/Adam/"; public static final String ADAM_DEFAULT_HDFS_REPO = "/user/adam/repo/"; public String getAdamJarHdfsPath() { return "hdfs:///user/" + getAdamUser() + "/adam-cli.jar"; } //Directory names in HDFS public static final String DIR_ROOT = "Projects"; public static final String DIR_SAMPLES = "Samples"; public static final String DIR_RESULTS = "Results"; public static final String DIR_CONSENTS = "consents"; public static final String DIR_BAM = "bam"; public static final String DIR_SAM = "sam"; public static final String DIR_FASTQ = "fastq"; public static final String DIR_FASTA = "fasta"; public static final String DIR_VCF = "vcf"; public static final String DIR_TEMPLATES = "Templates"; public static final String PROJECT_STAGING_DIR = "Resources"; // Elasticsearch private String ELASTIC_IP = "127.0.0.1"; public synchronized String getElasticIp() { checkCache(); return ELASTIC_IP; } public static final int ELASTIC_PORT = 9300; // Spark private String SPARK_HISTORY_SERVER_IP = "127.0.0.1"; public synchronized String getSparkHistoryServerIp() { checkCache(); return SPARK_HISTORY_SERVER_IP + ":18080"; } // Oozie private String OOZIE_IP = "127.0.0.1"; public synchronized String getOozieIp() { checkCache(); return OOZIE_IP; } // MapReduce Job History Server private String JHS_IP = "127.0.0.1"; public synchronized String getJhsIp() { checkCache(); return JHS_IP; } // Livy Server private String LIVY_IP = "127.0.0.1"; private String LIVY_YARN_MODE = "yarn"; public synchronized String getLivyIp() { checkCache(); return LIVY_IP; } public synchronized String getLivyUrl() { return "http://" + getLivyIp() + ":8998"; } public synchronized String getLivyYarnMode() { checkCache(); return LIVY_YARN_MODE; } public static final int ZK_PORT = 2181; // Kibana private String KIBANA_IP = "10.0.2.15"; public static final int KIBANA_PORT = 5601; public synchronized String getKibanaUri() { checkCache(); return "http://" + KIBANA_IP+":"+KIBANA_PORT; } // Zookeeper private String ZK_IP = "10.0.2.15"; public synchronized String getZkConnectStr() { checkCache(); return ZK_IP+":"+ZK_PORT; } private String ZK_USER = "zk"; public synchronized String getZkUser() { checkCache(); return ZK_USER; } // Zeppelin private String ZEPPELIN_DIR = "/srv/zeppelin"; public synchronized String getZeppelinDir() { checkCache(); return ZEPPELIN_DIR; } private String ZEPPELIN_PROJECTS_DIR = "/srv/zeppelin/Projects"; public synchronized String getZeppelinProjectsDir() { checkCache(); return ZEPPELIN_PROJECTS_DIR; } private long ZEPPELIN_SYNC_INTERVAL = 24 * 60 * 60* 1000; public synchronized long getZeppelinSyncInterval(){ checkCache(); return ZEPPELIN_SYNC_INTERVAL; } // Kafka private String KAFKA_IP = "10.0.2.15"; public static final int KAFKA_PORT = 9091; public synchronized String getKafkaConnectStr() { checkCache(); return KAFKA_IP+":"+KAFKA_PORT; } private String KAFKA_USER = "kafka"; public synchronized String getKafkaUser() { checkCache(); return KAFKA_USER; } private String KAFKA_DIR = "/srv/kafka"; public synchronized String getKafkaDir() { checkCache(); return KAFKA_DIR; } private String GVOD_REST_ENDPOINT = "http://10.0.2.15:42000"; public synchronized String getGVodRestEndpoint() { checkCache(); return GVOD_REST_ENDPOINT; } private String PUBLIC_SEARCH_ENDPOINT = "http://10.0.2.15:8080/hopsworks/api/elastic/publicdatasets/"; public synchronized String getPublicSearchEndpoint() { checkCache(); return PUBLIC_SEARCH_ENDPOINT; } private int REST_PORT = 8080; public synchronized int getRestPort() { checkCache(); return REST_PORT; } /** * Generates the Endpoint for kafka. * @return */ public String getRestEndpoint(){ String gvod_endpoint = getGVodRestEndpoint(); String ip = getGVodRestEndpoint().substring(0,gvod_endpoint.lastIndexOf(":")); int port = getRestPort(); return ip+":"+port; } private String HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD = "adminpw"; public synchronized String getHopsworksMasterPasswordSsl() { checkCache(); return HOPSWORKS_DEFAULT_SSL_MASTER_PASSWORD; } private String GLASSFISH_CERT_GENERATED = "false"; public synchronized boolean isGlassfishCertGenerated() { checkCache(); return Boolean.parseBoolean(GLASSFISH_CERT_GENERATED); } private String KAFKA_DEFAULT_NUM_PARTITIONS = "2"; private String KAFKA_DEFAULT_NUM_REPLICAS = "1"; public synchronized String getKafkaDefaultNumPartitions() { checkCache(); return KAFKA_DEFAULT_NUM_PARTITIONS; } public synchronized String getKafkaDefaultNumReplicas() { checkCache(); return KAFKA_DEFAULT_NUM_REPLICAS; } private String ZK_DIR = "/srv/zookeeper"; public synchronized String getZkDir() { checkCache(); return ZK_DIR; } // Dr Elephant private String DRELEPHANT_IP = "127.0.0.1"; private String DRELEPHANT_DB = "hopsworks"; public static int DRELEPHANT_PORT = 11000; public synchronized String getDrElephantUrl() { checkCache(); return "http://" + DRELEPHANT_IP+":"+DRELEPHANT_PORT; } public synchronized String getDrElephantDb() { checkCache(); return DRELEPHANT_DB; } // Hopsworks public static final Charset ENCODING = StandardCharsets.UTF_8; public static final String HOPS_USERS_HOMEDIR = "/home/"; public static final String HOPS_USERNAME_SEPARATOR = "__"; private static String CA_DIR = "/config/ca/intermediate"; public static final String SSL_CREATE_CERT_SCRIPTNAME = "createusercerts.sh"; public static final String SSL_DELETE_CERT_SCRIPTNAME = "deleteusercerts.sh"; public static final String SSL_DELETE_PROJECT_CERTS_SCRIPTNAME = "deleteprojectcerts.sh"; public static final int USERNAME_LEN = 8; public static final int MAX_USERNAME_SUFFIX = 99; public static final int MAX_RETRIES = 500; public static final String META_NAME_FIELD = "name"; public static final String META_DESCRIPTION_FIELD = "description"; public static final String META_INDEX = "projects"; public static final String META_PROJECT_TYPE = "proj"; public static final String META_DATASET_TYPE = "ds"; public static final String META_INODE_TYPE = "inode"; public static final String META_PROJECT_ID_FIELD = "project_id"; public static final String META_ID = "_id"; public static final String META_DATA_NESTED_FIELD = "xattr"; public static final String META_DATA_FIELDS = META_DATA_NESTED_FIELD + ".*"; //Filename conventions public static final String FILENAME_DISALLOWED_CHARS = " /\\?*:|'\"<>%()&; public static final String PRINT_FILENAME_DISALLOWED_CHARS = "__, space, /, \\, ?, *, :, |, ', \", <, >, %, (, ), &, ;, public static final String SHARED_FILE_SEPARATOR = "::"; public static final String DOUBLE_UNDERSCORE = "__"; public static final String KAFKA_K_CERTIFICATE = "kafka_k_certificate"; public static final String KAFKA_T_CERTIFICATE = "kafka_t_certificate"; public static final String TMP_CERT_STORE_LOCAL = "/srv/glassfish/kafkacerts"; public static final String TMP_CERT_STORE_REMOTE = "/user/glassfish/kafkacerts"; //Used to retrieve schema by KafkaUtil public static final String KAFKA_SESSIONID_ENV_VAR = "hopsworks.sessionid"; public static final String KAFKA_PROJECTID_ENV_VAR = "hopsworks.projectid"; public static final String KAFKA_BROKERADDR_ENV_VAR = "hopsworks.kafka.brokeraddress"; public static final String KAFKA_JOB_ENV_VAR = "hopsworks.kafka.job"; public static final String KAFKA_JOB_TOPICS_ENV_VAR = "hopsworks.kafka.job.topics"; public static final String KEYSTORE_PASSWORD_ENV_VAR = "hopsworks.keystore.password"; public static final String TRUSTSTORE_PASSWORD_ENV_VAR = "hopsworks.truststore.password"; public static final String KAFKA_CONSUMER_GROUPS = "hopsworks.kafka.consumergroups"; public static final String KAFKA_REST_ENDPOINT_ENV_VAR = "hopsworks.kafka.restendpoint"; public static int FILE_PREVIEW_IMAGE_SIZE = 10000000; public static int FILE_PREVIEW_TXT_SIZE = 100; public static int FILE_PREVIEW_TXT_SIZE_BYTES = 1024*128; public static int FILE_PREVIEW_TXT_SIZE_BYTES_README = 1024*512; public static String README_TEMPLATE = "*This is an auto-generated README.md" + " file for your Dataset!*\n" + "To replace it, go into your DataSet and edit the README.md file.\n" + "\n" + "*%s* DataSet\n" + "===\n" + "\n" + " //Dataset request subject public static String MESSAGE_DS_REQ_SUBJECT = "Dataset access request."; // QUOTA public static final float DEFAULT_YARN_MULTIPLICATOR = 1.0f; /** * Returns the maximum image size in bytes that can be previewed in the * browser. * @return */ public synchronized int getFilePreviewImageSize() { checkCache(); return FILE_PREVIEW_IMAGE_SIZE; } /** * Returns the maximum number of lines of the file that can be previewed in the * browser. * @return */ public synchronized int getFilePreviewTxtSize() { checkCache(); return FILE_PREVIEW_TXT_SIZE; } //Project creation: default datasets public static enum DefaultDataset { LOGS("Logs", "Contains the logs for jobs that have been run through the Hopsworks platform."), RESOURCES("Resources", "Contains resources used by jobs, for example, jar files."), NOTEBOOKS("notebook", "Contains zeppelin notebooks."); private final String name; private final String description; private DefaultDataset(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } } public Settings() { } /** * Get the variable value with the given name. * <p/> * @param id * @return The user with given email, or null if no such user exists. */ public Variables findById(String id) { try { return em.createNamedQuery("Variables.findById", Variables.class ).setParameter("id", id).getSingleResult(); } catch (NoResultException e) { return null; } } // public void setIdValue(String id, String value) { // Variables v = new Variables(id, value); // try { // em.persist(v) // } catch (EntityExistsException ex) { public void detach(Variables variable) { em.detach(variable); } public static String getProjectPath(String projectname) { return File.separator + DIR_ROOT + File.separator + projectname; } }
package seedu.ezdo.model.todo; import seedu.ezdo.commons.exceptions.IllegalValueException; import seedu.ezdo.logic.parser.DateParser; /** * Represents the date associated with tasks. */ public abstract class TaskDate { public String value; public static final String TASKDATE_VALIDATION_REGEX = "^$|(0[1-9]|" + "[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)[0-9]{2} " + "(2[0-3]|[0-1][0-9])[:][0-5][0-9]"; public static final String FIND_TASKDATE_VALIDATION_REGEX = "^$|(0[1-9]|[12][0-9]|3[01])" + "[/](0[1-9]|1[012])[/](19|20)[0-9]{2}"; public static final String MESSAGE_FIND_DATE_CONSTRAINTS = "Please enter a date in this form: DD/MM/YYYY or in the natural language"; public TaskDate(String taskDate) { DateParser dateParser = new DateParser(taskDate); this.value = dateParser.value; } public TaskDate(String taskDate, boolean isFind) throws IllegalValueException { String trimmedDate = taskDate.trim(); assert trimmedDate != null; DateParser dateParser = new DateParser(taskDate); this.value = dateParser.value; } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof TaskDate // instanceof handles nulls && this.value.equals(((TaskDate) other).value)); // state // check } @Override public int hashCode() { return value.hashCode(); } /** * Returns true if a given string is a valid task date. */ public static boolean isValidTaskDate(String test) { return test.matches(TASKDATE_VALIDATION_REGEX); } }
package seedu.unburden.model.task; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Objects; import seedu.unburden.commons.core.Messages; import seedu.unburden.commons.exceptions.IllegalValueException; import seedu.unburden.commons.util.CollectionUtil; import seedu.unburden.model.tag.Tag; import seedu.unburden.model.tag.UniqueTagList; import seedu.unburden.model.tag.UniqueTagList.DuplicateTagException; /** * Represents a Task in the address book. * Guarantees: details are present and not null, field values are validated. * @@author A0143095H */ public class Task implements ReadOnlyTask, Comparable<Task> { private Name name; private TaskDescription taskD; private Date date; private Time startTime; private Time endTime; private UniqueTagList tags; private boolean done; private String getDoneString; private static final SimpleDateFormat DATEFORMATTER = new SimpleDateFormat("dd-MM-yyyy"); public Task(Name name, TaskDescription taskD, Date date, Time startTime, Time endTime, Boolean done,UniqueTagList tags) throws IllegalValueException { assert !CollectionUtil.isAnyNull(name, taskD, date, startTime, endTime, tags); if(startTime.compareTo(endTime) < 0){ throw new IllegalValueException(Messages.MESSAGE_STARTTIME_AFTER_ENDTIME); } this.name = name; this.taskD = taskD; this.date = date; this.startTime = startTime; this.endTime = endTime; this.done = done; this.tags = tags; // protect internal tags from changes in the arg list } public Task(ReadOnlyTask source) throws IllegalValueException { this(source.getName(), source.getTaskDescription(), source.getDate(), source.getStartTime(), source.getEndTime(), source.getDone(),source.getTags()); } //@@Nathanael Chan A0139678J // adds event public Task(Name name, TaskDescription taskD, Date date, Time startTime, Time endTime, UniqueTagList tags) throws IllegalValueException { assert !CollectionUtil.isAnyNull(name, taskD, date, startTime, endTime, tags); if(startTime.compareTo(endTime) < 0){ throw new IllegalValueException(Messages.MESSAGE_STARTTIME_AFTER_ENDTIME); } this.name = name; this.taskD = taskD; this.date = date; this.startTime = startTime; this.endTime = endTime; //this.getDoneString = getDoneString; this.tags = tags; // protect internal tags from changes in the arg list } // adds event without description public Task(Name name,Date date, Time startTime, Time endTime, UniqueTagList tags) throws IllegalValueException { assert !CollectionUtil.isAnyNull(name, date, startTime, endTime, tags); if(startTime.compareTo(endTime) < 0){ throw new IllegalValueException(Messages.MESSAGE_STARTTIME_AFTER_ENDTIME); } this.name = name; this.taskD = new TaskDescription(""); this.date = date; this.startTime = startTime; this.endTime = endTime; this.tags = tags; // protect internal tags from changes in the arg list } // adds deadline public Task(Name name, TaskDescription taskD, Date date, Time endTime, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, taskD, date, endTime, tags); this.name = name; this.taskD = taskD; this.date = date; this.startTime = new Time(""); this.endTime = endTime; this.tags = tags; } // adds deadline without task description public Task(Name name, Date date, Time endTime, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, date, endTime, tags); this.name = name; this.taskD = new TaskDescription(""); this.date = date; this.startTime = new Time(""); this.endTime = endTime; this.tags = tags; } // adds deadline without task description and time public Task(Name name, Date date, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, date, tags); this.name = name; this.taskD = new TaskDescription(""); this.date = date; this.startTime = new Time(""); this.endTime = new Time(""); this.tags = tags; } // adds deadline without task description and date public Task(Name name, Time endTime, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, endTime, tags); this.name = name; this.taskD = new TaskDescription(""); this.date = new Date(""); this.startTime = new Time(""); this.endTime = endTime; this.tags = tags; } // adds deadline without date public Task(Name name, TaskDescription taskD, Time endTime, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, taskD, endTime, tags); this.name = name; this.taskD = taskD; this.date = new Date(""); this.startTime = new Time(""); this.endTime = endTime; this.tags = tags; } // adds deadline without time public Task(Name name, TaskDescription taskD, Date date, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, taskD, date, tags); this.name = name; this.taskD = taskD; this.date = date; this.startTime = new Time(""); this.endTime = new Time(""); this.tags = tags; } // adds floating Task public Task(Name name, TaskDescription taskD, UniqueTagList tags) throws IllegalValueException { assert !CollectionUtil.isAnyNull(name, taskD, tags); this.name = name; this.taskD = taskD; this.date = new Date(""); this.startTime = new Time(""); this.endTime = new Time(""); this.tags = tags; } // adds floating task without task description public Task(Name name, UniqueTagList tags) throws IllegalValueException { assert!CollectionUtil.isAnyNull(name, tags); this.name = name; this.taskD = new TaskDescription(""); this.date = new Date(""); this.startTime = new Time(""); this.endTime = new Time(""); this.tags = tags; } //@@Nathanael Chan /** * Copy constructor. */ //@@Gauri Joshi A0143095H // public Task(ReadOnlyTask source) { // this(source.getName(), source.getTaskDescription(), source.getDate(), source.getStartTime(), source.getEndTime(), source.getTags()); @Override public Name getName() { return name; } @Override public TaskDescription getTaskDescription() { return taskD; } @Override public Date getDate() { return date; } @Override public Time getStartTime() { return startTime; } @Override public Time getEndTime() { return endTime; } @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } //@@Gauri Joshi A0143095H @Override public boolean getDone() { return done; } public String getDoneString(){ if(done){ getDoneString = "Done!"; } else { getDoneString = "Undone!"; } return getDoneString; } //@@Gauri Joshi A0143095H /** * Replaces this person's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } public void setName(Name name) { this.name = name; } public void setTaskDescription(TaskDescription taskD) { this.taskD = taskD; } public void setDate(Date date) { this.date = date; } public void setStartTime(Time startTime) { this.startTime = startTime; } public void setEndTime(Time endTime) { this.endTime = endTime; } public void setDone(boolean done) { this.done = done; } public boolean overDue() throws IllegalValueException{ Calendar calendar = Calendar.getInstance(); calendar.setTime(calendar.getTime()); if(this.getDate().compareTo(new Date(DATEFORMATTER.format(calendar.getTime()))) < 0){ return true; } return false; } public void setOverdue() throws DuplicateTagException, IllegalValueException{ this.tags.add(new Tag("Overdue")); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyTask // instanceof handles nulls && this.isSameStateAs((ReadOnlyTask) other)); } @Override public int compareTo(Task task) { if (this.getDate().compareTo(task.getDate()) == 0) { // two objects have the same date, compare end times if (this.getEndTime().compareTo(task.getEndTime()) == 0) { return this.getStartTime().compareTo(task.getStartTime()); } else { return this.getEndTime().compareTo(task.getEndTime()); } } else { return this.getDate().compareTo(task.getDate()); } } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(name,taskD,date,startTime,endTime, tags); } //@@Gauri Joshi @Override public String toString() { return getAsText(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.bridgedb.uri; import java.util.HashSet; import java.util.Set; import org.bridgedb.DataSource; import org.bridgedb.Xref; import org.bridgedb.sql.SQLUriMapper; import org.bridgedb.uri.api.Mapping; import org.bridgedb.uri.lens.Lens; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; /** * * @author Christian */ public abstract class UriMapperNullTargetTest extends UriListenerTest{ private static final String NULL_GRAPH = null; private static final Boolean DEFAULT_IGNORE = null; private static final Set<DataSource> NO_TARGET_DATA_SOURCES = null; private static final Set<String> NO_PATTERNS = null; /** * Test of mapID method, of class UriMapper. */ @Test public void testMapID_sourceXref_lensId_tgtDataSources_first_null() throws Exception { report("MapID_sourceXref_lensId_tgtDataSources_first_null"); Xref sourceXref = map2xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(null); targets.add(DataSource3); Set<Xref> results = uriMapper.mapID(sourceXref, lensId, targets); assertFalse(results.contains(map2xref1)); assertFalse(results.contains(map2xref2)); assertTrue(results.contains(map2xref3)); assertFalse(results.contains(map1xref2)); assertFalse(results.contains(map1xref1)); assertFalse(results.contains(map3xref2)); checkForNoOtherLensXrefs(results); } /** * Test of mapID method, of class UriMapper. */ @Test public void testMapID_sourceXref_lensId_tgtDataSources_second_null() throws Exception { report("MapID_sourceXref_lensId_tgtDataSources_second_null"); Xref sourceXref = map2xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(DataSource2); targets.add(null); Set<Xref> results = uriMapper.mapID(sourceXref, lensId, targets); assertFalse(results.contains(map2xref1)); assertTrue(results.contains(map2xref2)); assertFalse(results.contains(map2xref3)); assertFalse(results.contains(map1xref2)); assertFalse(results.contains(map1xref1)); assertFalse(results.contains(map3xref2)); checkForNoOtherLensXrefs(results); } /** * Test of mapID method, of class UriMapper. */ @Test public void testMapID_sourceXref_lensId_tgtDataSource() throws Exception { report("MapID_sourceXref_lensId_tgtDataSource"); Xref sourceXref = map2xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> tgtDataSources = new HashSet<DataSource>(); tgtDataSources.add(null); Set results = uriMapper.mapID(sourceXref, lensId, tgtDataSources); assertTrue(results.isEmpty()); } /** * Test of mapID method, of class UriMapper. */ @Test public void testMapID_sourceXref_lensId_null_array() throws Exception { report("MapID_sourceXref_lensId_null_array"); Xref sourceXref = map2xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set results = uriMapper.mapID(sourceXref, lensId, NO_TARGET_DATA_SOURCES); assertTrue(results.contains(map2xref1)); assertTrue(results.contains(map2xref2)); assertTrue(results.contains(map2xref3)); assertFalse(results.contains(map1xref2)); assertFalse(results.contains(map1xref1)); assertFalse(results.contains(map3xref2)); checkForNoOtherLensXrefs(results); } /** * Test of mapID method, of class UriMapper. */ @Test public void testMapID_sourceXref_lensId_empty_array() throws Exception { report("MapID_sourceXref_lensId_empty_array"); Xref sourceXref = map2xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); Set results = uriMapper.mapID(sourceXref, lensId, targets ); assertTrue(results.contains(map2xref1)); assertTrue(results.contains(map2xref2)); assertTrue(results.contains(map2xref3)); assertFalse(results.contains(map1xref2)); assertFalse(results.contains(map1xref1)); assertFalse(results.contains(map3xref2)); checkForNoOtherLensXrefs(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUri_lensId_tgtUriPatterns_first_null() throws Exception { report("MapUri_sourceUri_lensId_tgtUriPatterns_first_null"); String sourceUri = map3Uri3; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(null); tgtUriPatterns.add(stringPattern3); Set results = uriMapper.mapUri(sourceUri, lensId, NULL_GRAPH, tgtUriPatterns); assertFalse(results.contains(map3Uri1)); assertFalse(results.contains(map3Uri2)); assertFalse(results.contains(map3Uri2a)); assertTrue(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUri_lensId_tgtUriPatterns_second_null() throws Exception { report("MapUri_sourceUri_lensId_tgtUriPatterns_second_null"); String sourceUri = map3Uri3; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(stringPattern2); tgtUriPatterns.add(null); Set results = uriMapper.mapUri(sourceUri, lensId, NULL_GRAPH, tgtUriPatterns); assertFalse(results.contains(map3Uri1)); assertTrue(results.contains(map3Uri2)); assertFalse(results.contains(map3Uri2a)); assertFalse(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceXref_lensId_tgtUriPattern() throws Exception { report("MapUri_sourceXref_lensId_tgtUriPattern"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = new HashSet<String>(); targets.add(null); Set results = uriMapper.mapUri(sourceXref, lensId, NULL_GRAPH, targets); assertTrue(results.isEmpty()); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceXref_lensId_null_pattern() throws Exception { report("MapUri_sourceXref_lensId_null_pattern"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = null; Set results = uriMapper.mapUri(sourceXref, lensId, NULL_GRAPH, targets); assertTrue(results.contains(map3Uri1)); assertTrue(results.contains(map3Uri2)); assertTrue(results.contains(map3Uri2a)); assertTrue(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceXref_lensId_empty_pattern() throws Exception { report("MapUri_sourceXref_lensId"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = new HashSet<String>(); Set results = uriMapper.mapUri(sourceXref, lensId, NULL_GRAPH, targets); assertTrue(results.contains(map3Uri1)); assertTrue(results.contains(map3Uri2)); assertTrue(results.contains(map3Uri2a)); assertTrue(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceXref_lensId_tgtUriPatterns_second__null() throws Exception { report("MapUri_sourceXref_lensId_tgtUriPatterns_second_null"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(stringPattern2); tgtUriPatterns.add(null); Set results = uriMapper.mapUri(sourceXref, lensId, NULL_GRAPH, tgtUriPatterns); assertFalse(results.contains(map3Uri1)); assertTrue(results.contains(map3Uri2)); assertFalse(results.contains(map3Uri2a)); assertFalse(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceXref_lensId_tgtUriPatterns_first_null() throws Exception { report("MapUri_sourceXref_lensId_tgtUriPatterns_first_null"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(null); tgtUriPatterns.add(stringPattern3); Set results = uriMapper.mapUri(sourceXref, lensId, NULL_GRAPH, tgtUriPatterns); assertFalse(results.contains(map3Uri1)); assertFalse(results.contains(map3Uri2)); assertFalse(results.contains(map3Uri2a)); assertTrue(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUri_lensId_tgtUriPattern() throws Exception { report("MapUri_sourceUri_lensId_tgtUriPattern"); String sourceUri = map3Uri2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPattern = new HashSet<String>(); tgtUriPattern.add(null); Set results = uriMapper.mapUri(sourceUri, lensId, NULL_GRAPH, tgtUriPattern); assertTrue(results.isEmpty()); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUri_lensId_null_target() throws Exception { report("MapUri_sourceUri_lensId_null_target"); String sourceUri = map3Uri2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = null; Set results = uriMapper.mapUri(sourceUri, lensId, NULL_GRAPH, targets); assertTrue(results.contains(map3Uri1)); assertTrue(results.contains(map3Uri2)); assertTrue(results.contains(map3Uri2a)); assertTrue(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapUri method, of class UriMapper. */ @Test public void testMapUri_sourceUri_lensId_empty_targets() throws Exception { report("MapUri_sourceUri_lensId_empty_targets"); String sourceUri = map3Uri2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = new HashSet<String>(); Set results = uriMapper.mapUri(sourceUri, lensId, NULL_GRAPH, targets); assertTrue(results.contains(map3Uri1)); assertTrue(results.contains(map3Uri2)); assertTrue(results.contains(map3Uri2a)); assertTrue(results.contains(map3Uri3)); assertFalse(results.contains(map2Uri2)); assertFalse(results.contains(map1Uri3)); checkForNoOtherlensId(results); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_tgtDataSources_first_null() throws Exception { report("MapFull_sourceXref_lensId_tgtDataSources_first_null"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(null); targets.add(DataSource3); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, true, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); Set<Integer> ids = new HashSet<Integer>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, not(hasItem(map3Uri2))); assertThat(targetUris, not(hasItem(map3Uri2a))); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, not(hasItem(map3xref2))); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_tgtDataSources_second_null() throws Exception { report("MapFull_sourceXref_lensId_tgtDataSources_second_null"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(DataSource2); targets.add(null); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, true, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, not(hasItem(map3Uri3))); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, not(hasItem(map3xref3))); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_tgtDataSource() throws Exception { report("MapFull_sourceXref_lensId_tgtDataSources"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> tgtDataSource = new HashSet<DataSource>(); tgtDataSource.add(null); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, DEFAULT_IGNORE, tgtDataSource); assertTrue(results.isEmpty()); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_null_tgtDataSources() throws Exception { report("MapFull_sourceXref_lensId_null_tgtDataSources"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = null; Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, true, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_empty_tgtDataSources() throws Exception { report("MapFull_sourceXref_lensId_empty_tgtDataSources"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, true, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_null_UriPatterns() throws Exception { report("MapFull_sourceXref_lensId_null_UriPatterns"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = null; Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, NULL_GRAPH, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_empty_UriPatterns() throws Exception { report("MapFull_sourceXref_lensId_empty_UriPatterns"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = new HashSet<String>(); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, NULL_GRAPH, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_tgtUriPatterns_first_null() throws Exception { report("MapFull_sourceXref_lensId_tgtUriPatterns_first_null"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(null); tgtUriPatterns.add(stringPattern3); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, NULL_GRAPH, tgtUriPatterns); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, not(hasItem(map3Uri2))); assertThat(targetUris, not(hasItem(map3Uri2a))); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, not(hasItem(map3xref2))); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_tgtUriPatterns_second_null() throws Exception { report("MapFull_sourceXref_lensId_tgtUriPatterns_second_null"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(stringPattern2); tgtUriPatterns.add(null); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, NULL_GRAPH, tgtUriPatterns); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, not(hasItem(map3Uri2a))); assertThat(targetUris, not(hasItem(map3Uri3))); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, not(hasItem(map3xref3))); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceXref_lensId_tgtUriPattern() throws Exception { //No way to pass an empty set via webservices org.junit.Assume.assumeTrue(uriMapper instanceof SQLUriMapper); report("MapFull_sourceXref_lensId_tgtUriPattern"); Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(null); Set<Mapping> results = uriMapper.mapFull(sourceXref, lensId, NULL_GRAPH, tgtUriPatterns); assertTrue(results.isEmpty()); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceUri_lensId_tgtDataSources_first_null() throws Exception { report("MapFull_sourceUri_lensId_tgtDataSources_first_null"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(null); targets.add(DataSource3); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, not(hasItem(map3Uri2))); assertThat(targetUris, not(hasItem(map3Uri2a))); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, not(hasItem(map3xref2))); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceUri_lensId_tgtDataSources_second_null() throws Exception { report("MapFull_sourceUri_lensId_tgtDataSources_second_null"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(DataSource2); targets.add(null); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, not(hasItem(map3Uri3))); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, not(hasItem(map3xref3))); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceUri_lensId_tgtDataSource() throws Exception { report("MapFull_sourceUri_lensId_tgtDataSource"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); targets.add(null); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, targets); assertTrue(results.isEmpty()); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_MapFull_sourceUri_lensId_null_DataSources() throws Exception { report("MapFull_sourceUri_lensId_null_DataSources"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = null; Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_MapFull_sourceUri_lensId_empty_dataSources() throws Exception { report("MapFull_sourceUri_lensId_empty_dataSources"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<DataSource> targets = new HashSet<DataSource>(); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ if (uriMapper instanceof SQLUriMapper){ //Skip this tes for Webservice is it would need IncludedXrefResults set to true //Which this call does not allow assertEquals(sourceXref, mapping.getSource()); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetXrefs.add(mapping.getTarget()); } assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); targetUris.addAll(mapping.getTargetUri()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); //Skip this tes for Webservice is it would need IncludedXrefResults set to true //Which this call does not allow if (uriMapper instanceof SQLUriMapper){ assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_MapFull_sourceUri_lensId_null_patterns() throws Exception { report("MapFull_sourceUri_lensId_null_patterns"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = null; Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, true, NULL_GRAPH, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_MapFull_sourceUri_lensId_null_patterns_noXrefs() throws Exception { report("MapFull_sourceUri_lensId_null_patterns_noXrefs"); String sourceUri = map3Uri2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = null; Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, false, NULL_GRAPH, targets); for (Mapping mapping:results){ assertTrue(mapping.getSource() == null); assertTrue(mapping.getTarget() == null); } } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_MapFull_sourceUri_lensId_null_patterns_noXrefs_default() throws Exception { report("MapFull_sourceUri_lensId_null_patterns_default"); String sourceUri = map3Uri2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = null; Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, DEFAULT_IGNORE, NULL_GRAPH, targets); for (Mapping mapping:results){ assertTrue(mapping.getSource() == null); assertTrue(mapping.getTarget() == null); } } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_MapFull_sourceUri_lensId_empty_patterns() throws Exception { report("MapFull_sourceUri_lensId_empty_patterns"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = new HashSet<String>(); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, true, NULL_GRAPH, targets); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, hasItem(map3Uri1)); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, hasItem(map3Uri2a)); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, hasItem(map3xref1)); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceUri_lensId_tgtUriPattern() throws Exception { //No way to pass an empty set via webservices org.junit.Assume.assumeTrue(uriMapper instanceof SQLUriMapper); report("MapFull_sourceUri_lensId_tgtUriPattern"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> targets = new HashSet<String>(); targets.add(null); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, DEFAULT_IGNORE, NULL_GRAPH, targets); assertTrue(results.isEmpty()); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceUri_lensId_tgtUriPatterns_first_null() throws Exception { report("MapFull_sourceUri_lensId_tgtUriPatterns_first_null"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(null); tgtUriPatterns.add(stringPattern3); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, true, NULL_GRAPH, tgtUriPatterns); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, not(hasItem(map3Uri2))); assertThat(targetUris, not(hasItem(map3Uri2a))); assertThat(targetUris, hasItem(map3Uri3)); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, not(hasItem(map3xref2))); assertThat(targetXrefs, hasItem(map3xref3)); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } /** * Test of mapFull method, of class UriMapper. */ @Test public void testMapFull_sourceUri_lensId_tgtUriPatterns_second_null() throws Exception { report("MapFull_sourceUri_lensId_tgtUriPatterns_second_null"); String sourceUri = map3Uri2; Xref sourceXref = map3xref2; String lensId = Lens.DEFAULT_LENS_NAME; Set<String> tgtUriPatterns = new HashSet<String>(); tgtUriPatterns.add(stringPattern2); tgtUriPatterns.add(null); Set<Mapping> results = uriMapper.mapFull(sourceUri, lensId, true, NULL_GRAPH, tgtUriPatterns); Set<String> targetUris = new HashSet<String>(); Set<Xref> targetXrefs = new HashSet<Xref>(); for (Mapping mapping:results){ assertEquals(sourceXref, mapping.getSource()); assertTrue(mapping.getSourceUri().contains(sourceUri)); assertTrue(mapping.getSourceUri().size() == 1); if (!mapping.getTarget().equals(sourceXref)){ assertThat(mapping.getPredicate(), not(equalTo(null))); assertThat(mapping.getMappingSetId(), not(equalTo(null))); } targetUris.addAll(mapping.getTargetUri()); targetXrefs.add(mapping.getTarget()); } assertThat(targetUris, not(hasItem(map3Uri1))); assertThat(targetUris, hasItem(map3Uri2)); assertThat(targetUris, not(hasItem(map3Uri2a))); assertThat(targetUris, not(hasItem(map3Uri3))); assertThat(targetUris, not(hasItem(map2Uri2))); assertThat(targetUris, not(hasItem(map1Uri3))); checkForNoOtherlensId(targetUris); assertThat(targetXrefs, not(hasItem(map3xref1))); assertThat(targetXrefs, hasItem(map3xref2)); assertThat(targetXrefs, not(hasItem(map3xref3))); assertThat(targetXrefs, not(hasItem(map1xref2))); assertThat(targetXrefs, not(hasItem(map1xref1))); assertThat(targetXrefs, not(hasItem(map2xref2))); } }
package server.service; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import server.entity.Status; import static server.service.TmdbServiceImpl.Cache.MOVIE; import static server.service.TmdbServiceImpl.Cache.SEARCH; public class TmdbServiceImpl extends CachingServiceImpl<JsonObject> implements TmdbService { private static final Logger log = LoggerFactory.getLogger(TmdbServiceImpl.class); private static final int HTTPS = 443; private static final String ENDPOINT = "api.themoviedb.org"; private static final String APIKEY_PREFIX1 = "&api_key="; private static final String APIKEY_PREFIX2 = "?api_key="; private static final String APIKEY = "tmdb_key"; private static final String MOVIE_NAME = "/3/search/movie?query="; private static final String MOVIE_ID = "/3/movie/"; private final Vertx vertx; private final JsonObject config; private final HttpClient client; protected TmdbServiceImpl(Vertx vertx, JsonObject config) { super(CachingServiceImpl.DEFAULT_MAX_CACHE_SIZE); this.vertx = vertx; this.config = config; this.client = vertx.createHttpClient(new HttpClientOptions().setSsl(true)); } @Override public Future<JsonObject> getMovieByName(String name) { return get(MOVIE_NAME + name + APIKEY_PREFIX1, getCached(SEARCH.get(name))); } @Override public Future<JsonObject> getMovieById(String id) { return get(MOVIE_ID + id + APIKEY_PREFIX2, getCached(MOVIE.get(id))); } private Future<JsonObject> get(String uri, CacheItem<JsonObject> cache) { Future<JsonObject> future = Future.future(); if (!tryCachedResult(true, cache, future)) { client.get(HTTPS, ENDPOINT, uri + config.getString(APIKEY, ""), response -> handleResponse(response, cache, future)).end(); } return future; } private void handleResponse(HttpClientResponse response, CacheItem<JsonObject> cache, Future<JsonObject> future) { if (response.statusCode() == Status.OK) { response.bodyHandler(body -> future.complete(cache.set(body.toJsonObject()))); } else { future.fail("API returned code: " + response.statusCode() + "; message: " + response.statusMessage()); } } public enum Cache { SEARCH("search_"), MOVIE("movie_"); private final String prefix; Cache(String prefix) { this.prefix = prefix; } public String get(String id) { return prefix + id; } } }
package org.hive2hive.core.security; import org.hive2hive.core.H2HConstants; /** * This stores a user's credentials. Do not change the password or the PIN manually by using * setters but rather define both parameters from scratch. The PIN needs to be unique per-user per-password. * * @author Christian * */ public final class UserCredentials { private final String userId; private final String password; private final String pin; private String locationCache = null; public UserCredentials(String userId, String password, String pin) { this.userId = userId; this.password = password; this.pin = pin; } public String getUserId() { return userId; } public String getPassword() { return password; } public String getPin() { return pin; } /** * Calculates the location for this {@link UserCredentials}. Once calculated, the location gets cached and * directly returned on further invokes. * * @return The location key associated with this credentials. */ public String getProfileLocationKey() { if (locationCache != null) return locationCache; // concatenate PIN + PW + UserId String location = new StringBuilder().append(pin).append(password).append(userId).toString(); // create fixed salt based on location byte[] fixedSalt = PasswordUtil.generateFixedSalt(location.getBytes()); // hash the location byte[] locationKey = PasswordUtil.generateHash(location.toCharArray(), fixedSalt); locationCache = new String(locationKey, H2HConstants.ENCODING_CHARSET); return locationCache; } }
package skyhussars.utility; import java.util.List; import static java.util.Objects.requireNonNull; public class Collections { public static class ZList<T> { private final List<T> list; private ZList(List<T> list){ this.list = requireNonNull(list); } public ZList add(T elem){ list.add(elem); return this; } public List<T> unwrap(){ return list; } } public static <T> ZList zList(List<T> list){ return new ZList(list); } }
package tehnut.stable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Mod(modid = StabilityTooltip.MODID, name = StabilityTooltip.NAME, version = StabilityTooltip.VERSION, dependencies = "after:Waila", canBeDeactivated = true, acceptedMinecraftVersions = "[1.8,)") public class StabilityTooltip { public static final String MODID = "StabilityTooltip"; public static final String NAME = "StabilityTooltip"; public static final String VERSION = "@VERSION@"; public Map<String, EnumStability> stabilityMap = new HashMap<String, EnumStability>(); @Mod.Instance public static StabilityTooltip instance; public File jsonConfig; public Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().disableHtmlEscaping().create(); @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { MinecraftForge.EVENT_BUS.register(instance); try { jsonConfig = new File(event.getModConfigurationDirectory(), NAME + ".json"); if (!jsonConfig.exists() && jsonConfig.createNewFile()) { Map<String, EnumStability> defaultMap = new HashMap<String, EnumStability>(); defaultMap.put("minecraft", EnumStability.STABLE); String json = gson.toJson(defaultMap, new TypeToken<Map<String, EnumStability>>(){ }.getType()); FileWriter writer = new FileWriter(jsonConfig); writer.write(json); writer.close(); } stabilityMap = gson.fromJson(new FileReader(jsonConfig), new TypeToken<Map<String, EnumStability>>(){ }.getType()); } catch (IOException e) { e.printStackTrace(); } } @SubscribeEvent(priority = EventPriority.LOWEST) public void onTooltip(ItemTooltipEvent event) { ItemStack stack = event.itemStack; EnumStability stability = stabilityMap.get(getModidFromStack(stack)); if (stability != null) event.toolTip.add(String.format(StatCollector.translateToLocal("desc.stability.format").replace("&", "\u00A7"), stability.getFancyDescription())); } private static String getModidFromStack(ItemStack stack) { Item check = stack.getItem(); ResourceLocation info = Item.itemRegistry.getNameForObject(check); return info.toString().split(":")[0]; } }
package cuchaz.enigma.analysis; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.strobel.decompiler.languages.Region; import com.strobel.decompiler.languages.java.ast.AstNode; import com.strobel.decompiler.languages.java.ast.Identifier; import cuchaz.enigma.mapping.Entry; public class SourceIndex { private String m_source; private TreeMap<Token,EntryReference<Entry,Entry>> m_tokenToReference; private Multimap<EntryReference<Entry,Entry>,Token> m_referenceToTokens; private Map<Entry,Token> m_declarationToToken; private List<Integer> m_lineOffsets; private boolean m_ignoreBadTokens; public SourceIndex(String source) { this(source, false); } public SourceIndex(String source, boolean ignoreBadTokens) { m_source = source; m_ignoreBadTokens = ignoreBadTokens; m_tokenToReference = Maps.newTreeMap(); m_referenceToTokens = HashMultimap.create(); m_declarationToToken = Maps.newHashMap(); m_lineOffsets = Lists.newArrayList(); // count the lines m_lineOffsets.add(0); for (int i = 0; i < source.length(); i++) { if (source.charAt(i) == '\n') { m_lineOffsets.add(i + 1); } } } public String getSource() { return m_source; } public Token getToken(AstNode node) { // get the text of the node String name = ""; if (node instanceof Identifier) { name = ((Identifier)node).getName(); } // get a token for this node's region Region region = node.getRegion(); if (region.getBeginLine() == 0 || region.getEndLine() == 0) { // DEBUG System.err.println(String.format("WARNING: %s \"%s\" has invalid region: %s", node.getNodeType(), name, region)); return null; } Token token = new Token( toPos(region.getBeginLine(), region.getBeginColumn()), toPos(region.getEndLine(), region.getEndColumn()), m_source ); if (token.start == 0) { // DEBUG System.err.println(String.format("WARNING: %s \"%s\" has invalid start: %s", node.getNodeType(), name, region)); return null; } // DEBUG // System.out.println( String.format( "%s \"%s\" region: %s", node.getNodeType(), name, region ) ); // if the token has a $ in it, something's wrong. Ignore this token if (name.lastIndexOf('$') >= 0 && m_ignoreBadTokens) { // DEBUG System.err.println(String.format("WARNING: %s \"%s\" is probably a bad token. It was ignored", node.getNodeType(), name)); return null; } return token; } public void addReference(AstNode node, Entry deobfEntry, Entry deobfContext) { Token token = getToken(node); if (token != null) { EntryReference<Entry,Entry> deobfReference = new EntryReference<Entry,Entry>(deobfEntry, token.text, deobfContext); m_tokenToReference.put(token, deobfReference); m_referenceToTokens.put(deobfReference, token); } } public void addDeclaration(AstNode node, Entry deobfEntry) { Token token = getToken(node); if (token != null) { EntryReference<Entry,Entry> reference = new EntryReference<Entry,Entry>(deobfEntry, token.text); m_tokenToReference.put(token, reference); m_referenceToTokens.put(reference, token); m_declarationToToken.put(deobfEntry, token); } } public Token getReferenceToken(int pos) { Token token = m_tokenToReference.floorKey(new Token(pos, pos, null)); if (token != null && token.contains(pos)) { return token; } return null; } public Collection<Token> getReferenceTokens(EntryReference<Entry,Entry> deobfReference) { return m_referenceToTokens.get(deobfReference); } public EntryReference<Entry,Entry> getDeobfReference(Token token) { if (token == null) { return null; } return m_tokenToReference.get(token); } public void replaceDeobfReference(Token token, EntryReference<Entry,Entry> newDeobfReference) { EntryReference<Entry,Entry> oldDeobfReference = m_tokenToReference.get(token); m_tokenToReference.put(token, newDeobfReference); Collection<Token> tokens = m_referenceToTokens.get(oldDeobfReference); m_referenceToTokens.removeAll(oldDeobfReference); m_referenceToTokens.putAll(newDeobfReference, tokens); } public Iterable<Token> referenceTokens() { return m_tokenToReference.keySet(); } public Iterable<Token> declarationTokens() { return m_declarationToToken.values(); } public Iterable<Entry> declarations() { return m_declarationToToken.keySet(); } public Token getDeclarationToken(Entry deobfEntry) { return m_declarationToToken.get(deobfEntry); } public int getLineNumber(int pos) { // line number is 1-based int line = 0; for (Integer offset : m_lineOffsets) { if (offset > pos) { break; } line++; } return line; } public int getColumnNumber(int pos) { // column number is 1-based return pos - m_lineOffsets.get(getLineNumber(pos) - 1) + 1; } private int toPos(int line, int col) { // line and col are 1-based return m_lineOffsets.get(line - 1) + col - 1; } }
package de.sb.messenger.rest; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.ws.rs.ClientErrorException; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import de.sb.messenger.persistence.Group; import de.sb.messenger.persistence.Person; @Path("people") public class PersonService { @GET @Produces({ APPLICATION_JSON, APPLICATION_XML }) public List<Person> queryPersons(@HeaderParam("Authorization") final String authentication, @QueryParam("givenName") final String givenName, @QueryParam("familyName") final String familyName, @QueryParam("mail") final String mail, @QueryParam("street") final String street, @QueryParam("postcode") final String postcode, @QueryParam("city") final String city, @QueryParam("group") final Group group) { final EntityManager messengerManager = Persistence.createEntityManagerFactory("messenger").createEntityManager(); TypedQuery<Person> query = messengerManager.createQuery("SELECT p FROM Person p WHERE " + "(:givenName is null OR p.name.given = :givenName) AND " + "(:familyName is null or p.name.family = :familyName) AND " + "(:mail IS null OR p.email = :mail) AND " + "(:street IS null OR p.address.street = :street) AND " + "(:postcode IS null OR p.address.postcode = :postcode) AND" + "(:city IS null OR p.address.city = :city) AND" + "(:group IS null OR p.group = :group)" + " ORDER BY p.name.family, p.name.given, p.email", Person.class); List<Person> results = query .setParameter("mail", mail) .setParameter("givenName", givenName) .setParameter("familyName", familyName) .setParameter("street", street) .setParameter("postcode", postcode) .setParameter("city", city) .setParameter("group", group) .getResultList(); if (results.isEmpty()) { throw new ClientErrorException(NOT_FOUND); } return results; } }
package scala.tools.scalac.ant; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Vector; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.GlobPatternMapper; import org.apache.tools.ant.util.SourceFileScanner; import org.apache.tools.ant.types.Reference; import scala.tools.scalac.CompilerPhases$class; import scala.tools.scalac.Global$class; import scala.tools.util.ConsoleReporter; import scala.tools.util.Reporter; import scala.tools.util.Timer; import scala.tools.util.debug.AbortError; import scalac.CompilationUnit; import scalac.CompilerCommand; /** * An Ant task to compile with the old Scala compiler. * This task can take the following parameters as attributes:<ul> * <li>srcdir (mandatory),</li> * <li>srcref,</li> * <li>destdir,</li> * <li>classpath,</li> * <li>classpathref,</li> * <li>sourcepath,</li> * <li>sourcepathref,</li> * <li>bootclasspath,</li> * <li>bootclasspathref,</li> * <li>extdirs,</li> * <li>extdirsref,</li> * <li>encoding,</li> * <li>verbose,</li> * <li>debug,</li> * <li>usepredefs,</li> * <li>useimports,</li> * <li>force.</li> * </ul> * It also takes the following parameters as nested elements:<ul> * <li>src (for srcdir),</li> * <li>classpath,</li> * <li>sourcepath,</li> * <li>bootclasspath,</li> * <li>extdirs.</li> * </ul> */ public class Scalac extends MatchingTask { private FileUtils fileUtils = FileUtils.newFileUtils(); private String SCALA_PRODUCT = System.getProperty("scala.product", "Scalac Ant compiler"); private String SCALA_VERSION = System.getProperty("scala.version", "Unknown version"); // // // /** The directories that contain source files to compile. */ private Path origin = null; /** The directory to put the compiled files in. */ private File destination = null; /** The class path to use for this compilation. */ private Path classpath = null; /** The source path to use for this compilation. */ private Path sourcepath = null; /** The boot class path to use for this compilation. */ private Path bootclasspath = null; /** The external extensions path to use for this compilation. */ private Path extpath = null; /** The text encoding of the files to compile. */ private String encoding = null; /** Whether to use verbose output or not. */ private boolean verbose = false; /** Whether to print-out some additional ant compilation information. */ private boolean debug = false; /** Whether to use implicit predefined values or not. */ private boolean usepredefs = true; /** Whether to implicitly import or not. */ private boolean useimports = true; /** What type of force compilation to use, if any. */ private String force = "never"; // // // /** * A setter for the srcdir attribute. Used by Ant. * @param input The value of <code>origin</code>. */ public void setSrcdir(Path input) { if (origin == null) { origin = input; } else { origin.append(input); } } /** * A setter of the <code>origin</code> as a nested src Ant parameter. * @return An origin path to be configured. */ public Path createSrc() { if (origin == null) { origin = new Path(getProject()); } return origin.createPath(); } /** * A setter of the <code>origin</code> as an external reference Ant parameter. * @param input A reference to an origin path. */ public void setSrcref(Reference input) { createSrc().setRefid(input); } /** * A setter for the destdir attribute. Used by Ant. * @param input The value of <code>destination</code>. */ public void setDestdir(File input) { destination = input; } /** * A setter for the classpath attribute. Used by Ant. * @param input The value of <code>classpath</code>. */ public void setClasspath(Path input) { if (classpath == null) { classpath = input; } else { classpath.append(input); } } /** * A setter of the <code>classpath</code> as a nested classpath Ant parameter. * @return A class path to be configured. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } /** * A setter of the <code>classpath</code> as an external reference Ant parameter. * @param input A reference to a class path. */ public void setClasspathref(Reference input) { createClasspath().setRefid(input); } /** * A setter for the sourcepath attribute. Used by Ant. * @param input The value of <code>sourcepath</code>. */ public void setSourcepath(Path input) { if (sourcepath == null) { sourcepath = input; } else { sourcepath.append(input); } } /** * A setter of the <code>sourcepath</code> as a nested sourcepath Ant parameter. * @return A source path to be configured. */ public Path createSourcepath() { if (sourcepath == null) { sourcepath = new Path(getProject()); } return sourcepath.createPath(); } /** * A setter of the <code>sourcepath</code> as an external reference Ant parameter. * @param input A reference to a source path. */ public void setSourcepathref(Reference input) { createSourcepath().setRefid(input); } /** * A setter for the boot classpath attribute. Used by Ant. * @param input The value of <code>bootclasspath</code>. */ public void setBootclasspath(Path input) { if (bootclasspath == null) { bootclasspath = input; } else { bootclasspath.append(input); } } /** * A setter of the <code>bootclasspath</code> as a nested sourcepath Ant parameter. * @return A source path to be configured. */ public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(getProject()); } return bootclasspath.createPath(); } /** * A setter of the <code>bootclasspath</code> as an external reference Ant parameter. * @param input A reference to a source path. */ public void setBootclasspathref(Reference input) { createBootclasspath().setRefid(input); } /** * A setter for the external extensions path attribute. Used by Ant. * @param input The value of <code>extpath</code>. */ public void setExtdirs(Path input) { if (extpath == null) { extpath = input; } else { extpath.append(input); } } /** * A setter of the <code>extpath</code> as a nested sourcepath Ant parameter. * @return A source path to be configured. */ public Path createExtdirs() { if (extpath == null) { extpath = new Path(getProject()); } return extpath.createPath(); } /** * A setter of the <code>extpath</code> as an external reference Ant parameter. * @param input A reference to a source path. */ public void setExtdirsref(Reference input) { createExtdirs().setRefid(input); } /** * A setter for the encoding attribute. Used by Ant. * @param input The value of <code>encoding</code>. */ public void setEncoding(String input) { encoding = input; } /** * A setter for the verbose attribute. Used by Ant. * @param input The value for <code>verbose</code>. */ public void setVerbose(boolean input) { verbose = input; } /** * A setter for the debug attribute. Used by Ant. * @param input The value for <code>debug</code>. */ public void setDebug(boolean input) { debug = input; } /** * A setter for the use predefs attribute. Used by Ant. * @param input The value for <code>usepredefs</code>. */ public void setUsepredefs(boolean input) { usepredefs = input; } /** * A setter for the use imports attribute. Used by Ant. * @param input The value for <code>useimport</code>. */ public void setUseimports(boolean input) { useimports = input; } /** * A setter for the force attribute. Used by Ant. * @param input The value for <code>force</code>. */ public void setForce(ForceMode input) { force = input.getValue(); } // // // /** * Generates a build error. Error location will be the current task in the ant file. * @param message The message of the error. This message should be end-user readable. * @throws org.apache.tools.ant.BuildException The build error exception. Will be thrown in all conditions. */ private void error(String message) throws BuildException { throw new BuildException(message, getLocation()); } /** * Performs the compilation. */ public void execute() throws BuildException { // Tests if all mandatory attributes are set and valid. if (origin == null) error("Attribute 'srcdir' is not set."); if (origin.size() == 0) error("Attribute 'srcdir' is not set."); if (destination != null && !destination.isDirectory()) error("Attribute 'destdir' does not refer to an existing directory."); Vector sourceFilesList = new Vector(); // Scans source directories to build up a compile lists. // If force is false, only files were the .class file in destination is newer than // the .suffix file will be used. String[] originList = origin.list(); for (int i = 0; i < originList.length; i++) { File originDir = getProject().resolveFile(originList[i]); if (!originDir.exists()) { log("Element '" + originDir.getPath() + "' in attribute 'srcdir' does not refer to an existing directory.", Project.MSG_WARN); break; } DirectoryScanner originDirScanner = this.getDirectoryScanner(originDir); String[] files = originDirScanner.getIncludedFiles(); if (force.compareToIgnoreCase("always") == 0) { addFilesToSourceList(files, originDir, sourceFilesList); } else { GlobPatternMapper mapper = new GlobPatternMapper(); mapper.setTo("*.class"); mapper.setFrom("*.scala"); SourceFileScanner scanner = new SourceFileScanner(this); String[] newFiles = scanner.restrict(files, originDir, destination, mapper); if (force.compareToIgnoreCase("changed") == 0 && (newFiles.length > 0)) { addFilesToSourceList(files, originDir, sourceFilesList); } else if (force.compareToIgnoreCase("never") == 0) { addFilesToSourceList(newFiles, originDir, sourceFilesList); } } } if (sourceFilesList.isEmpty()) { log("No files selected for compilation"); } else { log("Compiling " + sourceFilesList.size() + " source file" + (sourceFilesList.size() == 1 ? "" : "s") + (destination != null ? " to " + destination.toString() : "")); } // Builds-up the compilation settings for Scalac with the existing Ant parameters. Reporter reporter = new ConsoleReporter(); CompilerCommand command = new CompilerCommand(SCALA_PRODUCT, SCALA_VERSION, reporter, new CompilerPhases$class()); if (destination != null) command.outpath.value = destination.getAbsolutePath(); if (classpath != null) command.classpath.value = makeAbsolutePath(classpath, "classpath"); if (sourcepath != null) { command.sourcepath.value = makeAbsolutePath(sourcepath, "sourcepath"); } else { command.sourcepath.value = destination.getAbsolutePath(); } // The bootclasspath needs to be treated specially. // When no bootclasspath is provided, the classpath of the current classloader is used: // This is where the scala classes should be. // Furthermore, the source files for the library must be available in the bootclasspath too. // To do that, an element ending in 'lib/scala.jar' or 'scala/classes' is looked-up in the bootclasspath. // From there, the sources should be in '../src' or '../sources' respectively. // This means any other configuration will fail at runtime. In this case, the bootclasspath should be set explicitly. // Notice also how the bootclasspath must finish with a ":" for it to work. Path baseBootclasspath; if (bootclasspath != null) { baseBootclasspath = bootclasspath; } else { baseBootclasspath = getClassLoaderClasspath(this.getClass().getClassLoader()); } command.bootclasspath.value = makeAbsolutePath(baseBootclasspath, "bootclasspath") + ":"; if (extpath != null) command.extdirs.value = makeAbsolutePath(extpath, "extpath"); if (encoding != null) command.encoding.value = encoding; command.verbose.value = verbose; command.debug.value = debug; command.noimports.value = !useimports; command.nopredefs.value = !usepredefs; Timer timer = scalac.Global.getTimer(reporter); // Compiles the actual code Global$class compiler = new Global$class(command, timer, false); String[] stringArray = new String[sourceFilesList.size()]; try { timer.start(); CompilationUnit[] classes = compiler.compile((String[])sourceFilesList.toArray(stringArray), false); if (reporter.errors() > 0) { error("Compile failed with " + reporter.errors() + " error" + (reporter.errors() == 1 ? "" : "s") + "; see the compiler error output for details."); } compiler.dump(classes); } catch (AbortError exception) { if (debug) exception.printStackTrace(); error("Compile failed because of an internal compiler error; see the error output for details."); } finally { timer.stop("Compile time"); } if (reporter.warnings() > 0) { log("Compile suceeded with " + reporter.errors() + " warning" + (reporter.warnings() == 1 ? "" : "s") + "; see the compiler output for details."); } } private void addFilesToSourceList (String[] files, File originDir, Vector sourceFilesList) { for (int i = 0; i < files.length; i++) { String sourceFile = fileUtils.resolveFile(originDir, files[i]).toString(); log(sourceFile, Project.MSG_VERBOSE); sourceFilesList.add(sourceFile); } } private String makeAbsolutePath(Path path, String pathName) { String result = ""; String[] pathList = path.list(); for (int i = 0; i < pathList.length; i++) { File pathFile = new File(pathList[i]); if (pathFile.exists()) { result = result + ((result == "") ? "" : File.pathSeparator) + pathFile.getAbsolutePath(); } else { log("Element '" + pathFile.toString() + "' in " + pathName + " does not exist.", Project.MSG_WARN); result = result + ((result == "") ? "" : File.pathSeparator) + pathFile.toString(); } } return result; } private Path getClassLoaderClasspath(ClassLoader classLoader) throws BuildException { Path classLoaderClasspath = new Path(getProject()); ClassLoader parentClassLoader = classLoader.getParent(); String classloaderName = classLoader.getClass().getName(); boolean isURLClassLoader = classloaderName.endsWith("URLClassLoader"); boolean isAntClassLoader = classloaderName.endsWith("AntClassLoader2") || classloaderName.endsWith("AntClassLoader"); if (isURLClassLoader) { URL[] urls = ((URLClassLoader) classLoader).getURLs(); for (int i = 0; i < urls.length; i++) { classLoaderClasspath.append(new Path(getProject(), urls[i].toString())); } } else if (isAntClassLoader) { String[] paths = ((AntClassLoader) classLoader).getClasspath().split(File.pathSeparator); for (int i = 0; i < paths.length; i++) { classLoaderClasspath.append(new Path(getProject(), paths[i])); } } if (parentClassLoader != null && parentClassLoader != classLoader) { classLoaderClasspath.append(getClassLoaderClasspath(parentClassLoader)); } return classLoaderClasspath; } /** * Enumerated attribute with the values "never", "always", "changed". */ public static class ForceMode extends EnumeratedAttribute { /** * @see EnumeratedAttribute#getValues */ public String[] getValues() { return new String[] {"never", "always", "changed"}; } } }
package dk.netarkivet.common.utils; import java.io.StringReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.exceptions.IllegalState; import dk.netarkivet.common.exceptions.PermissionDenied; /** * Various database related utilities. * */ public class DBUtils { /** The logger. */ private static final Log log = LogFactory.getLog(DBUtils.class); /** Execute an SQL statement and return the single integer * in the result set. * * @param s A prepared statement * @return The integer result, or null if the result value was null. * @throws IOFailure if the statement didn't result in exactly one integer. */ public static Integer selectIntValue(PreparedStatement s) { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); try { ResultSet res = s.executeQuery(); if (!res.next()) { throw new IOFailure("No results from " + s); } Integer resultInt = res.getInt(1); if (res.wasNull()) { resultInt = null; } if (res.next()) { throw new IOFailure("Too many results from " + s); } return resultInt; } catch (SQLException e) { throw new IOFailure("SQL error executing statement " + s + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL statement and return the single int in the result set. * This variant takes a query string and a single string arg and combines * them to form a normal query. * * NB: the method does not close the provided connection. * * @param connection connection to database. * @param query a query with ? for parameters (must not be null or * empty string) * @param args parameters of type string, int, long or boolean * @return The integer result * @throws IOFailure if the statement didn't result in exactly one integer */ public static Integer selectIntValue(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = null; try { s = DBUtils.prepareStatement(connection, query, args); // We do not test for 0-values here, already tested in // selectIntValue(s) return selectIntValue(s); } catch (SQLException e) { throw new IOFailure("SQL error preparing statement " + query + " args " + Arrays.toString(args) + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL statement and return the single long in the result set. * * @param s A prepared statement * @return The long result, or null if the result was a null value * Note that a null value is not the same as no result rows. * @throws IOFailure if the statement didn't result in exactly one row with * a long or null value */ public static Long selectLongValue(PreparedStatement s) { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); try { ResultSet res = s.executeQuery(); if (!res.next()) { throw new IOFailure("No results from " + s); } Long resultLong = res.getLong(1); if (res.wasNull()) { resultLong = null; } if (res.next()) { throw new IOFailure("Too many results from " + s); } return resultLong; } catch (SQLException e) { throw new IOFailure("SQL error executing statement " + s + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL statement and return the single long in the result set. * This variant takes a query string and a single string arg and combines * them to form a normal query. * * NB: the provided connection is not closed. * * @param connection connection to database. * @param query a query with ? for parameters (must not be null or * empty string) * @param args parameters of type string, int, long or boolean * @return The long result * @throws IOFailure if the statement didn't result in exactly one long * value */ public static Long selectLongValue(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = null; try { s = DBUtils.prepareStatement(connection, query, args); // We do not test for 0-values here, already tested in // selectLongValue(s) return selectLongValue(s); } catch (SQLException e) { throw new IOFailure("Error preparing SQL statement " + query + " args " + Arrays.toString(args) + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL statement and return the first long in the result set, * or null if resultset is empty. * * NB: the provided connection is not closed. * * @param connection connection to database. * @param query a query with ? for parameters (must not be null * or empty string) * @param args parameters of type string, int, long or boolean * @return The long result, or will return null in one of the two following * cases: There is no results, or the first result is a null-value. * @throws IOFailure on SQL errors. */ public static Long selectFirstLongValueIfAny(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = null; try { s = DBUtils.prepareStatement(connection, query, args); ResultSet rs = s.executeQuery(); if (rs.next()) { return DBUtils.getLongMaybeNull(rs, 1); } else { return null; } } catch (SQLException e) { String message = "SQL error executing '" + query + "'" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } } /** * Prepare a statement given a query string and some args. * * NB: the provided connection si not closed. * * @param c a Database connection * @param query a query string (must not be null or empty) * @param args some args to insert into this query string (must not be null) * @return a prepared statement * @throws SQLException If unable to prepare a statement * @throws ArgumentNotValid If unable to handle type of one the args, or * the arguments are either null or an empty String. */ public static PreparedStatement prepareStatement(Connection c, String query, Object... args) throws SQLException { ArgumentNotValid.checkNotNull(c, "Connection c"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = c.prepareStatement(query); int i = 1; for (Object arg : args) { if (arg instanceof String) { s.setString(i, (String) arg); } else if (arg instanceof Integer) { s.setInt(i, (Integer) arg); } else if (arg instanceof Long) { s.setLong(i, (Long) arg); } else if (arg instanceof Boolean) { s.setBoolean(i, (Boolean) arg); } else if (arg instanceof Date) { s.setTimestamp(i, new Timestamp(((Date) arg).getTime())); } else { throw new ArgumentNotValid("Cannot handle type '" + arg.getClass().getName() + "'. We can only handle string, " + "int, long, date or boolean args for query: " + query); } i++; } return s; } /** Execute an SQL statement and return the list of strings * in its result set. This uses specifically the harvester database. * * NB: the provided connection is not closed. * * @param connection connection to the database. * @param query the given sql-query (must not be null or empty) * @param args The arguments to insert into this query (must not be null) * @throws IOFailure If this query fails * @return the list of strings in its result set */ public static List<String> selectStringList(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = null; try { s = prepareStatement(connection, query, args); ResultSet result = s.executeQuery(); List<String> results = new ArrayList<String>(); while (result.next()) { if (result.getString(1) == null){ String warning = "NULL pointer found in resultSet from query: " + query; log.warn(warning); throw new IOFailure(warning); } results.add(result.getString(1)); } return results; } catch (SQLException e) { throw new IOFailure("Error preparing SQL statement " + query + " args " + Arrays.toString(args) + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL statement and return the list of strings -> id mappings * in its result set. * * NB: the provided connection si not closed. * * @param connection connection to the database. * @param query the given sql-query (must not be null or empty string) * @param args The arguments to insert into this query * @throws SQLException If this query fails * @return the list of strings -> id mappings */ public static Map<String, Long> selectStringLongMap(Connection connection, String query, Object... args) throws SQLException { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = prepareStatement(connection, query, args); ResultSet result = s.executeQuery(); Map<String, Long> results = new HashMap<String, Long>(); while (result.next()) { String resultString = result.getString(1); long resultLong = result.getLong(2); if ((resultString == null) || (resultLong == 0L && result.wasNull())) { String warning = "NULL pointers found in entry (" + resultString + "," + resultLong + ") in resultset from query: " + query; log.warn(warning); //throw new IOFailure(warning); } results.put(resultString, resultLong); } return results; } /** * Execute an SQL statement and return the list of Long-objects * in its result set. * * NB: the provided connection is not closed. * * @param connection connection to the database. * @param query the given sql-query (must not be null or empty string) * @param args The arguments to insert into this query * @return the list of Long-objects in its result set */ public static List<Long> selectLongList(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = null; try { s = prepareStatement(connection, query, args); ResultSet result = s.executeQuery(); List<Long> results = new ArrayList<Long>(); while (result.next()) { if (result.getLong(1) == 0L && result.wasNull()){ String warning = "NULL value encountered in query: " + query; log.warn(warning); //throw new IOFailure(warning); } results.add(result.getLong(1)); } return results; } catch (SQLException e) { throw new IOFailure("Error preparing SQL statement " + query + " args " + Arrays.toString(args) + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Get the automatically generated key that was created with the * just-executed statement. * * @param s A statement created with Statement.RETURN_GENERATED_KEYS * @return The single generated key * @throws SQLException If a database access error occurs or * the PreparedStatement is closed, or the JDBC driver does not support * the setGeneratedKeys() method */ public static long getGeneratedID(PreparedStatement s) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); ResultSet res = s.getGeneratedKeys(); if (!res.next()) { throw new IOFailure("No keys generated by " + s); } return res.getLong(1); } /** Returns the version of a table according to schemaversions, or 0 * for the initial, unnumbered version. * * NB: the provided connection is not closed * * @param connection connection to the database. * @param tablename The name of a table in the database. * @return Version of the given table. * @throws IOFailure if DB table schemaversions does not exist */ public static int getTableVersion(Connection connection, String tablename) throws IOFailure { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(tablename, "String tablenname"); PreparedStatement s = null; int version = 0; try { s = connection.prepareStatement("SELECT version FROM schemaversions" + " WHERE tablename = ?"); s.setString(1, tablename); ResultSet res = s.executeQuery(); if (!res.next()) { log.warn("As yet unknown tablename '" + tablename + "' in table schemaversions. The table probably" + " just needs to be created in the database"); } else { version = res.getInt(1); if (res.wasNull()) { log.warn("Null table version for '" + tablename + "'"); } } return version; } catch (SQLException e) { String msg = "SQL Error checking version of table " + tablename + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(msg, e); throw new IOFailure(msg, e); } } /** * Set String Max Length. * If contents.length() > maxSize, contents is truncated to contain * the first maxSize characters of the contents, and a warning is logged. * @param s a Prepared Statement * @param fieldNum a index into the above statement * @param contents the contents * @param maxSize the maximum size of field: fieldName * @param o the Object, which assumedly have a field named fieldName * @param fieldname the name of a given field * @throws SQLException if set operation fails */ public static void setStringMaxLength(PreparedStatement s, int fieldNum, String contents, int maxSize, Object o, String fieldname) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); ArgumentNotValid.checkNotNegative(fieldNum, "int fieldNum"); if (contents != null) { if (contents.length() > maxSize) { log.warn(fieldname + " of " + o + " is longer than the allowed " + maxSize + " characters. The contents is truncated to length " + maxSize + ". The untruncated contents was: " + contents); // truncate to length maxSize contents = contents.substring(0, maxSize); } s.setString(fieldNum, contents); } else { s.setNull(fieldNum, Types.VARCHAR); } } public static void setComments(PreparedStatement s, int fieldNum, Named o, int maxFieldSize) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); ArgumentNotValid.checkNotNegative(fieldNum, "int fieldNum"); ArgumentNotValid.checkNotNull(o, "Named o"); ArgumentNotValid.checkNotNegative(maxFieldSize, "int maxFieldSize"); if (o.getComments().length() > maxFieldSize) { throw new PermissionDenied("Length of comments (" + o.getComments().length() + ") is larger than allowed. Max length is " + maxFieldSize); } setStringMaxLength(s, fieldNum, o.getComments(), maxFieldSize, o, "comments"); } public static void setName(PreparedStatement s, int fieldNum, Named o, int maxFieldSize) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); ArgumentNotValid.checkNotNegative(fieldNum, "int fieldNum"); ArgumentNotValid.checkNotNull(o, "Named o"); ArgumentNotValid.checkNotNegative(maxFieldSize, "int maxFieldSize"); if (o.getName().length() > maxFieldSize) { throw new PermissionDenied("Length of name (" + o.getName().length() + ") is larger than allowed. Max length is " + maxFieldSize); } setStringMaxLength(s, fieldNum, o.getName(), maxFieldSize, o, "name"); } /** Set the Date into the given field of a statement. * * @param s a prepared statement * @param fieldNum the index of the given field to be set * @param date the date (may be null) * @throws SQLException If any trouble accessing the database during * the operation */ public static void setDateMaybeNull( PreparedStatement s, int fieldNum, Date date) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); ArgumentNotValid.checkNotNegative(fieldNum, "int fieldNum"); if (date != null) { s.setTimestamp(fieldNum, new Timestamp(date.getTime())); } else { s.setNull(fieldNum, Types.DATE); } } /** * Get a Date from a column in the resultset. * Returns null, if the value in the column is NULL. * @param rs the resultSet * @param columnIndex The given column, where the Date resides * @return a Date from a column in the resultset * @throws SQLException If columnIndex does not correspond to a * parameter marker in the ResultSet, or a database access error * occurs or this method is called on a closed ResultSet */ public static Date getDateMaybeNull(ResultSet rs, final int columnIndex) throws SQLException { ArgumentNotValid.checkNotNull(rs, "ResultSet rs"); ArgumentNotValid.checkNotNegative(columnIndex, "int columnIndex"); final Timestamp startTimestamp = rs.getTimestamp(columnIndex); if (rs.wasNull()) { return null; } Date startdate; if (startTimestamp != null) { startdate = new Date(startTimestamp.getTime()); } else { startdate = null; } return startdate; } /** * Method to perform a rollback of complex DB updates. If no commit has * been performed, this will undo the entire transaction, otherwise * nothing will happen. This should be called in a finally block with * no DB updates after the last commit. * Thus exceptions while closing are ignored, but logged as warnings. * * NB: the provided connection si not closed. * * @param c the db-connection * @param action The action going on, before calling this method * @param o The Object being acted upon by this action */ public static void rollbackIfNeeded(Connection c, String action, Object o) { ArgumentNotValid.checkNotNull(c, "Connection c"); try { c.rollback(); c.setAutoCommit(true); } catch (SQLException e) { log.warn("SQL error doing rollback after " + action + " " + o + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); // Can't throw here, we want the real exception } } /** * Set the CLOB maxlength. * If contents.length() > maxSize, contents is truncated to contain * the first maxSize characters of the contents, and a warning is logged. * @param s a prepared statement * @param fieldNum the field-index, where the contents are inserted * @param contents the contents * @param maxSize the maxsize for this contents * @param o the Object, which assumedly have a field named fieldName * @param fieldName a given field (Assumedly in Object o) * @throws SQLException If fieldNum does not correspond to a * parameter marker in the PreparedStatement, or a database access error * occurs or this method is called on a closed PreparedStatement */ public static void setClobMaxLength(PreparedStatement s, int fieldNum, String contents, long maxSize, Object o, String fieldName) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); if (contents != null) { if (contents.length() > maxSize) { log.warn( fieldName + " of " + o + " is longer than the allowed " + maxSize + " characters. The contents is now truncated to " + "length " + maxSize + ". The untruncated contents was: " + contents); // truncate to length maxSize (if maxSize <= Integer.MAX_VALUE) // else truncate to length Integer.MAX_VALUE if (maxSize > Integer.MAX_VALUE) { maxSize = Integer.MAX_VALUE; } contents = contents.substring(0, (int) maxSize); } s.setCharacterStream(fieldNum, new StringReader(contents), contents .length()); s.setString(fieldNum, contents); } else { s.setNull(fieldNum, Types.CLOB); } } /** * Insert a long value (which could be null) into * the given field of a statement. * @param s a prepared Statement * @param i the number of a given field in the prepared statement * @param value the long value to insert (maybe null) * @throws SQLException If i does not correspond to a * parameter marker in the PreparedStatement, or a database access error * occurs or this method is called on a closed PreparedStatement */ public static void setLongMaybeNull(PreparedStatement s, int i, Long value) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); if (value != null) { s.setLong(i, value); } else { s.setNull(i, Types.BIGINT); } } /** * Insert an Integer in prepared statement. * @param s a prepared statement * @param i the index of the statement, where the Integer should be inserted * @param value The Integer to insert (maybe null) * @throws SQLException If i does not correspond to a * parameter marker in the PreparedStatement, or a database access error * occurs or this method is called on a closed PreparedStatement */ public static void setIntegerMaybeNull(PreparedStatement s, int i, Integer value) throws SQLException { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); if (value != null) { s.setInt(i, value); } else { s.setNull(i, Types.INTEGER); } } /** * Get an Integer from the resultSet in column i. * @param rs the resultset * @param i the column where the wanted Integer resides * @return an Integer object located in column i in the resultset * @throws SQLException If the columnIndex is not valid, or a database * access error occurs or this method is called on a closed result set */ public static Integer getIntegerMaybeNull(ResultSet rs, int i) throws SQLException { ArgumentNotValid.checkNotNull(rs, "ResultSet rs"); Integer res = rs.getInt(i); if (rs.wasNull()) { return null; } return res; } /** * Get a Long from the resultSet in column i. * @param rs the resultset * @param i the column where the wanted Long resides * @return a Long object located in column i in the resultset * @throws SQLException If the columnIndex is not valid, or a database * access error occurs or this method is called on a closed result set */ public static Long getLongMaybeNull(ResultSet rs, int i) throws SQLException { ArgumentNotValid.checkNotNull(rs, "ResultSet rs"); Long res = rs.getLong(i); if (rs.wasNull()) { return null; } return res; } /** Return a description of where an object is used elsewhere in the * database, or null. * * NB: the provided connection is not closed. * * @param connection connection to the database. * @param select A select statement finding the names of other uses. The * statement should result in exactly one column of string values. * @param victim The object being used. * @param args Any objects that may be used to prepare the select statement. * @return A string describing the usages, or null if no usages were found. */ public static String getUsages( Connection connection, String select, Object victim, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); PreparedStatement s = null; try { s = prepareStatement(connection, select, args); ResultSet res = s.executeQuery(); if (res.next()) { List<String> usedIn = new ArrayList<String>(); do { usedIn.add(res.getString(1)); } while (res.next()); return usedIn.toString(); } return null; } catch (SQLException e) { final String message = "SQL error checking for usages of " + victim + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } } public static void checkTableVersion(Connection connection, String tablename, int desiredVersion) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(tablename, "String tablename"); ArgumentNotValid.checkPositive(desiredVersion, "int desiredVersion"); int actualVersion = getTableVersion(connection, tablename); if (actualVersion != desiredVersion) { String message = "Wrong table version for '" + tablename + "': Should be " + desiredVersion + ", but is " + actualVersion; log.warn(message); throw new IllegalState(message); } } /** Execute an SQL statement and return the single string in the result set. * This variant takes a query string and a single string arg and combines * them to form a normal query. * * This assumes the connection is to the harvester database. * * @param connection connection to the database. * @param query a query with ? for parameters (must not be null or * an empty string) * @param args parameters of type string, int, long or boolean * @return The string result * @throws IOFailure if the statement didn't result in exactly one string * value */ public static String selectStringValue(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); ArgumentNotValid.checkNotNull(connection, "Connection connection"); PreparedStatement s = null; try { s = prepareStatement(connection, query, args); // We do not test for null-values here, already tested in // selectStringValue(s) return DBUtils.selectStringValue(s); } catch (SQLException e) { throw new IOFailure("Error preparing SQL statement " + query + " args " + Arrays.toString(args) + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL statement and return the single string in the result set. * * @param s A prepared statement * @return The string result, or null if the result was a null value * Note that a null value is not the same as no result rows. * @throws IOFailure if the statement didn't result in exactly one row with * a string or null value */ public static String selectStringValue(PreparedStatement s) { ArgumentNotValid.checkNotNull(s, "PreparedStatement s"); try { ResultSet res = s.executeQuery(); if (!res.next()) { throw new IOFailure("No results from " + s); } String resultString = res.getString(1); if (res.wasNull()) { resultString = null; } if (res.next()) { throw new IOFailure("Too many results from " + s); } return resultString; } catch (SQLException e) { throw new IOFailure("SQL error executing statement " + s + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Execute an SQL query and return whether the result contains any rows. * * NB: the provided connection is not closed. * * @param connection connection to the database. * @param query a query with ? for parameters (must not be null or * an empty String) * @param args parameters of type string, int, long or boolean * @return True if executing the query resulted in at least one row. * @throws IOFailure if there were problems with the SQL query */ public static boolean selectAny(Connection connection, String query, Object... args) { ArgumentNotValid.checkNotNull(connection, "Connection connection"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); PreparedStatement s = null; try { s = prepareStatement(connection, query, args); return s.executeQuery().next(); } catch (SQLException e) { throw new IOFailure("Error preparing SQL statement " + query + " args " + Arrays.toString(args) + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } /** Translate a "normal" glob (with * and .) into SQL syntax. * * @param glob A shell-like glob string (must not be null) * @return A string that implements glob in SQL "LIKE" constructs. */ public static String makeSQLGlob(String glob) { ArgumentNotValid.checkNotNull(glob, "String glob"); return glob.replace("*", "%").replace("?", "_"); } /** Update a database by executing all the statements in * the updates String array. * NOTE: this must NOT be used for tables under version control * It must only be used in connection with temporary tables e.g. used * for backup. * * NB: the method does not close the provided connection. * * @param connection connection to the database. * @param updates The SQL statements that makes the necessary * updates. * @throws IOFailure in case of problems in interacting with the database */ public static void executeSQL(Connection connection, final String... updates) { ArgumentNotValid.checkNotNull(updates, "String... updates"); PreparedStatement st = null; String s = ""; try { connection.setAutoCommit(false); for (String update : updates) { s = update; log.debug("Executing SQL-statement: " + update); st = prepareStatement(connection, update); st.executeUpdate(); st.close(); } connection.setAutoCommit(true); log.debug("Updated database using updates '" + StringUtils.conjoin(";", updates) + "'."); } catch (SQLException e) { String msg = "SQL error updating database with sql: " + s + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(msg, e); throw new IOFailure(msg, e); } finally { rollbackIfNeeded(connection, "updating table with SQL: ", StringUtils.conjoin(";", updates) + "'."); } } /** * Close a statement, if not closed already * Note: This does not throw any a SQLException, because * it is always called inside a finally-clause. * Exceptions are logged as warnings, though. * @param s a statement */ public static void closeStatementIfOpen(PreparedStatement s) { if (s != null) { try { s.close(); } catch (SQLException e) { log.warn("Error closing SQL statement " + s + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } } } }
package dr.app.beauti.options; import dr.app.beauti.enumTypes.OperatorType; import dr.app.beauti.enumTypes.PriorScaleType; import dr.app.beauti.enumTypes.PriorType; import dr.evolution.util.TaxonList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Alexei Drummond * @author Andrew Rambaut */ public class ModelOptions { protected static final Map<String, Parameter> parameters = new HashMap<String, Parameter>(); protected static final Map<String, Operator> operators = new HashMap<String, Operator>(); protected static final Map<TaxonList, Parameter> statistics = new HashMap<TaxonList, Parameter>(); public static final double demoTuning = 0.75; public static final double demoWeights = 3.0; protected static final double branchWeights = 30.0; protected static final double treeWeights = 15.0; protected static final double rateWeights = 3.0; private final List<ComponentOptions> components = new ArrayList<ComponentOptions>(); //+++++++++++++++++++ Create Parameter ++++++++++++++++++++++++++++++++ public void createParameter(String name, String description) { new Parameter.Builder(name, description).build(parameters); } public void createParameter(String name, String description, double initial) { new Parameter.Builder(name, description).initial(initial).build(parameters); } public void createParameterUniformPrior(String name, String description, PriorScaleType scaleType, double initial, double lower, double upper) { new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.UNIFORM_PRIOR) .initial(initial).lower(lower).upper(upper).build(parameters); } public void createParameterGammaPrior(String name, String description, PriorScaleType scaleType, double initial, double shape, double scale, double lower, double upper, boolean priorFixed) { new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.GAMMA_PRIOR) .initial(initial).shape(shape).scale(scale).lower(lower).upper(upper).priorFixed(priorFixed).build(parameters); } public void createParameterJeffreysPrior(String name, String description, PriorScaleType scaleType, double initial, double lower, double upper) { new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.JEFFREYS_PRIOR) .initial(initial).lower(lower).upper(upper).build(parameters); } //+++++++++++++++++++ Create Statistic ++++++++++++++++++++++++++++++++ protected void createDiscreteStatistic(String name, String description) { new Parameter.Builder(name, description).isDiscrete(true).isStatistic(true) .prior(PriorType.POISSON_PRIOR).mean(Math.log(2)).build(parameters); } protected void createStatistic(String name, String description, double lower, double upper) { new Parameter.Builder(name, description).isStatistic(true).prior(PriorType.UNIFORM_PRIOR) .lower(lower).upper(upper).build(parameters); } //+++++++++++++++++++ Create Operator ++++++++++++++++++++++++++++++++ public void createOperator(String parameterName, OperatorType type, double tuning, double weight) { Parameter parameter = getParameter(parameterName); new Operator.Builder(parameterName, parameterName, parameter, type, tuning, weight).build(operators); } public void createScaleOperator(String parameterName, double tuning, double weight) { Parameter parameter = getParameter(parameterName); new Operator.Builder(parameterName, parameterName, parameter, OperatorType.SCALE, tuning, weight).build(operators); } // public void createScaleAllOperator(String parameterName, double tuning, double weight) { // tuning = 0.75 // Parameter parameter = getParameter(parameterName); // new Operator.Builder(parameterName, parameterName, parameter, OperatorType.SCALE_ALL, tuning, weight).build(operators); public void createOperator(String key, String name, String description, String parameterName, OperatorType type, double tuning, double weight) { Parameter parameter = getParameter(parameterName); operators.put(key, new Operator.Builder(name, description, parameter, type, tuning, weight).build()); // key != name } public void createOperatorUsing2Parameters(String key, String name, String description, String parameterName1, String parameterName2, OperatorType type, double tuning, double weight) { Parameter parameter1 = getParameter(parameterName1); Parameter parameter2 = getParameter(parameterName2); operators.put(key, new Operator.Builder(name, description, parameter1, type, tuning, weight).parameter2(parameter2).build()); } public void createUpDownOperator(String key, String name, String description, Parameter parameter1, Parameter parameter2, boolean isPara1Up, double tuning, double weight) { if (isPara1Up) { operators.put(key, new Operator.Builder(name, description, parameter1, OperatorType.UP_DOWN, tuning, weight) .parameter2(parameter2).build()); } else { operators.put(key, new Operator.Builder(name, description, parameter2, OperatorType.UP_DOWN, tuning, weight) .parameter2(parameter1).build()); } } public void createTagOperator(String key, String name, String description, String parameterName, OperatorType type, String tag, String idref, double tuning, double weight) { Parameter parameter = getParameter(parameterName); operators.put(key, new Operator.Builder(name, description, parameter, type, tuning, weight) .tag(tag).idref(idref).build()); } public void createUpDownAllOperator(String paraName, String opName, String description, double tuning, double weight) { final Parameter parameter = new Parameter.Builder(paraName, description).build(); operators.put(paraName, new Operator.Builder(opName, description, parameter, OperatorType.UP_DOWN_ALL_RATES_HEIGHTS, tuning, weight).build()); }//TODO a switch like createUpDownOperator? //+++++++++++++++++++ Methods ++++++++++++++++++++++++++++++++ public Parameter getParameter(String name) { Parameter parameter = parameters.get(name); if (parameter == null) { for (String key : parameters.keySet()) { System.err.println(key); } throw new IllegalArgumentException("Parameter with name, " + name + ", is unknown"); } return parameter; } public Parameter getStatistic(TaxonList taxonList) { Parameter parameter = statistics.get(taxonList); if (parameter == null) { for (TaxonList key : statistics.keySet()) { System.err.println("Taxon list: " + key.getId()); } throw new IllegalArgumentException("Statistic for taxon list, " + taxonList.getId() + ", is unknown"); } return parameter; } public Operator getOperator(String name) { Operator operator = operators.get(name); if (operator == null) throw new IllegalArgumentException("Operator with name, " + name + ", is unknown"); return operator; } // abstract public String getPrefix(); protected void addComponent(ComponentOptions component) { components.add(component); component.createParameters(this); } public ComponentOptions getComponentOptions(Class<?> theClass) { for (ComponentOptions component : components) { if (theClass.isAssignableFrom(component.getClass())) { return component; } } return null; } protected void selectComponentParameters(ModelOptions options, List<Parameter> params) { for (ComponentOptions component : components) { component.selectParameters(options, params); } } protected void selectComponentStatistics(ModelOptions options, List<Parameter> stats) { for (ComponentOptions component : components) { component.selectStatistics(options, stats); } } protected void selectComponentOperators(ModelOptions options, List<Operator> ops) { for (ComponentOptions component : components) { component.selectOperators(options, ops); } } public Map<String, Parameter> getParameters() { return parameters; } public Map<TaxonList, Parameter> getStatistics() { return statistics; } public Map<String, Operator> getOperators() { return operators; } public String noDuplicatedPrefix(String a , String b) { if (a.equals(b)) { return a; } else { return a + b; } } }
package dr.evomodel.tree; import dr.evolution.io.Importer; import dr.evolution.io.NewickImporter; import dr.evolution.tree.CladeSet; import dr.evolution.tree.FlexibleTree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.util.FrequencySet; import dr.util.NumberFormatter; import jebl.evolution.treemetrics.RobinsonsFouldMetric; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Set; /** * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: TreeTraceAnalysis.java,v 1.20 2005/06/07 16:28:18 alexei Exp $ */ public class TreeTraceAnalysis { public TreeTraceAnalysis(TreeTrace[] traces, int burnIn, boolean verbose) { this.traces = traces; int minMaxState = Integer.MAX_VALUE; for (TreeTrace trace : traces) { if (trace.getMaximumState() < minMaxState) { minMaxState = trace.getMaximumState(); } } if (burnIn < 0 || burnIn >= minMaxState) { this.burnin = minMaxState / (10 * traces[0].getStepSize()); if (verbose) System.out.println("WARNING: Burn-in larger than total number of states - using 10% of smallest trace"); } else { this.burnin = burnIn; } analyze(verbose); } public static double[] getSymmetricTreeDistanceTrace(TreeTrace treeTrace, Tree targetTree) { double[] symDistance = new double[treeTrace.getTreeCount(0)]; RobinsonsFouldMetric metric = new RobinsonsFouldMetric(); jebl.evolution.trees.RootedTree jreference = Tree.Utils.asJeblTree(targetTree); for (int i = 0; i < symDistance.length; i++) { jebl.evolution.trees.RootedTree tree = Tree.Utils.asJeblTree(treeTrace.getTree(i, 0)); symDistance[i] = metric.getMetric(jreference, tree); } return symDistance; } /** * Actually analyzes the trace given the burnin * * @param verbose if true then progress is logged to stdout */ public void analyze(boolean verbose) { if (verbose) { if (traces.length > 1) System.out.println("Combining " + traces.length + " traces."); } Tree tree = getTree(0); double[][] changed = new double[tree.getNodeCount()][tree.getNodeCount()]; double[] rateConditionalOnChange = new double[tree.getNodeCount()]; cladeSet = new CladeSet(tree); treeSet = new FrequencySet(); treeSet.add(Tree.Utils.uniqueNewick(tree, tree.getRoot())); for (TreeTrace trace : traces) { int treeCount = trace.getTreeCount(burnin * trace.getStepSize()); double stepSize = treeCount / 60.0; int counter = 1; if (verbose) { System.out.println("Analyzing " + treeCount + " trees..."); System.out.println("0 25 50 75 100"); System.out.println("| System.out.print("*"); } for (int i = 1; i < treeCount; i++) { tree = trace.getTree(i, burnin * trace.getStepSize()); for (int j = 0; j < tree.getNodeCount(); j++) { if (tree.getNode(j) != tree.getRoot()) { final Object o = tree.getNodeAttribute(tree.getNode(j), "changed"); if( o != null ) { if ((Integer) o == 1) { rateConditionalOnChange[j] += (Double) tree.getNodeAttribute(tree.getNode(j), "rate"); } for (int k = 0; k < tree.getNodeCount(); k++) { if (tree.getNode(k) != tree.getRoot()) { changed[j][k] += (Integer) o * (Integer) tree.getNodeAttribute(tree.getNode(k), "changed"); } } } } } cladeSet.add(tree); treeSet.add(Tree.Utils.uniqueNewick(tree, tree.getRoot())); if (i >= (int) Math.round(counter * stepSize) && counter <= 60) { if (verbose) { System.out.print("*"); System.out.flush(); } counter += 1; } } if (verbose) { System.out.println("*"); } } for (int j = 0; j < tree.getNodeCount(); j++) { System.out.println(j + "\t" + rateConditionalOnChange[j]); } System.out.println(); for (int j = 0; j < tree.getNodeCount(); j++) { for (int k = 0; k < tree.getNodeCount(); k++) { System.out.print(changed[j][k] + "\t"); } System.out.println(); } } /** * Actually analyzes a particular tree using the trace given the burnin * * @param target a tree in uniqueNewick format * @return a tree with mean node heights */ public final Tree analyzeTree(String target) { int n = getTreeCount(); FlexibleTree meanTree = null; for (int i = 0; i < n; i++) { Tree tree = getTree(i); if (Tree.Utils.uniqueNewick(tree, tree.getRoot()).equals(target)) { meanTree = new FlexibleTree(tree); break; } } if (meanTree == null) throw new RuntimeException("No target tree in trace"); int m = meanTree.getInternalNodeCount(); for (int j = 0; j < m; j++) { double[] heights = new double[n]; NodeRef node1 = meanTree.getInternalNode(j); Set<String> leafSet = Tree.Utils.getDescendantLeaves(meanTree, node1); for (int i = 0; i < n; i++) { Tree tree = getTree(i); NodeRef node2 = Tree.Utils.getCommonAncestorNode(tree, leafSet); heights[i] = tree.getNodeHeight(node2); } meanTree.setNodeHeight(node1, dr.stats.DiscreteStatistics.mean(heights)); meanTree.setNodeAttribute(node1, "upper", dr.stats.DiscreteStatistics.quantile(0.975, heights)); meanTree.setNodeAttribute(node1, "lower", dr.stats.DiscreteStatistics.quantile(0.025, heights)); } return meanTree; } public final int getTreeCount() { int treeCount = 0; for (TreeTrace trace : traces) { treeCount += trace.getTreeCount(burnin * trace.getStepSize()); } return treeCount; } public final Tree getTree(int index) { int oldTreeCount = 0; int newTreeCount = 0; for (TreeTrace trace : traces) { newTreeCount += trace.getTreeCount(burnin * trace.getStepSize()); if (index < newTreeCount) { return trace.getTree(index - oldTreeCount, burnin * trace.getStepSize()); } oldTreeCount = newTreeCount; } throw new RuntimeException("Couldn't find tree " + index); } public void report() throws IOException { report(0.5, 0.95); } public void report(double minCladeProbability) throws IOException { report(minCladeProbability, 0.95); } /** * @param minCladeProbability clades with at least this posterior probability will be included in report. * @throws IOException if general I/O error occurs */ public void report(double minCladeProbability, double credSetProbability) throws IOException { int fieldWidth = 14; NumberFormatter formatter = new NumberFormatter(6); formatter.setPadding(true); formatter.setFieldWidth(fieldWidth); int n = treeSet.size(); int totalTrees = treeSet.getSumFrequency(); System.out.println(); System.out.println("burnIn=" + burnin); System.out.println("total trees used =" + totalTrees); System.out.println(); System.out.println((Math.round(credSetProbability * 100.0)) + "% credible set (" + n + " unique trees, " + totalTrees + " total):"); System.out.println("Count\tPercent\tTree"); int credSet = (int) (credSetProbability * totalTrees); int sumFreq = 0; NumberFormatter nf = new NumberFormatter(8); for (int i = 0; i < n; i++) { int freq = treeSet.getFrequency(i); double prop = ((double) freq) / totalTrees; System.out.print(freq); System.out.print("\t" + nf.formatDecimal(prop * 100.0, 2) + "%"); sumFreq += freq; double sumProp = ((double) sumFreq) / totalTrees; System.out.print("\t" + nf.formatDecimal(sumProp * 100.0, 2) + "%"); String newickTree = (String) treeSet.get(i); if (freq > 100) { // calculate conditional average node heights Tree meanTree = analyzeTree(newickTree); System.out.println("\t" + Tree.Utils.newick(meanTree)); } else { System.out.println("\t" + newickTree); } if (sumFreq >= credSet) { System.out.println(); System.out.println("95% credible set has " + (i + 1) + " trees."); break; } } System.out.println(); System.out.println(Math.round(minCladeProbability * 100.0) + "%-rule clades (" + cladeSet.size() + " unique clades):"); n = cladeSet.size(); for (int i = 0; i < n; i++) { int freq = cladeSet.getFrequency(i); double prop = ((double) freq) / totalTrees; if (prop >= minCladeProbability) { System.out.print(freq); System.out.print("\t" + nf.formatDecimal(prop * 100.0, 2) + "%"); System.out.print("\t" + cladeSet.getMeanNodeHeight(i)); System.out.println("\t" + cladeSet.getClade(i)); } } System.out.flush(); System.out.println("Clade credible sets:"); int fiveCredSet = (5 * totalTrees) / 100; int halfCredSet = (50 * totalTrees) / 100; sumFreq = 0; n = treeSet.size(); CladeSet tempCladeSet = new CladeSet(); for (int i = 0; i < n; i++) { sumFreq += treeSet.getFrequency(i); String newickTree = (String) treeSet.get(i); NewickImporter importer = new NewickImporter(new StringReader(newickTree)); try { Tree tree = importer.importNextTree(); tempCladeSet.add(tree); } catch (Importer.ImportException e) { System.err.println("Err"); } if (sumFreq >= fiveCredSet) { System.out.println(); System.out.println("5% credible set has " + tempCladeSet.getCladeCount() + " clades."); // don't do it more than once fiveCredSet = totalTrees + 1; } if (sumFreq >= halfCredSet) { System.out.println(); System.out.println("50% credible set has " + tempCladeSet.getCladeCount() + " clades."); // don't do it more than once halfCredSet = totalTrees + 1; } } System.out.flush(); } public void shortReport(String name, Tree tree, boolean drawHeader) throws IOException { String targetTree = ""; if (tree != null) targetTree = Tree.Utils.uniqueNewick(tree, tree.getRoot()); int n = treeSet.size(); int totalTrees = treeSet.getSumFrequency(); double highestProp = ((double) treeSet.getFrequency(0)) / totalTrees; String mapTree = (String) treeSet.get(0); if (drawHeader) { System.out.println("file\ttrees\tuniqueTrees\tp(MAP)\tMAP tree\t95credSize\ttrue_I\tp(true)\tcum(true)"); } System.out.print(name + "\t"); System.out.print(totalTrees + "\t"); System.out.print(n + "\t"); System.out.print(highestProp + "\t"); System.out.print(mapTree + "\t"); int credSet = (95 * totalTrees) / 100; int sumFreq = 0; int credSetSize = -1; int targetTreeIndex = -1; double targetTreeProb = 0.0; double targetTreeCum = 1.0; for (int i = 0; i < n; i++) { int freq = treeSet.getFrequency(i); double prop = ((double) freq) / totalTrees; sumFreq += freq; double sumProp = ((double) sumFreq) / totalTrees; String newickTree = (String) treeSet.get(i); if (newickTree.equals(targetTree)) { targetTreeIndex = i + 1; targetTreeProb = prop; targetTreeCum = sumProp; } if (sumFreq >= credSet) { if (credSetSize == -1) credSetSize = i + 1; } } System.out.print(credSetSize + "\t"); System.out.print(targetTreeIndex + "\t"); System.out.print(targetTreeProb + "\t"); System.out.println(targetTreeCum); } public int getBurnin() { return burnin; } /** * @param reader the readers to be analyzed * @param burnin the burnin in states * @param verbose true if progress should be logged to stdout * @return an analyses of the trees in a log file. * @throws java.io.IOException if general I/O error occurs */ public static TreeTraceAnalysis analyzeLogFile(Reader[] reader, int burnin, boolean verbose) throws IOException { TreeTrace[] trace = new TreeTrace[reader.length]; for (int i = 0; i < reader.length; i++) { try { trace[i] = TreeTrace.loadTreeTrace(reader[i]); } catch (Importer.ImportException ie) { throw new RuntimeException(ie.toString()); } reader[i].close(); } return new TreeTraceAnalysis(trace, burnin, verbose); } private int burnin = -1; private TreeTrace[] traces; private CladeSet cladeSet; private FrequencySet treeSet; }
package edu.iu.grid.oim.servlet; import edu.iu.grid.oim.lib.StaticConfig; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.DataOutputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import org.json.*; import javax.servlet.http.HttpSession; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import net.minidev.json.JSONArray; import net.minidev.json.JSONStyle; import net.minidev.json.parser.ParseException; import java.io.UnsupportedEncodingException; import java.util.*; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.divrep.DivRep; import com.divrep.DivRepEvent; import edu.iu.grid.oim.lib.Authorization; import edu.iu.grid.oim.model.UserContext; import edu.iu.grid.oim.model.db.ContactModel; import edu.iu.grid.oim.model.db.record.ContactRecord; import edu.iu.grid.oim.view.BootMenuView; import edu.iu.grid.oim.view.BootPage; import edu.iu.grid.oim.view.ContactAssociationView; import edu.iu.grid.oim.view.GenericView; import edu.iu.grid.oim.view.HtmlView; import edu.iu.grid.oim.view.IView; import edu.iu.grid.oim.view.LinkView; import edu.iu.grid.oim.view.SideContentView; import java.net.URI; import java.net.URL; import com.nimbusds.oauth2.sdk.client.*; //import com.nimbusds.oauth2.sdk.token.*; //import com.nimbusds.oauth2.sdk.util.*; import com.nimbusds.oauth2.sdk.id.*; import com.nimbusds.oauth2.sdk.auth.*; import com.nimbusds.oauth2.sdk.http.*; import com.nimbusds.oauth2.sdk.*; import com.nimbusds.openid.connect.sdk.*; import com.nimbusds.openid.connect.sdk.claims.*; import com.nimbusds.openid.connect.sdk.id.*; import com.nimbusds.openid.connect.sdk.op.*; import com.nimbusds.openid.connect.sdk.rp.*; import com.nimbusds.openid.connect.sdk.util.*; public class SSOServlet extends ServletBase { private static final long serialVersionUID = 1L; static Logger log = Logger.getLogger(HomeServlet.class); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserContext context = new UserContext(request); try { URI authzEndpoint = new URI("https://cilogon.org/authorize"); // The client identifier provisioned by the server \ ClientID clientID = new ClientID(StaticConfig.conf.getProperty("cilogon.client_id")); // The requested scope values for the token \ String clientIDstr = StaticConfig.conf.getProperty("cilogon.client_id"); Scope scope = new Scope("openid", "email","profile","org.cilogon.userinfo"); String scopestr = "scope=openid+email+profile+org.cilogon.userinfo"; Secret clientSecret = new Secret(StaticConfig.conf.getProperty("cilogon.client_secret")); String clientSecretstr = StaticConfig.conf.getProperty("cilogon.client_secret"); // The client callback URI, typically pre-registered with the server \ URI callback = new URI(StaticConfig.conf.getProperty("cilogon.callback")); String redirectURLstr =StaticConfig.conf.getProperty("cilogon.callback"); // Generate random state string for pairing the response to the request \ State state = new State(); // Build the request Nonce nonce = new Nonce(); if(request.getParameter("code")=="" || request.getParameter("code")==null){ try { // Compose the request (in code flow) AuthenticationRequest req = new AuthenticationRequest( authzEndpoint, new ResponseType(ResponseType.Value.CODE), Scope.parse("openid email profile org.cilogon.userinfo"), clientID, callback, state, nonce); URI requestURI = req.toURI(); String str = requestURI.toString(); response.sendRedirect(str); } catch(Exception exception) { System.out.println("Caught Exception: " + exception); } }else{ String code = request.getParameter("code"); try{ String url = "https://cilogon.org/oauth2/token"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String data = "grant_type=authorization_code&client_id=" + clientIDstr + "&client_secret=" + clientSecretstr + "&code=" +code + "&redirect_uri=" + redirectURLstr; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + data); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response5 = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response5.append(inputLine); } in.close(); //print result String jsonstr= response5.toString(); JSONObject json = (JSONObject) JSONValue.parseWithException(jsonstr); String access_token = (String) json.get("access_token"); String refresh_token = (String) json.get("refresh_token"); String id_token = (String) json.get("id_token"); String token_type = (String) json.get("token_type"); //Integer expires_in = (Integer) json.get("expires_in"); System.out.print(" String url_userinfo = "https://cilogon.org/oauth2/userinfo"; URL objuserinfo = new URL(url_userinfo); HttpsURLConnection conuserinfo = (HttpsURLConnection) objuserinfo.openConnection(); //add reuqest header conuserinfo.setRequestMethod("POST"); conuserinfo.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conuserinfo.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String datauserinfo = "access_token=" + access_token; // Send post request conuserinfo.setDoOutput(true); DataOutputStream wr_userinfo = new DataOutputStream(conuserinfo.getOutputStream()); wr_userinfo.writeBytes(datauserinfo); wr_userinfo.flush(); wr_userinfo.close(); // int responseCode1 = conuserinfo.getResponseCode(); BufferedReader in_userinfo = new BufferedReader( new InputStreamReader(conuserinfo.getInputStream())); String inputLine_userinfo; StringBuffer response5_userinfo = new StringBuffer(); while ((inputLine_userinfo = in_userinfo.readLine()) != null) { response5_userinfo.append(inputLine_userinfo); } in_userinfo.close(); //print result System.out.println("before json parse"); String jsonstr_userinfo= response5_userinfo.toString(); JSONObject json_userinfo = (JSONObject) JSONValue.parseWithException(jsonstr_userinfo); String access_email = (String) json_userinfo.get("email"); HttpSession session = request.getSession(); // String user_access= (String) session.getAttribute("user_access"); session.setAttribute("user_access", access_email); String user_access= (String) session.getAttribute("user_access"); System.out.println(user_access + " < = session email"); System.out.println(access_email + "<== access email"); System.out.print(" response.sendRedirect("/"); } catch(Exception exception) { System.out.println("Caught Exception: " + exception); } } } catch(Exception exception) { System.out.println("Caught Exception: " + exception); } BootMenuView menuview = new BootMenuView(context, "home"); BootPage page = new BootPage(context, menuview, new Content(context), createSideView(context)); page.addExCSS("home.css"); GenericView header = new GenericView(); header.add(new HtmlView("<h1>OSG Information Management System</h1>")); header.add(new HtmlView("<p class=\"lead\">Defines the topology used by various OSG services based on the <a target=\"_blank\" href=\"http://osg-docdb.opensciencegrid.org/cgi-bin/ShowDocument?docid=18\">OSG Blueprint Document</a></p>")); page.setPageHeader(header); page.render(response.getWriter()); } class Content implements IView { UserContext context; public Content(UserContext context) { this.context = context; } @Override public void render(PrintWriter out) { //out.write("<div>"); //disable authorization on the home pag 6/29/2017 Authorization auth = context.getAuthorization(); if(auth.isUser()) { try { ContactRecord user = auth.getContact(); Confirmation conf = new Confirmation(user.id, context); conf.render(out); } catch (SQLException e) { log.error(e); } //show entities that this user is associated try { ContactAssociationView caview = new ContactAssociationView(context, auth.getContact().id); caview.showNewButtons(true); caview.render(out); } catch (SQLException e) { log.error(e); } } else { //guest view out.write("<div class=\"row-fluid\">"); out.write("<div class=\"span4 hotlink\" onclick=\"document.location='topology';\">"); out.write("<h2>Topology</h2>"); out.write("<p>Defines resource hierarchy</p>"); out.write("<img src=\"images/topology.png\">"); out.write("</div>"); out.write("<div class=\"span4 hotlink\" onclick=\"document.location='vo';\">"); out.write("<h2>Virtual Organization</h2>"); out.write("<p>Defines access for group of users</p>"); out.write("<img src=\"images/voicon.png\">"); out.write("</div>"); out.write("<div class=\"span4 hotlink\" onclick=\"document.location='sc';\">"); out.write("<h2>Support Centers</h2>"); out.write("<p>Defines who supports virtual organization</p>"); out.write("<img src=\"images/scicon.png\">"); out.write("</div>"); out.write("</div>"); } //out.write("</div>"); } } private SideContentView createSideView(UserContext context) { SideContentView contentview = new SideContentView(); Authorization auth = context.getAuthorization(); if(auth.isUnregistered()) { contentview.add(new HtmlView("<div class=\"alert alert-info\"><p>Your certificate is not yet registered with OIM.</p><p><a class=\"btn btn-info\" href=\"register\">Register</a></p></div>")); } else if(auth.isDisabled()) { contentview.add(new HtmlView("<div class=\"alert alert-danger\"><p>Your contact or DN is disabled. Please contact GOC for more information.</p><a class=\"btn btn-danger\" href=\"https://ticket.grid.iu.edu\">Contact GOC</a></p></div>")); } else if(!auth.isUser()) { String text = "<p>OIM requires an X509 certificate issued by an <a target=\"_blank\" href='http://software.grid.iu.edu/cadist/'>OSG-approved Certifying Authority (CA)</a> to authenticate.</p>"+ "<p><a class=\"btn btn-info\" href=\"/oim/certificaterequestuser\">Request New Certificate</a></p>"+ "If you already have a certificate installed on your browser, please login.</p><p><a class=\"btn btn-info\" href=\""+context.getSecureUrl()+"\">Login</a></p>"; contentview.add(new HtmlView("<div class=\"alert alert-info\"><p>"+text+"</p></div>")); } contentview.add(new HtmlView("<h2>Documentations</h2>")); contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMTermDefinition", "OIM Definitions", true)); contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMRegistrationInstructions", "Registration", true)); contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMMaintTool", "Resource Downtime", true)); if(auth.isUser()) { contentview.addContactLegend(); } return contentview; } @SuppressWarnings("serial") class Confirmation extends DivRep { final ContactRecord crec; final ContactModel cmodel; final UserContext context; public Confirmation(Integer contact_id, UserContext _context) throws SQLException { super(_context.getPageRoot()); cmodel = new ContactModel(_context); crec = (ContactRecord) cmodel.get(contact_id);//.clone(); context = _context; } protected void onEvent(DivRepEvent e) { // TODO Auto-generated method stub } public void render(PrintWriter out) { if(crec.isConfirmationExpired()) { out.write("<div id=\""+getNodeID()+"\">"); out.write("<h2>Content Confirmation</h2>"); out.write("<p class=\"divrep_round divrep_elementerror\">You have not recently confirmed that your information in OIM is current</p>"); out.write("<p>The last time you confirmed your profile information was "+crec.confirmed.toString()+"</p>"); out.write("<p>Please go to the "); out.write("<a href=\"profileedit\">My Profile</a>"); out.write(" page to check your profile information</p>"); out.write("</div>"); } } } }
package edu.miamioh.cse283.htw; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; /** * Proxy client object. */ public class ClientProxy { /** * This socket is connected to a client. */ private Socket s; /** * Used to read from the client's socket. */ private BufferedReader in; /** * Used to write to the client's socket. */ private PrintWriter out; private Room currentRoom; private boolean alive; private int arrows; private int gold; /** * Constructor. */ public ClientProxy(Socket s) throws IOException { this.s = s; try { this.out = new PrintWriter(s.getOutputStream(), true); this.in = new BufferedReader(new InputStreamReader(s.getInputStream())); this.alive = true; this.arrows = Protocol.INITIAL_ARROWS; gold = 0; } catch (IOException ex) { try { s.close(); } catch (IOException ex2) { } throw ex; } } /** * Close the connection to the client. */ public void close() throws IOException { currentRoom.leaveRoom(this); s.close(); } public int getArrows() { return arrows; } public void pickupArrows() { arrows += Protocol.ROOM_ARROWS; sendNotifications(String.format("You now have %d arrows!", arrows)); } public void shootArrow() { --arrows; } public void increaseGold(int delta) { assert delta > 0; gold += delta; sendNotifications(String.format("You now have %d gold!", gold)); } public int getGold() { return gold; } /** * Send a handoff message to this client. */ public void handoff(InetAddress addr, int port) { String msg = Protocol.HANDOFF + " " + addr.getHostName() + " " + port; out.println(msg); } /** * Send notification messages to the client. */ public void sendNotifications(String... notifications) { out.println(Protocol.BEGIN_NOTIFICATION); for (String i : notifications) { out.println(i); } out.println(Protocol.END_NOTIFICATION); } /** * Send a block message of notifications to the client. */ public void sendNotifications(ArrayList<String> blockMsg) { sendNotifications(blockMsg.toArray(new String[blockMsg.size()])); } /** * Send a block message of sensory information to the client. */ public void sendSenses(ArrayList<String> blockMsg) { out.println(Protocol.BEGIN_SENSES); for (String i : blockMsg) { out.println(i); } out.println(Protocol.END_SENSES); } public Room getCurrentRoom() { return currentRoom; } /** * Moves this ClientProxy from the current Room to the given Room and send senses to client * * @param toEnter the room to which this ClientProxy should move */ public synchronized void changeRoom(Room toEnter) { changeRoom(toEnter, true); } /** * Moves this ClientProxy from the current Room to the given Room. * * @param toEnter the room to which this ClientProxy should move * @param sendInfo if this is true, send senses to the client, otherwise do not send senses to client */ public synchronized void changeRoom(Room toEnter, boolean sendInfo) { if (currentRoom != null) { currentRoom.leaveRoom(this); } currentRoom = toEnter; toEnter.enterRoom(this); if (sendInfo) { sendSenses(currentRoom.getSensed()); } } /** * Returns true if the player is alive. */ public synchronized boolean isAlive() { return alive; } /** * Send a DIED message. */ public synchronized void kill() { out.println(Protocol.DIED); alive = false; } /** * Returns true if this client has data that can be read. */ public boolean ready() throws IOException { return in.ready(); } /** * Get an action from the client. */ public String nextLine() throws IOException { return in.readLine(); } }
package eu.visualize.ini.retinamodel; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Observer; import java.util.Random; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.glu.GLU; import net.sf.jaer.Description; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.util.filter.LowpassFilter; /** * Models a single object motion cell that is excited by on or off activity * within its classical receptive field but is inhibited by synchronous on or * off activity in its extended RF, such as that caused by a saccadic eye * movement. Also gives direction of movement of object * * @author diederik */ @Description("Models object motion cell known from mouse and salamander retina") //@DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class OMCOD extends AbstractRetinaModelCell implements FrameAnnotater, Observer { private OMCODModel OMCODModel = new OMCODModel(); private float synapticWeight = getFloat("synapticWeight", 1f); private float centerExcitationToSurroundInhibitionRatio = getFloat("centerExcitationToSurroundInhibitionRatio", 0.4386f); private boolean surroundSuppressionEnabled = getBoolean("surroundSuppressionEnabled", false); private Subunits subunits; private int nxmax =chip.getSizeX() >> getSubunitSubsamplingBits(); private int nymax =chip.getSizeY() >> getSubunitSubsamplingBits(); private float[][] inhibitionArray = new float [nxmax-1][nymax-1]; private float[][] excitationArray = new float [nxmax-1][nymax-1]; private float subunitActivityBlobRadiusScale = getFloat("subunitActivityBlobRadiusScale", 0.004f); private float integrateAndFireThreshold = getFloat("integrateAndFireThreshold", 1f); private float nonLinearityOrder = getFloat("nonLinearityOrder", 2f); private boolean startLogging = getBoolean("startLogging", false); private boolean deleteLogging = getBoolean("deleteLogging", false); private float barsHeight = getFloat("barsHeight", 0.000020f); private int excludedEdgeSubunits = getInt("excludedEdgeSubunits", 1); private int showXcoord = getInt("showXcoord", 1); private int showYcoord = getInt("showYcoord", 1); private int tanhSaturation = getInt("tanhSaturation", 1); private boolean exponentialToTanh = getBoolean("exponentialToTanh", false); public OMCOD(AEChip chip) { super(chip); chip.addObserver(this); setPropertyTooltip("showSubunits", "Enables showing subunit activity annotation over retina output"); setPropertyTooltip("showOutputCell", "Enables showing object motion cell activity annotation over retina output"); setPropertyTooltip("subunitSubsamplingBits", "Each subunit integrates events from 2^n by 2^n pixels, where n=subunitSubsamplingBits"); setPropertyTooltip("synapticWeight", "Subunit activity inputs to the objectMotion neuron are weighted this much; use to adjust response magnitude"); setPropertyTooltip("subunitDecayTimeconstantMs", "Subunit activity decays with this time constant in ms"); setPropertyTooltip("enableSpikeSound", "Enables audio spike output from objectMotion cell"); setPropertyTooltip("maxSpikeRateHz", "Maximum spike rate of objectMotion cell in Hz"); setPropertyTooltip("centerExcitationToSurroundInhibitionRatio", "Inhibitory ON subunits are weighted by factor more than excitatory OFF subunit activity to the object motion cell"); setPropertyTooltip("minUpdateIntervalUs", "subunits activities are decayed to zero at least this often in us, even if they receive no input"); setPropertyTooltip("surroundSuppressionEnabled", "subunits are suppressed by surrounding activity of same type; reduces response to global dimming"); setPropertyTooltip("subunitActivityBlobRadiusScale", "The blobs represeting subunit activation are scaled by this factor"); setPropertyTooltip("integrateAndFireThreshold", "The ganglion cell will fire if the difference between excitation and inhibition overcomes this threshold"); setPropertyTooltip("poissonFiringEnabled", "The ganglion cell fires according to Poisson rate model for net synaptic input"); setPropertyTooltip("nonLinearityOrder", "The non-linear order of the subunits' value before the total sum"); setPropertyTooltip("startLogging", "Start logging inhibition and excitation"); setPropertyTooltip("deleteLogging", "Delete the logging of inhibition and excitation"); setPropertyTooltip("barsHeight", "set the magnitute of cen and sur if the inhibition and excitation are out of range"); setPropertyTooltip("excludedEdgeSubunits", "Set the number of subunits excluded from computation at the edge"); setPropertyTooltip("tanhSaturation", "Set the maximum contribution of a single subunit, where it saturates"); setPropertyTooltip("exponentialToTanh", "Switch from exponential non-linearity to exponential tangent"); setPropertyTooltip("showXcoord", "decide which Object Motion Cell to show by selecting the X coordinate of the center"); setPropertyTooltip("showYcoord", "decide which Object Motion Cell to show by selecting the Y coordinate of the center"); } private int lastOMCODSpikeCheckTimestamp = 0; @Override public EventPacket<?> filterPacket(EventPacket<?> in) { if (!(in.getEventPrototype() instanceof PolarityEvent)) { return in; } if (in instanceof ApsDvsEventPacket) { checkOutputPacketEventType(in); // make sure memory is allocated to avoid leak. we don't use output packet but it is necesary to iterate over DVS events only } clearOutputPacket(); if (subunits == null) { resetFilter(); } for (Object o : in) { PolarityEvent e = (PolarityEvent) o; if (e.special) { continue; } subunits.update(e); int dt = e.timestamp - lastOMCODSpikeCheckTimestamp; if (dt < 0) { lastOMCODSpikeCheckTimestamp = e.timestamp; return in; } if (dt > minUpdateIntervalUs) { lastOMCODSpikeCheckTimestamp = e.timestamp; OMCODModel.update(e.timestamp); } } // System.out.println(String.format("spikeRate=%.1g \tonActivity=%.2f \toffActivity=%.1f", OMCODModel.spikeRate, inhibition, offExcitation)); return in; } @Override public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); GL2 gl = drawable.getGL().getGL2(); gl.glPushMatrix(); gl.glTranslatef(chip.getSizeX() / 2, chip.getSizeY() / 2, 10); if ((showXcoord<0) || (showYcoord<0) || (showXcoord>nxmax-1) || (showYcoord>nymax-1)){ showXcoord = 1; showYcoord = 1; } if (showOutputCell && (OMCODModel.nSpikesArray[showXcoord][showYcoord]!=0)) { gl.glColor4f(1, 1, 1, .2f); glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL); float radius = (chip.getMaxSize() * OMCODModel.spikeRateHz) / maxSpikeRateHz / 2; glu.gluDisk(quad, 0, radius, 32, 1); OMCODModel.resetSpikeCount(); } gl.glPopMatrix(); if (showSubunits) { gl.glColor4f(0, 1, 0, .3f); gl.glRectf(-10, 0, -5, barsHeight*inhibitionArray[showXcoord][showYcoord]); gl.glColor4f(1, 0, 0, .3f); gl.glRectf(-20, 0, -15, barsHeight*excitationArray[showXcoord][showYcoord]); renderer.begin3DRendering(); renderer.setColor(0, 1, 0, .3f); renderer.draw3D("sur", -10, -3, 0, .4f); renderer.setColor(1, 0, 0, .3f); renderer.draw3D("cen", -20, -3, 0, .4f); renderer.end3DRendering(); // render all the subunits now subunits.render(gl); } } @Override public void resetFilter() { subunits = new Subunits(); } @Override public void initFilter() { resetFilter(); } /** * @return the subunitActivityBlobRadiusScale */ public float getSubunitActivityBlobRadiusScale() { return subunitActivityBlobRadiusScale; } /** * @param subunitActivityBlobRadiusScale the subunitActivityBlobRadiusScale * to set */ public void setSubunitActivityBlobRadiusScale(float subunitActivityBlobRadiusScale) { this.subunitActivityBlobRadiusScale = subunitActivityBlobRadiusScale; putFloat("subunitActivityBlobRadiusScale", subunitActivityBlobRadiusScale); } // handles all subunits on and off private class Subunits { Subunit[][] subunits; int nx; int ny; int ntot; int lastUpdateTimestamp; FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object public Subunits() { reset(); } synchronized public void update(PolarityEvent e) { // subsample retina address to clump retina input pixel blocks. int x = e.x >> subunitSubsamplingBits, y = e.y >> subunitSubsamplingBits; if ((x < nx) && (y < ny)) { switch (e.polarity) { case Off: // these subunits are excited by OFF events and in turn excite the approach cell subunits[x][y].updatepos(e); break; case On: // these are excited by ON activity and in turn inhibit the approach cell subunits[x][y].updatepos(e); break; // all subunits are excited by any retina on or off activity } } maybeDecayAll(e); } void maybeDecayAll(BasicEvent e) { int dt = e.timestamp - lastUpdateTimestamp; if (dt < 0) { lastUpdateTimestamp = e.timestamp; return; } if (dt > minUpdateIntervalUs) { lastUpdateTimestamp = e.timestamp; // now update all subunits to RC decay activity toward zero float decayFactor = (float) Math.exp(-dt / (1000 * subunitDecayTimeconstantMs)); for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { subunits[x][y].decayBy(decayFactor); } } } } float[][] computeInhibitionToOutputCell() { // For all subunits, excluding the edge ones and the last ones (far right and bottom) for (int nsx = excludedEdgeSubunits; nsx < (nx-1-excludedEdgeSubunits); nsx++) { for (int nsy = excludedEdgeSubunits; nsy < (nx-1-excludedEdgeSubunits); nsy++) { // Find inhibition around center made of [nsx,nsy], [nsx+1,nsy+1], [nsx+1,nsy], [nsx,nsy+1] for (int x = excludedEdgeSubunits; x < (nx-excludedEdgeSubunits); x++) { for (int y = excludedEdgeSubunits; y < (ny-excludedEdgeSubunits); y++) { // Select computation type if(!exponentialToTanh){// Use non-linear model (given the nonlinearity order) if (((x == nsx) && (y == nsy)) || ((x == nsx+1) && (y == nsy+1)) || ((x == nsx) && (y == nsy+1)) || ((x == nsx+1) && (y == nsy))) { } // Ignore center else { inhibitionArray[nsx][nsy] += (float) Math.pow(subunits[x][y].computeInputToCell(),nonLinearityOrder); } } else{ // Use tanh model (given saturation value): preferred method if (((x == nsx) && (y == nsy)) || ((x == nsx+1) && (y == nsy+1)) || ((x == nsx) && (y == nsy+1)) || ((x == nsx+1) && (y == nsy))) { } // Ignore center else { inhibitionArray[nsx][nsy] += tanhSaturation*Math.tanh(subunits[x][y].computeInputToCell()); } } } } inhibitionArray[nsx][nsy] /= (ntot - 4); // Divide by the number of subunits to normalise inhibitionArray[nsx][nsy] = synapticWeight * inhibitionArray[nsx][nsy]; // Give a synaptic weight (a simple scalar value) // Log inhibitionArray if (startLogging == true){ try { // Create a new file output stream FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Diederik Paul Moeys\\Desktop\\inhibitionArray.txt"),true); // Connect print stream to the output stream p = new PrintStream(out); p.print(inhibitionArray); p.print(", "); p.println(lastUpdateTimestamp); p.close(); } catch (Exception e) { System.err.println("Error writing to file"); } } // Delete inhibitionArray if (deleteLogging == true){ File fout = new File("C:\\Users\\Diederik Paul Moeys\\Desktop\\inhibitionArray.txt"); fout.delete(); } } } return inhibitionArray; } float[][] computeExcitationToOutputCell() { // For all subunits, excluding the edge ones and the last ones (far right and bottom) for (int nsx = excludedEdgeSubunits; nsx < (nx-1-excludedEdgeSubunits); nsx++) { for (int nsy = excludedEdgeSubunits; nsy < (nx-1-excludedEdgeSubunits); nsy++) { // Find excitation of center made of [nsx,nsy], [nsx+1,nsy+1], [nsx+1,nsy], [nsx,nsy+1] for (int x = excludedEdgeSubunits; x < (nx-excludedEdgeSubunits); x++) { for (int y = excludedEdgeSubunits; y < (ny-excludedEdgeSubunits); y++) { // Select computation type if(!exponentialToTanh){// Use non-linear model (given the nonlinearity order) if (((x == nsx) && (y == nsy)) || ((x == nsx+1) && (y == nsy+1)) || ((x == nsx) && (y == nsy+1)) || ((x == nsx+1) && (y == nsy))) { // Average of 4 central cells excitationArray[nsx][nsy] = (float)((centerExcitationToSurroundInhibitionRatio*Math.pow(synapticWeight * subunits[x][y].computeInputToCell(),nonLinearityOrder))+ (centerExcitationToSurroundInhibitionRatio*Math.pow(synapticWeight * subunits[x+1][y+1].computeInputToCell(),nonLinearityOrder))+ (centerExcitationToSurroundInhibitionRatio*Math.pow(synapticWeight * subunits[x+1][y].computeInputToCell(),nonLinearityOrder))+ (centerExcitationToSurroundInhibitionRatio*Math.pow(synapticWeight * subunits[x][y+1].computeInputToCell(),nonLinearityOrder)))/4; } else { } // Ignore surround } else{ // Use tanh model (given saturation value): preferred method if (((x == nsx) && (y == nsy)) || ((x == nsx+1) && (y == nsy+1)) || ((x == nsx) && (y == nsy+1)) || ((x == nsx+1) && (y == nsy))) { // Average of 4 central cells excitationArray[nsx][nsy] = (float)((tanhSaturation*Math.tanh((centerExcitationToSurroundInhibitionRatio * synapticWeight * subunits[x][y].computeInputToCell()))) + (tanhSaturation*Math.tanh((centerExcitationToSurroundInhibitionRatio * synapticWeight * subunits[x+1][y+1].computeInputToCell()))) + (tanhSaturation*Math.tanh((centerExcitationToSurroundInhibitionRatio * synapticWeight * subunits[x+1][y].computeInputToCell()))) + (tanhSaturation*Math.tanh((centerExcitationToSurroundInhibitionRatio * synapticWeight * subunits[x][y+1].computeInputToCell())))) / 4; } else { } // Ignore surround } // Log excitationArray if(startLogging == true){ try { // Create a new file output stream. FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Diederik Paul Moeys\\Desktop\\excitationArray.txt"), true); // Connect print stream to the output stream p = new PrintStream(out); p.print(excitationArray); p.print(", "); p.println(lastUpdateTimestamp); p.close(); out.close(); } catch (Exception e) { System.err.println("Error writing to file"); } } if (deleteLogging == true){ File fout = new File("C:\\Users\\Diederik Paul Moeys\\Desktop\\excitationArray.txt"); fout.delete(); } } } } } return excitationArray; } synchronized private void reset() { // Reset arrays float[][] inhibitionArray = new float [nxmax-1][nymax-1]; for(int i=0;i<inhibitionArray.length;i++) { for(int j=0;j<inhibitionArray.length;j++) { inhibitionArray[i][j] = 0; } } float[][] excitationArray = new float [nxmax-1][nymax-1]; for(int i=0;i<excitationArray.length;i++) { for(int j=0;j<excitationArray.length;j++) { excitationArray[i][j] = 0; } } nx = (chip.getSizeX() >> getSubunitSubsamplingBits()); ny = (chip.getSizeY() >> getSubunitSubsamplingBits()); if (nx < 4) { nx = 4; } if (ny < 4) { ny = 4; // always at least 4 subunits or computation does not make sense } ntot = (nx-excludedEdgeSubunits) * (ny-excludedEdgeSubunits); subunits = new Subunit[nx][ny]; for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { subunits[x][y] = new Subunit(x, y, subunits); } } } private void render(GL2 gl) { final float alpha = .2f; glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL); int off = (1 << (subunitSubsamplingBits)) / 2; for (int x = excludedEdgeSubunits; x < (nx-excludedEdgeSubunits); x++) { for (int y = excludedEdgeSubunits; y < (ny-excludedEdgeSubunits); y++) { gl.glPushMatrix(); gl.glTranslatef((x << subunitSubsamplingBits) + off, (y << subunitSubsamplingBits) + off, 5); if (((x == (nx / 2)) && (y == (ny / 2))) || ((x == ((nx / 2) - 1)) && (y == (ny / 2))) || ((x == ((nx / 2) - 1)) && (y == ((ny / 2) - 1))) || ((x == (nx / 2)) && (y == ((ny / 2) - 1)))) { gl.glColor4f(1, 0, 0, alpha); } else { gl.glColor4f(0, 1, 0, alpha); } glu.gluDisk(quad, 0, subunitActivityBlobRadiusScale * subunits[x][y].computeInputToCell(), 16, 1); gl.glPopMatrix(); } } renderer.begin3DRendering(); renderer.setColor(1, 0, 0, 1); renderer.draw3D("Center", 0, chip.getSizeY(), 0, .5f); renderer.setColor(0, 1, 0, 1); renderer.draw3D("Surround", chip.getSizeX() / 2, chip.getSizeY(), 0, .5f); renderer.end3DRendering(); } } // models one single subunit ON or OFF. // polarity is ignored here and only handled on update of objectMotion cell private class Subunit { float vmem; int x, y; Subunit[][] mySubunits; public Subunit(int x, int y, Subunit[][] mySubunits) { this.x = x; this.y = y; this.mySubunits = mySubunits; } public void decayBy(float factor) { vmem *= factor; } public void updatepos(PolarityEvent e) { vmem = vmem + 1; } public void updateneg (PolarityEvent e) { vmem = vmem - 1; } /** * subunit input is pure rectification */ public float computeInputToCell() { if (!surroundSuppressionEnabled) { // if (vmem < 0) { // return 0; // actually it cannot be negative since it only gets excitation from DVS events // } else { return vmem; } else { // surround inhibition // here we return the half-rectified local difference between ourselves and our neighbors int n = 0; float sum = 0; if ((x + 1) < subunits.nx) { sum += mySubunits[x + 1][y].vmem; n++; } if ((x - 1) >= 0) { sum += mySubunits[x - 1][y].vmem; n++; } if ((y + 1) < subunits.ny) { sum += mySubunits[x][y + 1].vmem; n++; } if ((y - 1) >= 0) { sum += mySubunits[x][y - 1].vmem; n++; } sum /= n; float result = vmem - sum; if (result < 0) { return 0; } else { return result; // half rectify result } } } } // models soma and integration and spiking of objectMotion cell private class OMCODModel { int lastTimestamp = 0; Random r = new Random(); private float[][] membraneStateArray = new float [nxmax-1][nymax-1]; private float[][] netSynapticInputArray = new float [nxmax-1][nymax-1]; private int[][] nSpikesArray = new int [nxmax-1][nymax-1]; // counts spikes since last rendering cycle private LowpassFilter isiFilter = new LowpassFilter(300); private int lastSpikeTimestamp = 0; private boolean initialized = false; float spikeRateHz = 0; boolean result = false; synchronized private boolean update(int timestamp) { // compute subunit input to us for(int nsx=0;nsx<(nxmax-1);nsx++) { for(int nsy=0;nsy<(nymax-1);nsy++) { netSynapticInputArray[nsx][nsy] = (subunits.computeExcitationToOutputCell()[nsx][nsy] - subunits.computeInhibitionToOutputCell()[nsx][nsy]); int dtUs = timestamp - lastTimestamp; if (dtUs < 0) { dtUs = 0; // to handle negative dt } lastTimestamp = timestamp; if (poissonFiringEnabled) { float spikeRate = netSynapticInputArray[nsx][nsy]; if (spikeRate < 0) { result = false; } if (spikeRate > maxSpikeRateHz) { spikeRate = maxSpikeRateHz; } if (r.nextFloat() < (spikeRate * 1e-6f * dtUs)) { spike(timestamp, nsx, nsy); result = true; } else { result = false; } } else { // IF neuron membraneStateArray[nsx][nsy] += netSynapticInputArray[nsx][nsy] * dtUs * 1e-6f; if (membraneStateArray[nsx][nsy] > integrateAndFireThreshold) { spike(timestamp, nsx, nsy); membraneStateArray[nsx][nsy] = 0; result = true; } else if (membraneStateArray[nsx][nsy] < -10) { membraneStateArray[nsx][nsy] = 0; result = false; } else { result = false; } } } } return result; } void spike(int timestamp, int x, int y) { if (enableSpikeSound) { spikeSound.play(); } nSpikesArray[x][y]++; int dtUs = timestamp - lastSpikeTimestamp; if (initialized && (dtUs>=0)) { float avgIsiUs = isiFilter.filter(dtUs, timestamp); spikeRateHz = 1e6f / avgIsiUs; } else { initialized = true; } lastSpikeTimestamp = timestamp; } void reset() { for(int nsx=0;nsx<(nymax-1);nsx++) { for(int nsy=0;nsy<(nymax-1);nsy++) { membraneStateArray[nsx][nsy] = 0; } } isiFilter.reset(); initialized=false; } private void resetSpikeCount() { for(int i=0;i<nSpikesArray.length;i++) { for(int j=0;j<nSpikesArray.length;j++) { nSpikesArray[i][j] = 0; } } } } /** * @return the subunitDecayTimeconstantMs */ public float getSubunitDecayTimeconstantMs() { return subunitDecayTimeconstantMs; } /** * * @return the integrateAndFireThreshold * */ public float getIntegrateAndFireThreshold() { return integrateAndFireThreshold; } /** * * @param integrateAndFireThreshold the integrateAndFireThreshold to set * */ public void setIntegrateAndFireThreshold(float integrateAndFireThreshold) { this.integrateAndFireThreshold = integrateAndFireThreshold; putFloat("integrateAndFireThreshold", integrateAndFireThreshold); } public int getShowXcoord() { return showXcoord; } /** * * @param showXcoord the showXcoord to set * */ public void setShowXcoord(int showXcoord) { this.showXcoord = showXcoord; putInt("showXcoord", showXcoord); } public int getShowYcoord() { return showYcoord; } /** * * @param showYcoord the showYcoord to set * */ public void setShowYcoord(int showYcoord) { this.showYcoord = showYcoord; putInt("showYcoord", showYcoord); } /** * * @return the nonLinearityOrder * */ public float getNonLinearityOrder() { return nonLinearityOrder; } /** * * @param nonLinearityOrder the nonLinearityOrder to set * */ public void setNonLinearityOrder(float nonLinearityOrder) { this.nonLinearityOrder = nonLinearityOrder; putFloat("nonLinearityOrder", nonLinearityOrder); } /** * @return the synapticWeight */ public float getSynapticWeight() { return synapticWeight; } /** * @param synapticWeight the synapticWeight to set */ public void setSynapticWeight(float synapticWeight) { this.synapticWeight = synapticWeight; putFloat("synapticWeight", synapticWeight); } /** * @return the barsHeight */ public float getBarsHeight() { return barsHeight; } /** * @param barsHeight the barsHeight to set */ public void setBarsHeight(float barsHeight) { this.barsHeight = barsHeight; putFloat("barsHeight", barsHeight); } /** * @return the excludedEdgeSubunits */ public int getExcludedEdgeSubunits() { return excludedEdgeSubunits; } /** * @param excludedEdgeSubunits the excludedEdgeSubunits to set */ public void setExcludedEdgeSubunits(int excludedEdgeSubunits) { this.excludedEdgeSubunits = excludedEdgeSubunits; putFloat("excludedEdgeSubunits", excludedEdgeSubunits); } /** * @return the onOffWeightRatio */ public float getCenterExcitationToSurroundInhibitionRatio() { return centerExcitationToSurroundInhibitionRatio; } /** * @param onOffWeightRatio the onOffWeightRatio to set */ public void setCenterExcitationToSurroundInhibitionRatio(float onOffWeightRatio) { this.centerExcitationToSurroundInhibitionRatio = onOffWeightRatio; putFloat("centerExcitationToSurroundInhibitionRatio", onOffWeightRatio); } /** * @return the tanhSaturation */ public int getTanhSaturation() { return tanhSaturation; } /** * @param tanhSaturation the tanhSaturation to set */ public void setTanhSaturation(int tanhSaturation) { this.tanhSaturation = tanhSaturation; putInt("tanhSaturation", tanhSaturation); } /** * @return the deleteLogging */ public boolean isDeleteLogging() { return deleteLogging; } /** * @param deleteLogging the deleteLogging to set */ public void setDeleteLogging(boolean deleteLogging) { this.deleteLogging = deleteLogging; putBoolean("deleteLogging", deleteLogging); } /** * @return the exponentialToTanh */ public boolean isExponentialToTanh() { return exponentialToTanh; } /** * @param exponentialToTanh the exponentialToTanh to set */ public void setExponentialToTanh(boolean exponentialToTanh) { this.exponentialToTanh = exponentialToTanh; putBoolean("exponentialToTanh", exponentialToTanh); } /** * @return the startLogging */ public boolean isStartLogging() { return startLogging; } /** * @param startLogging the startLogging to set */ public void setStartLogging(boolean startLogging) { this.startLogging = startLogging; putBoolean("startLogging", startLogging); } /** * @return the surroundSuppressionEnabled */ public boolean isSurroundSuppressionEnabled() { return surroundSuppressionEnabled; } /** * @param surroundSuppressionEnabled the surroundSuppressionEnabled to set */ public void setSurroundSuppressionEnabled(boolean surroundSuppressionEnabled) { this.surroundSuppressionEnabled = surroundSuppressionEnabled; putBoolean("surroundSuppressionEnabled", surroundSuppressionEnabled); } }
/** @author Aron Culotta <a href="mailto:culotta@cs.umass.edu">culotta@cs.umass.edu</a> */ /** Limited Memory BFGS, as described in Byrd, Nocedal, and Schnabel, "Representations of Quasi-Newton Matrices and Their Use in Limited Memory Methods" */ package cc.mallet.optimize; import java.util.logging.*; import java.util.LinkedList; import cc.mallet.optimize.BackTrackLineSearch; import cc.mallet.optimize.LineOptimizer; import cc.mallet.optimize.Optimizable; import cc.mallet.types.MatrixOps; import cc.mallet.util.MalletLogger; public class LimitedMemoryBFGS implements Optimizer { private static Logger logger = MalletLogger.getLogger("edu.umass.cs.mallet.base.ml.maximize.LimitedMemoryBFGS"); boolean converged = false; Optimizable.ByGradientValue optimizable; final int maxIterations = 1000; // xxx need a more principled stopping point //final double tolerance = .0001; private double tolerance = .0001; final double gradientTolerance = .001; final double eps = 1.0e-5; // The number of corrections used in BFGS update // ideally 3 <= m <= 7. Larger m means more cpu time, memory. final int m = 4; // Line search function private LineOptimizer.ByGradient lineMaximizer; public LimitedMemoryBFGS (Optimizable.ByGradientValue function) { this.optimizable = function; lineMaximizer = new BackTrackLineSearch (function); } public Optimizable getOptimizable () { return this.optimizable; } public boolean isConverged () { return converged; } /** * Sets the LineOptimizer.ByGradient to use in L-BFGS optimization. * @param lineOpt line optimizer for L-BFGS */ public void setLineOptimizer(LineOptimizer.ByGradient lineOpt) { lineMaximizer = lineOpt; } // State of search // g = gradient // s = list of m previous "parameters" values // y = list of m previous "g" values // rho = intermediate calculation double [] g, oldg, direction, parameters, oldParameters; LinkedList s = new LinkedList(); LinkedList y = new LinkedList(); LinkedList rho = new LinkedList(); double [] alpha; static double step = 1.0; int iterations; private OptimizerEvaluator.ByGradient eval = null; // CPAL - added this public void setTolerance(double newtol) { this.tolerance = newtol; } public void setEvaluator (OptimizerEvaluator.ByGradient eval) { this.eval = eval; } public int getIteration () { return iterations; } public boolean optimize () { return optimize (Integer.MAX_VALUE); } public boolean optimize (int numIterations) { double initialValue = optimizable.getValue(); logger.fine("Entering L-BFGS.optimize(). Initial Value="+initialValue); if(g==null) { //first time through logger.fine("First time through L-BFGS"); iterations = 0; s = new LinkedList(); y = new LinkedList(); rho = new LinkedList(); alpha = new double[m]; for(int i=0; i<m; i++) alpha[i] = 0.0; parameters = new double[optimizable.getNumParameters()]; oldParameters = new double[optimizable.getNumParameters()]; g = new double[optimizable.getNumParameters()]; oldg = new double[optimizable.getNumParameters()]; direction = new double[optimizable.getNumParameters()]; optimizable.getParameters (parameters); System.arraycopy (parameters, 0, oldParameters, 0, parameters.length); optimizable.getValueGradient (g); System.arraycopy (g, 0, oldg, 0, g.length); System.arraycopy (g, 0, direction, 0, g.length); if (MatrixOps.absNormalize (direction) == 0) { logger.info("L-BFGS initial gradient is zero; saying converged"); g = null; converged = true; return true; } logger.fine ("direction.2norm: " + MatrixOps.twoNorm (direction)); MatrixOps.timesEquals(direction, 1.0 / MatrixOps.twoNorm(direction)); // make initial jump logger.fine ("before initial jump: \ndirection.2norm: " + MatrixOps.twoNorm (direction) + " \ngradient.2norm: " + MatrixOps.twoNorm (g) + "\nparameters.2norm: " + MatrixOps.twoNorm(parameters)); //TestMaximizable.testValueAndGradientInDirection (maxable, direction); step = lineMaximizer.optimize(direction, step); if (step == 0.0) {// could not step in this direction. // give up and say converged. g = null; // reset search step = 1.0; throw new OptimizationException("Line search could not step in the current direction. " + "(This is not necessarily cause for alarm. Sometimes this happens close to the maximum," + " where the function may be very flat.)"); //return false; } optimizable.getParameters (parameters); optimizable.getValueGradient(g); logger.fine ("after initial jump: \ndirection.2norm: " + MatrixOps.twoNorm (direction) + " \ngradient.2norm: " + MatrixOps.twoNorm (g)); } for(int iterationCount = 0; iterationCount < numIterations; iterationCount++) { double value = optimizable.getValue(); logger.fine("L-BFGS iteration="+iterationCount +", value="+value+" g.twoNorm: "+MatrixOps.twoNorm(g)+ " oldg.twoNorm: "+MatrixOps.twoNorm(oldg)); // get difference between previous 2 gradients and parameters double sy = 0.0; double yy = 0.0; for (int i=0; i < oldParameters.length; i++) { // -inf - (-inf) = 0; inf - inf = 0 if (Double.isInfinite(parameters[i]) && Double.isInfinite(oldParameters[i]) && (parameters[i]*oldParameters[i] > 0)) oldParameters[i] = 0.0; else oldParameters[i] = parameters[i] - oldParameters[i]; if (Double.isInfinite(g[i]) && Double.isInfinite(oldg[i]) && (g[i]*oldg[i] > 0)) oldg[i] = 0.0; else oldg[i] = g[i] - oldg[i]; sy += oldParameters[i] * oldg[i]; // si * yi yy += oldg[i]*oldg[i]; direction[i] = g[i]; } if ( sy > 0 ) { throw new InvalidOptimizableException ("sy = "+sy+" > 0" ); } double gamma = sy / yy; // scaling factor if ( gamma>0 ) throw new InvalidOptimizableException ("gamma = "+gamma+" > 0" ); push (rho, 1.0/sy); push (s, oldParameters); push (y, oldg); // calculate new direction assert (s.size() == y.size()) : "s.size: " + s.size() + " y.size: " + y.size(); for(int i = s.size() - 1; i >= 0; i alpha[i] = ((Double)rho.get(i)).doubleValue() * MatrixOps.dotProduct ( (double[])s.get(i), direction); MatrixOps.plusEquals (direction, (double[])y.get(i), -1.0 * alpha[i]); } MatrixOps.timesEquals(direction, gamma); for(int i = 0; i < y.size(); i++) { double beta = (((Double)rho.get(i)).doubleValue()) * MatrixOps.dotProduct((double[])y.get(i), direction); MatrixOps.plusEquals(direction,(double[])s.get(i), alpha[i] - beta); } for (int i=0; i < oldg.length; i++) { oldParameters[i] = parameters[i]; oldg[i] = g[i]; direction[i] *= -1.0; } logger.fine ("before linesearch: direction.gradient.dotprod: "+ MatrixOps.dotProduct(direction,g)+"\ndirection.2norm: " + MatrixOps.twoNorm (direction) + "\nparameters.2norm: " + MatrixOps.twoNorm(parameters)); //TestMaximizable.testValueAndGradientInDirection (maxable, direction); step = lineMaximizer.optimize(direction, step); if (step == 0.0) { // could not step in this direction. g = null; // reset search step = 1.0; // xxx Temporary test; passed OK // TestMaximizable.testValueAndGradientInDirection (maxable, direction); throw new OptimizationException("Line search could not step in the current direction. " + "(This is not necessarily cause for alarm. Sometimes this happens close to the maximum," + " where the function may be very flat.)"); // return false; } optimizable.getParameters (parameters); optimizable.getValueGradient(g); logger.fine ("after linesearch: direction.2norm: " + MatrixOps.twoNorm (direction)); double newValue = optimizable.getValue(); // Test for terminations if(2.0*Math.abs(newValue-value) <= tolerance* (Math.abs(newValue)+Math.abs(value) + eps)){ logger.info("Exiting L-BFGS on termination #1:\nvalue difference below tolerance (oldValue: " + value + " newValue: " + newValue); converged = true; return true; } double gg = MatrixOps.twoNorm(g); if(gg < gradientTolerance) { logger.fine("Exiting L-BFGS on termination #2: \ngradient="+gg+" < "+gradientTolerance); converged = true; return true; } if(gg == 0.0) { logger.fine("Exiting L-BFGS on termination #3: \ngradient==0.0"); converged = true; return true; } logger.fine("Gradient = "+gg); iterations++; if (iterations > maxIterations) { System.err.println("Too many iterations in L-BFGS.java. Continuing with current parameters."); converged = true; return true; } //end of iteration. call evaluator if (eval != null && !eval.evaluate (optimizable, iterationCount)) { logger.fine ("Exiting L-BFGS on termination #4: evaluator returned false."); converged = true; return false; } } return false; } public void reset () { g = null; } /** * Pushes a new object onto the queue l * @param l linked list queue of Matrix obj's * @param toadd matrix to push onto queue */ private void push(LinkedList l, double[] toadd) { assert(l.size() <= m); if(l.size() == m) { // remove oldest matrix and add newset to end of list. // to make this more efficient, actually overwrite // memory of oldest matrix // this overwrites the oldest matrix double[] last = (double[]) l.get(0); System.arraycopy(toadd, 0, last, 0, toadd.length); Object ptr = last; // this readjusts the pointers in the list for(int i=0; i<l.size()-1; i++) l.set(i, (double[])l.get(i+1)); l.set(m-1, ptr); } else { double [] newArray = new double[toadd.length]; System.arraycopy (toadd, 0, newArray, 0, toadd.length); l.addLast(newArray); } } /** * Pushes a new object onto the queue l * @param l linked list queue of Double obj's * @param toadd double value to push onto queue */ private void push(LinkedList l, double toadd) { assert(l.size() <= m); if(l.size() == m) { //pop old double and add new l.removeFirst(); l.addLast(new Double(toadd)); } else l.addLast(new Double(toadd)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package battlecode.common; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; /** * * @author Sasa */ public class BuildMappings { private static final Map<ComponentType, Set<Chassis>> chassisMappings = new EnumMap<ComponentType, Set<Chassis>>(ComponentType.class); private static final Map<ComponentType, Set<ComponentType>> componentMappings = new EnumMap<ComponentType, Set<ComponentType>>(ComponentType.class); static { chassisMappings.put(ComponentType.RECYCLER, EnumSet.of(Chassis.LIGHT)); chassisMappings.put(ComponentType.CONSTRUCTOR, EnumSet.of(Chassis.BUILDING)); chassisMappings.put(ComponentType.ARMORY, EnumSet.of( Chassis.LIGHT, Chassis.MEDIUM, Chassis.FLYING)); chassisMappings.put(ComponentType.ARMORY, EnumSet.of( Chassis.LIGHT, Chassis.MEDIUM, Chassis.HEAVY)); chassisMappings.put(ComponentType.DUMMY, EnumSet.of(Chassis.DUMMY)); componentMappings.put(ComponentType.RECYCLER, EnumSet.of( ComponentType.SHIELD, ComponentType.PLATING, ComponentType.SMG, ComponentType.HAMMER, ComponentType.BLASTER, ComponentType.SIGHT, ComponentType.RADAR, ComponentType.ANTENNA, ComponentType.PROCESSOR, ComponentType.CONSTRUCTOR)); componentMappings.put(ComponentType.CONSTRUCTOR, EnumSet.of( ComponentType.RECYCLER, ComponentType.ARMORY, ComponentType.FACTORY)); componentMappings.put(ComponentType.FACTORY, EnumSet.of( ComponentType.HARDENED, ComponentType.REGEN, ComponentType.IRON, ComponentType.RAILGUN, ComponentType.MEDIC, ComponentType.TELESCOPE, ComponentType.DUMMY, ComponentType.DROPSHIP, ComponentType.DISH)); componentMappings.put(ComponentType.ARMORY, EnumSet.of( ComponentType.PLASMA, ComponentType.BEAM, ComponentType.SATELLITE, ComponentType.NETWORK, ComponentType.JUMP, ComponentType.BUG)); } public static boolean canBuild(ComponentType t, Chassis c) { if (chassisMappings.get(t).contains(c)) { return true; } return false; } public static boolean canBuild(ComponentType t, ComponentType c) { if (componentMappings.get(t).contains(c)) { return true; } return false; } }
package ch.ntb.inf.deep.config; public class Configuration { private static Project project; private static SystemConstants constants; private static MemoryMap memoryMap; private static RegisterMap registerMap; private static SysModules sysModules; private static RegInit regInit; private static OperatingSystem os; /** * Returns the first Segment which contains the code for the given * classname. If no such segment exists the method returns null. * * @param Class * the name of the desired Class * @return a Segment or null */ public static Segment getCodeSegmentOf(String Class) { return null; } /** * Returns the first Segment which contains the constants for the given * classname. If no such segment exists the method returns null. * * @param Class * the name of the desired Class * @return a Segment or null */ public static Segment getConstSegmentOf(String Class) { return null; } /** * Returns the first Segment which contains the variables for the given * classname. If no such segment exists the method returns null. * * @param Class * the name of the desired Class * @return a Segment or null */ public static Segment getVarSegmentOf(String Class) { return null; } }
package ch.pontius.nio.smb; import jcifs.smb.SmbFile; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.*; import java.util.*; public final class SMBPath implements Path { /** Reference to the {@link SMBFileSystem}. */ private final SMBFileSystem fileSystem; /** A list of path components that make up the current implementation of {@link SMBPath}. */ private String[] components; /** Flag indicating whether the current instance of {@link SMBPath} is an absolute path. */ private final boolean absolute; /** Flag indicating whether the current instance of {@link SMBPath} points to a folder. */ private final boolean folder; static SMBPath fromPath(Path path) { if (path instanceof SMBPath) { return (SMBPath)path; } else { throw new IllegalArgumentException("The provided path '" + path.toString() + "' is not an SMB path."); } } /** * Constructor for {@link SMBPath}. Creates a new, absolute path to a SMB resource from the provided URI. * * @param fileSystem {@link SMBFileSystem} object this {@link SMBPath} is associated with. * @param uri The URI pointing to the desired file or folder on the SMB file system. */ SMBPath(SMBFileSystem fileSystem, URI uri) { if (!uri.getScheme().equals(SMBFileSystem.SMB_SCHEME)) throw new IllegalArgumentException("The provided URI does not point to an SMB resource."); this.folder = SMBPathUtil.isFolder(uri.getPath()); this.absolute = SMBPathUtil.isAbsolutePath(uri.getPath()); this.components = SMBPathUtil.splitPath(uri.getPath()); this.fileSystem = fileSystem; } /** * Constructor for {@link SMBPath}. Constructs a new path to a SMB resource from the provided host and path string. * * @param fileSystem {@link SMBFileSystem} object this {@link SMBPath} is associated with. * @param path The path. It can either be relative or absolute. */ SMBPath(SMBFileSystem fileSystem, String path) { /* Make sure that path is absolute. */ this.absolute = SMBPathUtil.isAbsolutePath(path); this.folder = SMBPathUtil.isFolder(path); this.components = SMBPathUtil.splitPath(path); this.fileSystem = fileSystem; } /** * Getter for {@link SMBFileSystem} this {@link SMBPath} belongs to. * * @return {@link SMBFileSystem} */ @Override public final FileSystem getFileSystem() { return this.fileSystem; } /** * {@link SMBPath} is always absolute! * * @return true */ @Override public final boolean isAbsolute() { return this.absolute; } /** * Returns the root component of this {@link SMBPath} or null, if the path is relative. * * @return Root component of this {@link SMBPath */ @Override public Path getRoot() { if (this.absolute) { return new SMBPath(this.fileSystem, "/"); } else { return null; } } /** * Returns a new, relative {@link SMBPath} instance that just contains the last path component of the current {@link SMBPath}'s path. * * @return {@link SMBPath for the file name. */ @Override public Path getFileName() { return new SMBPath(this.fileSystem, this.components[this.components.length-1]); } /** * Returns a new {@link SMBPath} that points to the parent of the current {@link SMBPath}. If the current * {@link SMBPath} instance does not have a parent, this method returns null. * * @return Parent {@link SMBPath}. */ @Override public Path getParent() { if (this.components.length > 1) { String reduced = SMBPathUtil.mergePath(this.components, 0, this.components.length-1, this.absolute, true); return new SMBPath(this.fileSystem, reduced); } else { return null; } } /** * Returns the number of path components in the current {@link SMBPath}'s path. * * @return Number of path components. */ @Override public int getNameCount() { return this.components.length; } /** * Returns a name element of this {@link SMBPath} as a new {@link SMBPath} object. * * The index parameter is the index of the name element to return. The element that is closest to the root in the directory hierarchy has index 0. * The element that is farthest from the root has index count-1. * * @param index The index of the element * @return The name element. */ @Override public Path getName(int index) { if (index < 0 || index >= this.components.length) throw new IllegalArgumentException("The provided index is out of bounds."); String reduced = SMBPathUtil.mergePath(this.components, index, index, false, index == this.components.length - 1 && this.folder); return new SMBPath(this.fileSystem, reduced); } @Override public Path subpath(int beginIndex, int endIndex) { if (beginIndex < 0 || endIndex >= this.components.length) throw new IllegalArgumentException("The provided indices are out of bounds."); if (beginIndex > endIndex) throw new IllegalArgumentException("The beginIndex must be smaller than the endIndex."); String reduced = SMBPathUtil.mergePath(this.components, beginIndex, endIndex, false, endIndex == this.components.length - 1 && this.folder); return new SMBPath(this.fileSystem, reduced); } /** * Tests if this path starts with the given path. If the two paths belong to a different {@link FileSystem} then this * method always returns false. Otherwise, a string comparison is performed. * * @param other The given path * @return True if this path starts with the given path; otherwise false */ @Override public boolean startsWith(Path other) { return other.getFileSystem() == this.fileSystem && this.startsWith(other.toString()); } /** * Tests if this path starts with the provided string. The path separators will be taken into account. * * @param other The given path * @return True if this path starts with the given string; otherwise false */ @Override public boolean startsWith(String other) { String path = SMBPathUtil.mergePath(this.components, 0, this.components.length, this.absolute, this.folder); return path.startsWith(other); } /** * Tests if this path ends with the given path. If the two paths belong to a different {@link FileSystem} then this * method always returns false. Otherwise, a string comparison is performed. * * @param other The given path * @return True if this path starts with the given path; otherwise false */ @Override public boolean endsWith(Path other) { return other.getFileSystem() == this.fileSystem && this.endsWith(other.toString()); } /** * Tests if this path ends with the provided string. The path separators will be taken into account. * * @param other The given path * @return True if this path starts with the given string; otherwise false */ @Override public boolean endsWith(String other) { String path = SMBPathUtil.mergePath(this.components, 0, this.components.length, this.absolute, this.folder); return path.endsWith(other); } /** * Returns a path that is this path with redundant name elements, like "." or ".." eliminated. * * @return Normalized {@link SMBPath}. */ @Override public Path normalize() { final ArrayList<String> normalized = new ArrayList<>(); for (String component: this.components) { if (component.equals(".")) { continue; } else if (component.equals("..") && normalized.size() > 0) { normalized.remove(normalized.size()-1); } else if (component.equals("..") && normalized.size() == 0) { continue; } else { normalized.add(component); } } String path = SMBPathUtil.mergePath(normalized.toArray(new String[normalized.size()]), 0, this.components.length, this.absolute, this.folder); return new SMBPath(this.fileSystem, path); } @Override public Path resolve(Path other) { /* Check if other path is on the same filesystem. */ if (!(other instanceof SMBPath)) throw new IllegalArgumentException("You can only resolve an SMB path against another SMB path."); if (((SMBPath)other).fileSystem != this.fileSystem) throw new IllegalArgumentException("You can only resolve an SMB path against another SMB path on the same file system."); /* Check if current path is a folder (Important!). */ if (!this.isFolder()) throw new IllegalArgumentException("The current path appears to be a file. You cannot resolve another path against a file path. Either add a trailing '/' to indicate that this is a folder or use resolveSibling() instead."); /* If other is absolute, return other else resolve. */ if (other.isAbsolute()) { return other; } else { String[] components = new String[other.getNameCount() + this.getNameCount()]; System.arraycopy(this.components, 0, components, 0, this.getNameCount()); System.arraycopy(((SMBPath)other).components, 0, components, this.getNameCount(), other.getNameCount()); String path = SMBPathUtil.mergePath(components, 0, components.length, this.absolute, ((SMBPath) other).folder); return new SMBPath(this.fileSystem, path); } } @Override public Path resolve(String other) { /* Check if current path is a folder (Important!). */ if (!this.isFolder()) throw new IllegalArgumentException("The current path appears to be a file. You cannot resolve another path against a file path. Either add a trailing '/' to indicate that this is a folder or use resolveSibling() instead."); if (SMBPathUtil.isAbsolutePath(other)) { return new SMBPath(this.fileSystem, other); } else { String[] split = SMBPathUtil.splitPath(other); String[] components = new String[split.length + this.components.length]; System.arraycopy(this.components, 0, components, 0, this.components.length); System.arraycopy(split, 0, components, this.components.length, split.length); String path = SMBPathUtil.mergePath(components, 0, components.length, this.absolute, SMBPathUtil.isFolder(other)); return new SMBPath(this.fileSystem, path); } } @Override public Path resolveSibling(Path other) { /* Check if other path is on the same filesystem. */ if (!(other instanceof SMBPath)) throw new IllegalArgumentException("You can only resolve an SMB path against another SMB path."); if (((SMBPath)other).fileSystem != this.fileSystem) throw new IllegalArgumentException("You can only resolve an SMB path against another SMB path on the same file system."); if (other.isAbsolute()) { return other; } else { String[] components = new String[other.getNameCount() + this.getNameCount() - 1]; System.arraycopy(this.components, 0, components, 0, this.components.length-1); System.arraycopy(((SMBPath)other).components, 0, components, this.components.length-1, ((SMBPath) other).components.length); String path = SMBPathUtil.mergePath(components, 0, components.length, this.absolute, ((SMBPath) other).folder); return new SMBPath(this.fileSystem, path); } } @Override public Path resolveSibling(String other) { /* Check if current path is a folder (Important!). */ if (!this.isFolder()) throw new IllegalArgumentException("The current path appears to be a file. You cannot resolve another path against a file path. Either add a trailing '/' to indicate that this is a folder or use resolveSibling() instead."); if (SMBPathUtil.isAbsolutePath(other)) { return new SMBPath(this.fileSystem, other); } else { String[] split = SMBPathUtil.splitPath(other); String[] components = new String[split.length + this.components.length - 1]; System.arraycopy(this.components, 0, components, 0, this.components.length - 1); System.arraycopy(split, 0, components, this.components.length - 1, split.length); String path = SMBPathUtil.mergePath(components, 0, components.length, this.absolute, SMBPathUtil.isFolder(other)); return new SMBPath(this.fileSystem, path); } } @Override public Path relativize(Path other) { /* TODO. */ return null; } /** * Returns a URI to represent this {@link SMBPath}. * * @return The URI representing this path */ @Override public URI toUri() { String path = SMBPathUtil.mergePath(this.components, 0, this.components.length, this.absolute, this.folder); try { return new URI(SMBFileSystem.SMB_SCHEME, this.fileSystem.getName(), path, null, null); } catch (URISyntaxException e) { throw new IllegalStateException("The current instance of SMBPath '" + this.toString() + "' cannot be transformed to a valid URI."); } } /** * If this {@link SMBPath} is absolute then the method returns this. Otherwise, the given path is resolved against the top-level directory. * * @return Absolute {@link SMBPath} */ @Override public Path toAbsolutePath() { if (this.isAbsolute()) { return this; } else { return new SMBPath(this.fileSystem, "/").resolve(this); } } /** * Returns an iterator over the name elements of this {@link SMBPath}. * * The first element returned by the iterator represents the name element that is closest to the root in the directory hierarchy, the second element is the next closest, * and so on. The last element returned is the name of the file or directory denoted by this path. The root component, if present, is not returned by the iterator. * * @return An iterator over the name elements of this path. */ @Override public Iterator<Path> iterator() { return Arrays.stream(this.components).map(s -> (Path)new SMBPath(this.fileSystem, s)).iterator(); } /** * Compares two abstract paths lexicographically. This method does not access the file system and neither file is required to exist. * * @param other The path compared to this {@link SMBPath}. * @return Zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument */ @Override public int compareTo(Path other) { /* Check if other path is on the same filesystem. */ if (!(other instanceof SMBPath)) throw new IllegalArgumentException("You can only resolve an SMB path against another SMB path."); if (((SMBPath)other).fileSystem != this.fileSystem) throw new IllegalArgumentException("You can only resolve an SMB path against another SMB path on the same file system."); String thisPath = SMBPathUtil.mergePath(this.components, 0, this.components.length, this.absolute, this.folder); String thatPath = SMBPathUtil.mergePath(((SMBPath)other).components, 0, this.components.length, ((SMBPath)other).absolute, ((SMBPath)other).folder); return thisPath.compareTo(thatPath); } /** * Default toString() method. * * @return String representation of {@link SMBPath}. */ public String toString() { return SMBPathUtil.mergePath(this.components, 0, this.components.length, this.absolute, this.folder); } /** * Creates a new {@link SmbFile} associated with this {@link SMBPath} and returns it. * * @return {@link SmbFile} */ SmbFile getSmbFile() throws IOException { if (!this.fileSystem.isOpen()) throw new ClosedFileSystemException(); String path = SMBPathUtil.mergePath(this.components, 0, this.components.length, this.absolute, this.folder); return new SmbFile(this.fileSystem.getFQN() + SMBFileSystem.PATH_SEPARATOR + this.fileSystem.getName(), path); } /** * Tests this path for equality with the given object. If the given object is not a {@link SMBPath}, or is a {@link SMBPath} associated with a * different {@link SMBFileSystem}, then this method returns false. * * @param other The object to which this object is to be compared * @return If, and only if, the given object is a {@link SMBPath} that is identical to this {@link SMBPath}. */ public boolean equals(Object other) { if (!(other instanceof SMBPath)) return false; if (((SMBPath)other).fileSystem != this.fileSystem) return false; return Arrays.equals(this.components, ((SMBPath) other).components); } /** * Checks whether the current {@link SMBPath} is a folder. * * @return True if current {@link SMBPath} is a folder. */ public boolean isFolder() { return this.folder; } @Override public File toFile() { throw new UnsupportedOperationException("It is not possible to construct a file from a SMB path."); } @Override public Path toRealPath(LinkOption... options) throws IOException { throw new UnsupportedOperationException("Symbolic links are currently not supported by SMB paths."); } @Override public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException { throw new UnsupportedOperationException("FileWatchers are currently not supported by SMB paths."); } @Override public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException { throw new UnsupportedOperationException("FileWatchers are currently not supported by SMB paths."); } }
package com.blade.mvc.http; import com.blade.kit.StringKit; import com.blade.kit.WebKit; import com.blade.mvc.WebContext; import com.blade.mvc.multipart.FileItem; import com.blade.mvc.route.Route; import com.blade.server.netty.HttpConst; import io.netty.buffer.ByteBuf; import lombok.NonNull; import java.util.List; import java.util.Map; import java.util.Optional; import static com.blade.kit.WebKit.UNKNOWN_MAGIC; /** * Http Request * * @author biezhi * 2017/5/31 */ public interface Request { /** * init request path parameters * * @param route route object * @return Return request */ Request initPathParams(Route route); /** * Get client host. * * @return Return client request host */ String host(); /** * Get client remote address. e.g: 102.331.234.11:38227 * * @return Return client ip and port */ String remoteAddress(); /** * Get request uri * * @return Return request uri */ String uri(); /** * Get request url * * @return request url */ String url(); /** * Get request user-agent * * @return return user-agent */ default String userAgent() { return header(HttpConst.USER_AGENT); } /** * Get request http protocol * * @return Return protocol */ String protocol(); /** * Get current application contextPath, default is "/" * * @return Return contextPath */ default String contextPath() { return WebContext.contextPath(); } /** * Get current request Path params, like /users/:uid * * @return Return parameters on the path Map */ Map<String, String> pathParams(); /** * Get a URL parameter * * @param name Parameter name * @return Return parameter value */ default String pathString(@NonNull String name) { return pathParams().get(name); } /** * Return a URL parameter for a Int type * * @param name Parameter name * @return Return Int parameter value */ default Integer pathInt(@NonNull String name) { String val = pathString(name); return StringKit.isNotBlank(val) ? Integer.parseInt(val) : null; } /** * Return a URL parameter for a Long type * * @param name Parameter name * @return Return Long parameter value */ default Long pathLong(@NonNull String name) { String val = pathString(name); return StringKit.isNotBlank(val) ? Long.parseLong(val) : null; } String queryString(); /** * Get current request query parameters * * @return Return request query Map */ Map<String, List<String>> parameters(); /** * Get a request parameter * * @param name Parameter name * @return Return request parameter value */ default Optional<String> query(@NonNull String name) { List<String> values = parameters().get(name); if (null != values && values.size() > 0) return Optional.of(values.get(0)); return Optional.empty(); } /** * Get a request parameter, if NULL is returned to defaultValue * * @param name parameter name * @param defaultValue default String value * @return Return request parameter values */ default String query(@NonNull String name, @NonNull String defaultValue) { Optional<String> value = query(name); if (value.isPresent()) return value.get(); return defaultValue; } /** * Returns a request parameter for a Int type * * @param name Parameter name * @return Return Int parameter values */ default Optional<Integer> queryInt(@NonNull String name) { Optional<String> value = query(name); if (value.isPresent()) return Optional.of(Integer.parseInt(value.get())); return Optional.empty(); } /** * Returns a request parameter for a Int type * * @param name Parameter name * @param defaultValue default int value * @return Return Int parameter values */ default int queryInt(@NonNull String name, int defaultValue) { Optional<String> value = query(name); if (value.isPresent()) return Integer.parseInt(value.get()); return defaultValue; } /** * Returns a request parameter for a Long type * * @param name Parameter name * @return Return Long parameter values */ default Optional<Long> queryLong(@NonNull String name) { Optional<String> value = query(name); if (value.isPresent()) return Optional.of(Long.parseLong(value.get())); return Optional.empty(); } /** * Returns a request parameter for a Long type * * @param name Parameter name * @param defaultValue default long value * @return Return Long parameter values */ default long queryLong(@NonNull String name, long defaultValue) { Optional<String> value = query(name); if (value.isPresent()) return Long.parseLong(value.get()); return defaultValue; } /** * Returns a request parameter for a Double type * * @param name Parameter name * @return Return Double parameter values */ default Optional<Double> queryDouble(@NonNull String name) { Optional<String> value = query(name); if (value.isPresent()) return Optional.of(Double.parseDouble(value.get())); return Optional.empty(); } /** * Returns a request parameter for a Double type * * @param name Parameter name * @param defaultValue default double value * @return Return Double parameter values */ default double queryDouble(@NonNull String name, double defaultValue) { Optional<String> value = query(name); if (value.isPresent()) return Double.parseDouble(value.get()); return defaultValue; } /** * Get current request http method. e.g: GET * * @return Return request method */ String method(); /** * Get current request HttpMethod. e.g: HttpMethod.GET * * @return Return HttpMethod */ HttpMethod httpMethod(); /** * Get client ip address * * @return Return server remote address */ default String address() { String address = WebKit.ipAddress(this); if (StringKit.isBlank(address) || UNKNOWN_MAGIC.equalsIgnoreCase(address)) { address = remoteAddress().split(":")[0].substring(1); } if (StringKit.isBlank(address)) { address = "Unknown"; } return address; } /** * Get current request session, if null then create * * @return Return current session */ Session session(); /** * Get current request contentType. e.g: "text/html; charset=utf-8" * * @return Return contentType */ default String contentType() { String contentType = header(HttpConst.CONTENT_TYPE_STRING); return null != contentType ? contentType : "Unknown"; } /** * Get current request is https. * * @return Return whether to use the SSL connection */ boolean isSecure(); /** * Get current request is ajax. According to the header "x-requested-with" * * @return Return current request is a AJAX request */ default boolean isAjax() { return "XMLHttpRequest".equals(header("x-requested-with")); } /** * Gets the current request is the head of the IE browser * * @return return current request is IE browser */ default boolean isIE() { String ua = userAgent(); return ua.contains("MSIE") || ua.contains("TRIDENT"); } /** * Get current request cookies * * @return return cookies */ Map<String, Cookie> cookies(); /** * Get String Cookie Value * * @param name cookie name * @return Return Cookie Value */ default String cookie(@NonNull String name) { Cookie cookie = cookies().get(name); return null != cookie ? cookie.value() : null; } /** * Get raw cookie by cookie name * * @param name cookie name * @return return Optional<Cookie> */ Cookie cookieRaw(String name); /** * Get String Cookie Value * * @param name cookie name * @param defaultValue default cookie value * @return Return Cookie Value */ default String cookie(@NonNull String name, @NonNull String defaultValue) { String cookie = cookie(name); return null != cookie ? cookie : defaultValue; } /** * Add a cookie to the request * * @param cookie * @return return Request instance */ Request cookie(Cookie cookie); /** * Get current request headers. * * @return Return header information Map */ Map<String, String> headers(); /** * Get header information * * @param name Parameter name * @return Return header information */ default String header(@NonNull String name) { String header = headers().getOrDefault(name, ""); return StringKit.isBlank(header) ? headers().getOrDefault(name.toLowerCase(), "") : header; } /** * Get header information * * @param name Parameter name * @param defaultValue default header value * @return Return header information */ default String header(@NonNull String name, @NonNull String defaultValue) { String value = header(name); return value.length() > 0 ? value : defaultValue; } /** * Get current request is KeepAlive, HTTP1.1 is true. * * @return return current request connection keepAlive */ boolean keepAlive(); /** * Get current request attributes * * @return Return all Attribute in Request */ Map<String, Object> attributes(); /** * Setting Request Attribute * * @param name Parameter name * @param value Parameter Value * @return set attribute value and return current request instance */ default Request attribute(@NonNull String name, Object value) { if (null != value) attributes().put(name, value); return this; } /** * Get a Request Attribute * * @param name Parameter name * @return Return parameter value */ default <T> T attribute(String name) { if (null == name) return null; Object object = attributes().get(name); return null != object ? (T) object : null; } /** * Get current request all fileItems * * @return return request file items */ Map<String, FileItem> fileItems(); /** * get file item by request part name * * @param name * @return return Optional<FileItem> */ default Optional<FileItem> fileItem(@NonNull String name) { return Optional.ofNullable(fileItems().get(name)); } /** * Get current request body as ByteBuf * * @return Return request body */ ByteBuf body(); /** * Get current request body as string * * @return return request body to string */ String bodyToString(); }
package com.chbi.rest; import com.chbi.json.entities.*; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.Map; import java.util.Set; /* * TODO: if there is an error like 404 because jenkins is unavailable, * exceptions should be catched... */ @Service public class DataProvider { private static final String UNKNOWN_USER = "Luke Buildwalker"; @Autowired private RequestManager requestManager; @Autowired private UrlRewriter urlRewriter; public List<JenkinsJob> getJenkinsJobs() { RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> request = requestManager.getJsonHttpEntity(); String url = urlRewriter.getPreparedBaseUrl(); ResponseEntity<JenkinsView> response = restTemplate.exchange(url, HttpMethod.GET, request, JenkinsView.class); JenkinsView jenkinsView = response.getBody(); return jenkinsView.getJobs(); } public List<JenkinsBuildPipeline> getBuildsFor(JenkinsJob jenkinsJob) { return Lists.newArrayList(); } public JenkinsBuildPipeline getJenkinsBuildPipeline(JenkinsJob jenkinsJob) { RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> request = requestManager.getJsonHttpEntity(); String url = urlRewriter.prepareUrl(jenkinsJob.getUrl()) + "?tree=displayName,lastBuild[number,url]"; ResponseEntity<JenkinsBuildPipeline> response = restTemplate.exchange(url, HttpMethod.GET, request, JenkinsBuildPipeline.class); JenkinsBuildPipeline pipeline = response.getBody(); //lastbuild is null, if buildPipeline was never executed if (pipeline.getLastBuild() == null) { pipeline.setLastBuild(new JenkinsBuild()); pipeline.getLastBuild().setNumber(-1); pipeline.getLastBuild().setUrl(jenkinsJob.getUrl()); pipeline.getLastBuild().set_class("never built"); } return pipeline; } public JenkinsBuildInstance getBuildInstance(String lastBuildUrl) { RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> request = requestManager.getJsonHttpEntity(); String url = urlRewriter.prepareUrl(lastBuildUrl) + "?tree=fullDisplayName,culprits[fullName,absoluteUrl],changeSets[items[*]]"; ResponseEntity<JenkinsBuildInstance> response = restTemplate.exchange(url, HttpMethod.GET, request, JenkinsBuildInstance.class); return response.getBody(); } public String getChangingUserFor(JenkinsBuildInstance buildInstance) { String users; if (buildInstance.getCulprits() != null && buildInstance.getCulprits().size() > 0) { users = Joiner.on(", ").join(buildInstance.getCulprits()); } else if (buildInstance.getChangeSets() != null) { users = Joiner.on(", ").join(getAuthorsFromChangeSet(buildInstance.getChangeSets())); } else { users = UNKNOWN_USER; } return users; } private List<JenkinsAuthor> getAuthorsFromChangeSet(List<JenkinsChangeSets> changeSets) { Set<JenkinsAuthor> authors = Sets.newHashSet(); changeSets.forEach(jenkinsChangeSets -> jenkinsChangeSets.getItems() .stream().filter(stringObjectMap -> stringObjectMap.containsKey("author")) .forEach(filteredObject -> authors.add(new JenkinsAuthor((Map) filteredObject.get("author"))))); return Lists.newArrayList(authors.iterator()); } public static String getUnknownUser() { return UNKNOWN_USER; } }
package com.crowdin.client; import com.crowdin.client.core.http.exceptions.HttpBadRequestException; import com.crowdin.client.core.http.exceptions.HttpException; import com.crowdin.client.core.model.ClientConfig; import com.crowdin.client.core.model.Credentials; import com.crowdin.client.core.model.DownloadLink; import com.crowdin.client.core.model.ResponseList; import com.crowdin.client.core.model.ResponseObject; import com.crowdin.client.sourcefiles.model.AddBranchRequest; import com.crowdin.client.sourcefiles.model.AddFileRequest; import com.crowdin.client.sourcefiles.model.Branch; import com.crowdin.client.sourcefiles.model.GeneralFileExportOptions; import com.crowdin.client.sourcefiles.model.UpdateFileRequest; import com.crowdin.client.storage.model.Storage; import com.crowdin.client.translations.model.CrowdinTranslationCreateProjectBuildForm; import com.crowdin.client.translations.model.ProjectBuild; import com.crowdin.util.NotificationUtil; import com.crowdin.util.RetryUtil; import com.intellij.ide.plugins.PluginManager; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class Crowdin { private static final String PLUGIN_ID = "com.crowdin.crowdin-idea"; private final Long projectId; private final boolean invalidConfiguration; private final com.crowdin.client.Client client; public Crowdin(@NotNull Project project) { CrowdinClientProperties crowdinClientProperties = CrowdinClientProperties.load(project); if (crowdinClientProperties.getErrorMessage() != null) { this.projectId = null; this.client = null; this.invalidConfiguration = true; NotificationUtil.showErrorMessage(crowdinClientProperties.getErrorMessage()); } else { this.invalidConfiguration = false; this.projectId = crowdinClientProperties.getProjectId(); Credentials credentials = new Credentials(crowdinClientProperties.getToken(), null, crowdinClientProperties.getBaseUrl()); ClientConfig clientConfig = ClientConfig.builder() .userAgent("crowdin-android-studio-plugin/ " + PluginManager.getPlugin(PluginId.getId(PLUGIN_ID)).getVersion() + " android-studio/" + PluginManager.getPlugin(PluginId.getId(PluginManager.CORE_PLUGIN_ID)).getVersion()) .build(); this.client = new Client(credentials, clientConfig); } } public void uploadFile(VirtualFile source, String branch) { if (source == null || this.invalidConfiguration) { return; } try { Long branchId = this.getOrCreateBranch(branch); ResponseObject<Storage> storageResponseObject = this.client.getStorageApi().addStorage(source.getName(), source.getInputStream()); Long storageId = storageResponseObject.getData().getId(); ResponseList<com.crowdin.client.sourcefiles.model.File> fileResponseList = this.client.getSourceFilesApi().listFiles(this.projectId, branchId, null, null, 500, null); ResponseObject<com.crowdin.client.sourcefiles.model.File> foundFile = fileResponseList.getData().stream() .filter(f -> { if (branchId != null) { return f.getData().getBranchId().equals(branchId); } else { return f.getData().getBranchId() == null; } }) .filter(f -> f.getData().getName().equals(source.getName())) .findFirst().orElse(null); if (foundFile != null) { UpdateFileRequest request = new UpdateFileRequest(); request.setStorageId(storageId); GeneralFileExportOptions generalFileExportOptions = new GeneralFileExportOptions(); generalFileExportOptions.setExportPattern("/values-%android_code%/%original_file_name%"); this.client.getSourceFilesApi().updateOrRestoreFile(this.projectId, foundFile.getData().getId(), request); NotificationUtil.showInformationMessage("File '" + source.getName() + "' updated in Crowdin"); } else { AddFileRequest request = new AddFileRequest(); request.setStorageId(storageId); request.setName(source.getName()); request.setBranchId(branchId); GeneralFileExportOptions generalFileExportOptions = new GeneralFileExportOptions(); generalFileExportOptions.setExportPattern("/values-%android_code%/%original_file_name%"); request.setExportOptions(generalFileExportOptions); this.client.getSourceFilesApi().addFile(this.projectId, request); NotificationUtil.showInformationMessage("File '" + source.getName() + "' added to Crowdin"); } } catch (Exception e) { NotificationUtil.showErrorMessage(this.getErrorMessage(e)); } } public File downloadTranslations(VirtualFile sourceFile, String branch) { if (this.invalidConfiguration) { return null; } try { Long branchId = null; if (branch != null && branch.length() > 0) { Optional<Branch> foundBranch = this.getBranch(branch); if (!foundBranch.isPresent()) { NotificationUtil.showWarningMessage("Branch " + branch + " does not exists in Crowdin"); return null; } branchId = foundBranch.get().getId(); } CrowdinTranslationCreateProjectBuildForm buildProjectTranslationRequest = new CrowdinTranslationCreateProjectBuildForm(); buildProjectTranslationRequest.setBranchId(branchId); ResponseObject<ProjectBuild> projectBuildResponseObject = this.client.getTranslationsApi().buildProjectTranslation(this.projectId, buildProjectTranslationRequest); Long buildId = projectBuildResponseObject.getData().getId(); boolean finished = false; while (!finished) { ResponseObject<ProjectBuild> projectBuildStatusResponseObject = this.client.getTranslationsApi().checkBuildStatus(this.projectId, buildId); finished = projectBuildStatusResponseObject.getData().getStatus().equalsIgnoreCase("finished"); } ResponseObject<DownloadLink> downloadLinkResponseObject = this.client.getTranslationsApi().downloadProjectTranslations(this.projectId, buildId); String link = downloadLinkResponseObject.getData().getUrl(); File file = new File(sourceFile.getParent().getParent().getCanonicalPath() + "/all.zip"); try (ReadableByteChannel readableByteChannel = Channels.newChannel(new URL(link).openStream()); FileOutputStream fos = new FileOutputStream(file)) { fos.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); } return file; } catch (Exception e) { NotificationUtil.showErrorMessage(this.getErrorMessage(e)); return null; } } private Long getOrCreateBranch(String name) { if (name != null && name.length() > 0) { try { Branch foundBranch = this.getBranch(name).orElse(null); if (foundBranch != null) { return foundBranch.getId(); } else { AddBranchRequest request = new AddBranchRequest(); request.setName(name); ResponseObject<Branch> responseObject = this.client.getSourceFilesApi().addBranch(this.projectId, request); return responseObject.getData().getId(); } } catch (Exception e) { try { if (!this.concurrentIssue(e)) { throw e; } return this.waitAndFindBranch(name); } catch (Exception error) { if (this.customMessage(error)) { throw new RuntimeException(this.getErrorMessage(error)); } String msg = "Failed to create/find branch for project " + this.projectId + ". " + this.getErrorMessage(error); throw new RuntimeException(msg); } } } return null; } private Optional<Branch> getBranch(String name) { List<ResponseObject<Branch>> branches = this.client.getSourceFilesApi().listBranches(this.projectId, name, 500, null).getData(); return branches.stream() .filter(e -> e.getData().getName().equalsIgnoreCase(name)) .map(ResponseObject::getData) .findFirst(); } private String getErrorMessage(Exception e) { if (e instanceof HttpException) { HttpException ex = (HttpException) e; if (ex.getError().getCode().equalsIgnoreCase("401")) { return "Unable to authorize. Please, use another Personal Access Token and try again."; } else { return ex.getError().getMessage(); } } else if (e instanceof HttpBadRequestException) { return ((HttpBadRequestException) e).getErrors().stream() .map(er -> { String key = er.getError().getKey() == null ? "" : er.getError().getKey(); return key + " " + er.getError().getErrors().stream() .map(err -> err.getCode() + " " + err.getMessage()) .collect(Collectors.joining(";")); }) .collect(Collectors.joining(";")); } else { return e.getMessage(); } } private boolean concurrentIssue(Exception error) { return this.codeExists(error, "notUnique") || this.codeExists(error, "parallelCreation"); } private boolean codeExists(Exception e, String code) { if (e instanceof HttpException) { return ((HttpException) e).getError().getCode().equalsIgnoreCase(code); } else if (e instanceof HttpBadRequestException) { return ((HttpBadRequestException) e).getErrors().stream() .anyMatch(error -> error.getError().getErrors().stream() .anyMatch(er -> er.getCode().equalsIgnoreCase(code)) ); } else { return false; } } private Long waitAndFindBranch(String name) throws Exception { return RetryUtil.retry(() -> { ResponseList<Branch> branchResponseList = this.client.getSourceFilesApi().listBranches(this.projectId, name, 500, null); ResponseObject<Branch> branchResponseObject = branchResponseList.getData().stream() .filter(branch -> branch.getData().getName().equalsIgnoreCase(name)) .findFirst().orElse(null); if (branchResponseObject != null) { return branchResponseObject.getData().getId(); } else { throw new Exception("Could not find branch " + name + "in Crowdin response"); } }); } private boolean customMessage(Exception e) { if (e instanceof HttpException) { HttpException ex = (HttpException) e; if (ex.getError().getCode().equalsIgnoreCase("401")) { return true; } } return false; } }
package com.fluxchess.pulse; import com.fluxchess.jcpi.commands.IProtocol; import com.fluxchess.jcpi.commands.ProtocolBestMoveCommand; import com.fluxchess.jcpi.models.GenericMove; import com.fluxchess.jcpi.models.IntColor; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Semaphore; /** * This class implements our Alpha-beta search in a separate thread. */ public final class Search implements Runnable { private static final int MAX_HEIGHT = 256; private static final int MAX_DEPTH = 64; private final Thread thread = new Thread(this); private final Semaphore semaphore = new Semaphore(0); private final IProtocol protocol; private final Board board; private final MoveGenerator moveGenerator; private final Evaluation evaluation = new Evaluation(); // Depth search private int searchDepth = MAX_DEPTH; // Nodes search private long searchNodes = Long.MAX_VALUE; private long totalNodes = 0; // Time & Clock & Ponder search private long searchTime = 0; private Timer timer = null; private boolean timerStopped = false; // Moves search private final MoveList searchMoves = new MoveList(); // Search parameters private final MoveList rootMoves = new MoveList(); private Result bestResult = new Result(); private int ponderMove = Move.NOMOVE; private boolean abort = false; /** * This is our search timer for time & clock & ponder searches. */ private final class SearchTimer extends TimerTask { @Override public void run() { timerStopped = true; // If we already have a result abort the search. if (bestResult.move != Move.NOMOVE) { abort = true; } } } private final class Result { public int move = Move.NOMOVE; public int ponderMove = Move.NOMOVE; public int value = -Evaluation.INFINITY; } public static Search newDepthSearch(Board board, IProtocol protocol, int searchDepth) { if (board == null) throw new IllegalArgumentException(); if (protocol == null) throw new IllegalArgumentException(); if (searchDepth < 1 || searchDepth > MAX_DEPTH) throw new IllegalArgumentException(); Search search = new Search(board, protocol); search.searchDepth = searchDepth; return search; } public static Search newNodesSearch(Board board, IProtocol protocol, long searchNodes) { if (board == null) throw new IllegalArgumentException(); if (protocol == null) throw new IllegalArgumentException(); if (searchNodes < 1) throw new IllegalArgumentException(); Search search = new Search(board, protocol); search.searchNodes = searchNodes; return search; } public static Search newTimeSearch(Board board, IProtocol protocol, long searchTime) { if (board == null) throw new IllegalArgumentException(); if (protocol == null) throw new IllegalArgumentException(); if (searchTime < 1) throw new IllegalArgumentException(); Search search = new Search(board, protocol); search.searchTime = searchTime; search.timer = new Timer(true); return search; } public static Search newMovesSearch(Board board, IProtocol protocol, List<GenericMove> searchMoves) { if (board == null) throw new IllegalArgumentException(); if (protocol == null) throw new IllegalArgumentException(); if (searchMoves == null) throw new IllegalArgumentException(); Search search = new Search(board, protocol); for (GenericMove move : searchMoves) { search.searchMoves.moves[search.searchMoves.size++] = Move.valueOf(move, board); } return search; } public static Search newInfiniteSearch(Board board, IProtocol protocol) { if (board == null) throw new IllegalArgumentException(); if (protocol == null) throw new IllegalArgumentException(); return new Search(board, protocol); } public static Search newClockSearch(Board board, IProtocol protocol, long whiteTimeLeft, long whiteTimeIncrement, long blackTimeLeft, long blackTimeIncrement, int movesToGo) { Search search = newPonderSearch(board, protocol, whiteTimeLeft, whiteTimeIncrement, blackTimeLeft, blackTimeIncrement, movesToGo); search.timer = new Timer(true); return search; } public static Search newPonderSearch(Board board, IProtocol protocol, long whiteTimeLeft, long whiteTimeIncrement, long blackTimeLeft, long blackTimeIncrement, int movesToGo) { if (board == null) throw new IllegalArgumentException(); if (protocol == null) throw new IllegalArgumentException(); if (whiteTimeLeft < 1) throw new IllegalArgumentException(); if (whiteTimeIncrement < 0) throw new IllegalArgumentException(); if (blackTimeLeft < 1) throw new IllegalArgumentException(); if (blackTimeIncrement < 0) throw new IllegalArgumentException(); if (movesToGo < 0) throw new IllegalArgumentException(); Search search = new Search(board, protocol); long timeLeft; long timeIncrement; if (board.activeColor == IntColor.WHITE) { timeLeft = whiteTimeLeft; timeIncrement = whiteTimeIncrement; } else { timeLeft = blackTimeLeft; timeIncrement = blackTimeIncrement; } // Don't use all of our time. Search only for 95%. Always leave 1 second as // buffer time. long maxSearchTime = (long) (timeLeft * 0.95) - 1000L; if (maxSearchTime < 1) { // We don't have enough time left. Search only for 1 millisecond, meaning // get a result as fast as we can. maxSearchTime = 1; } // Assume that we still have to do movesToGo number of moves. For every next // move (movesToGo - 1) we will receive a time increment. search.searchTime = (maxSearchTime + (movesToGo - 1) * timeIncrement) / movesToGo; if (search.searchTime > maxSearchTime) { search.searchTime = maxSearchTime; } return search; } private Search(Board board, IProtocol protocol) { assert board != null; assert protocol != null; this.board = board; this.protocol = protocol; moveGenerator = new MoveGenerator(board); } public void start() { if (!thread.isAlive()) { thread.start(); try { // Wait for initialization semaphore.acquire(); } catch (InterruptedException e) { // Do nothing } } } public void stop() { if (thread.isAlive()) { abort = true; try { // Wait for the thread to die thread.join(); } catch (InterruptedException e) { // Do nothing } } } public void ponderhit() { if (thread.isAlive()) { // Enable time management timer = new Timer(true); timer.schedule(new SearchTimer(), searchTime); checkStopConditions(); } } public void run() { if (timer != null) { timer.schedule(new SearchTimer(), searchTime); } if (searchMoves.size == 0) { MoveList tempMoves = moveGenerator.getAll(); for (int i = 0; i < tempMoves.size; ++i) { rootMoves.moves[rootMoves.size++] = tempMoves.moves[i]; } } else { for (int i = 0; i < searchMoves.size; ++i) { rootMoves.moves[rootMoves.size++] = searchMoves.moves[i]; } } semaphore.release(); //### BEGIN Iterative Deepening for (int currentDepth = 1; currentDepth <= searchDepth; ++currentDepth) { Result currentResult = alphaBetaRoot(currentDepth, -Evaluation.CHECKMATE, Evaluation.CHECKMATE, 0); if (currentResult.move != Move.NOMOVE) { // Update the best result. bestResult = currentResult; checkStopConditions(); if (abort) { break; } } else { // We found no best move. // Perhaps we have a checkmate or we got a stop request? break; } } //### ENDOF Iterative Deepening if (timer != null) { timer.cancel(); } if (bestResult.move != Move.NOMOVE) { if (bestResult.ponderMove != Move.NOMOVE) { protocol.send(new ProtocolBestMoveCommand(Move.toGenericMove(bestResult.move), Move.toGenericMove(bestResult.ponderMove))); } else { protocol.send(new ProtocolBestMoveCommand(Move.toGenericMove(bestResult.move), null)); } } else { protocol.send(new ProtocolBestMoveCommand(null, null)); } } private void checkStopConditions() { // We will check the stop conditions only if we are using time management, // that is if our timer != null. Also we cannot stop the search if we don't // have any result if using time management. if (bestResult.move != Move.NOMOVE && timer != null) { if (timerStopped) { abort = true; } else { // Check if we have only one move to make if (rootMoves.size == 1) { abort = true; } // Check if we have a checkmate else if (Math.abs(bestResult.value) == Evaluation.CHECKMATE) { abort = true; } } } } private void updateSearch() { ++totalNodes; if (searchNodes <= totalNodes) { // Hard stop on number of nodes abort = true; } } private Result alphaBetaRoot(int depth, int alpha, int beta, int height) { Result result = new Result(); updateSearch(); // Abort conditions if (abort) { return result; } for (int i = 0; i < rootMoves.size; ++i) { int move = rootMoves.moves[i]; ponderMove = Move.NOMOVE; board.makeMove(move); int value = -alphaBeta(depth - 1, -beta, -alpha, height + 1); board.undoMove(move); if (abort) { break; } // Pruning if (value > result.value) { result.value = value; result.move = move; result.ponderMove = ponderMove; // Do we have a better value? if (value > alpha) { alpha = value; // Is the value higher than beta? if (value >= beta) { // Cut-off break; } } } } return result; } private int alphaBeta(int depth, int alpha, int beta, int height) { // We are at a leaf/horizon. So calculate that value. if (depth <= 0) { return evaluation.evaluate(board); } updateSearch(); // Abort conditions if (abort || height == MAX_HEIGHT) { return evaluation.evaluate(board); } // Check the repetition table and fifty move rule if (board.isRepetition() || board.halfMoveClock >= 100) { return Evaluation.DRAW; } // Initialize int bestValue = -Evaluation.INFINITY; int bestMove = Move.NOMOVE; MoveList moves = moveGenerator.getAll(); for (int i = 0; i < moves.size; ++i) { int move = moves.moves[i]; board.makeMove(move); int value = -alphaBeta(depth - 1, -beta, -alpha, height + 1); board.undoMove(move); if (abort) { break; } // Pruning if (value > bestValue) { bestValue = value; bestMove = move; // Do we have a better value? if (value > alpha) { alpha = value; // Is the value higher than beta? if (value >= beta) { // Cut-off break; } } } } // If we cannot move, check for checkmate and stalemate. if (bestValue == -Evaluation.INFINITY) { if (moveGenerator.isCheck()) { // We have a check mate. This is bad for us, so return a -CHECKMATE. bestValue = -Evaluation.CHECKMATE; } else { // We have a stale mate. Return the draw value. bestValue = Evaluation.DRAW; } } if (!abort) { if (height == 1 && bestMove != Move.NOMOVE) { ponderMove = bestMove; } } return bestValue; } }
package com.gitrekt.resort; import com.gitrekt.resort.controller.ScreenManager; import com.gitrekt.resort.hibernate.HibernateUtil; import com.gitrekt.resort.model.entities.GuestFeedback; import com.gitrekt.resort.model.services.EmailService; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javax.mail.MessagingException; import javax.persistence.EntityManager; import javax.persistence.PersistenceException; /** * The main application class shell. */ public class GitRekt extends Application { @Override public void start(Stage mainStage) throws IOException { ScreenManager screenManager = ScreenManager.getInstance(); screenManager.initialize(mainStage); Parent root = FXMLLoader.load(getClass().getResource("/fxml/HomeScreen.fxml")); Scene mainScene = new Scene(root); mainStage.setScene(mainScene); Image appLogo = new Image("images/Logo.png"); mainStage.getIcons().add(appLogo); mainStage.setTitle("Git-Rektsort Booking Software"); mainStage.show(); testHibernate(); //testEmailService(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } // TODO: Remove private void testHibernate() { // This method just stores an entity in the database really quick to // demonstrate Hibernate and verify that it is working and properly // configured. This should be removed later. GuestFeedback feedback = new GuestFeedback("This place sucks.", "mailloux.cl@gmail.com"); EntityManager entityManager = HibernateUtil.getEntityManager(); try { entityManager.getTransaction().begin(); entityManager.persist(feedback); entityManager.getTransaction().commit(); } catch (PersistenceException e) { // If shit hits the fan, rewind it to prevent database problems. entityManager.getTransaction().rollback(); } } // TODO: Remove private void testEmailService() { EmailService emailService = new EmailService(); String messageText = "This is a test email."; try { emailService.sendTestEmail( "mailloux.cl@gmail.com", "Testing email service", messageText ); } catch (MessagingException ex) { ex.printStackTrace(); } } }
package com.mangopay.core; import com.google.gson.*; import com.mangopay.MangoPayApi; import com.mangopay.core.enumerations.PersonType; import com.mangopay.entities.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.*; import java.util.Map.Entry; import java.util.regex.Matcher; /** * Class used to build HTTP request, call the request and handle response. */ public class RestTool { // root/parent instance that holds the OAuthToken and Configuration instance private MangoPayApi root; // enable/disable debugging private Boolean debugMode; // variable to flag that in request authentication data are required private Boolean authRequired; // array with HTTP header to send with request private Map<String, String> requestHttpHeaders; // HTTP communication object private HttpURLConnection connection; // request type for current request private String requestType; // key-value collection pass in the request private Map<String, String> requestData; // code get from response private int responseCode; // pagination object private Pagination pagination; // slf4j logger facade private Logger logger; /** * Instantiates new RestTool object. * * @param root Root/parent instance that holds the OAuthToken and Configuration instance. * @param authRequired Defines whether request authentication is required. * @throws Exception */ public RestTool(MangoPayApi root, Boolean authRequired) throws Exception { this.root = root; this.authRequired = authRequired; this.debugMode = this.root.getConfig().isDebugMode(); logger = LoggerFactory.getLogger(RestTool.class); } /** * Adds HTTP headers as name/value pairs into the request. * * @param httpHeader Collection of headers name/value pairs. */ public void addRequestHttpHeader(Map<String, String> httpHeader) { if (this.requestHttpHeaders == null) this.requestHttpHeaders = new HashMap<>(); this.requestHttpHeaders.putAll(httpHeader); } /** * Adds HTTP header into the request. * * @param key Header name. * @param value Header value. */ public void addRequestHttpHeader(final String key, final String value) { addRequestHttpHeader(new HashMap<String, String>() {{ put(key, value); }}); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting single * <code>Dto</code> instances. In order to process collections of objects, * use <code>requestList</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param urlMethod Relevant method key. * @param requestType HTTP request term, one of the GET, PUT or POST. * @param requestData Collection of key-value pairs of request * parameters. * @param pagination Pagination object. * @param entity Instance of Dto class that is going to be * sent in case of PUTting or POSTing. * @return The Dto instance returned from API. * @throws Exception */ public <T extends Dto> T request(Class<T> classOfT, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination, T entity) throws Exception { return this.request(classOfT, null, urlMethod, requestType, requestData, pagination, entity); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting single * <code>Dto</code> instances. In order to process collections of objects, * use <code>requestList</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param idempotencyKey idempotency key for this request. * @param urlMethod Relevant method key. * @param requestType HTTP request term, one of the GET, PUT or POST. * @param requestData Collection of key-value pairs of request * parameters. * @param pagination Pagination object. * @param entity Instance of Dto class that is going to be * sent in case of PUTting or POSTing. * @return The Dto instance returned from API. * @throws Exception */ public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination, T entity) throws Exception { this.requestType = requestType; this.requestData = requestData; T responseResult = this.doRequest(classOfT, idempotencyKey, urlMethod, pagination, entity); if (pagination != null) { pagination = this.pagination; } return responseResult; } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting single * <code>Dto</code> instances. In order to process collections of objects, * use <code>requestList</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param urlMethod Relevant method key. * @param requestType HTTP request term, one of the GET, PUT or POST. * @return The Dto instance returned from API. * @throws Exception */ public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType) throws Exception { return request(classOfT, idempotencyKey, urlMethod, requestType, null, null, null); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting single * <code>Dto</code> instances. In order to process collections of objects, * use <code>requestList</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param urlMethod Relevant method key. * @param requestType HTTP request term, one of the GET, PUT or POST. * @param requestData Collection of key-value pairs of request * parameters. * @return The Dto instance returned from API. * @throws Exception */ public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType, Map<String, String> requestData) throws Exception { return request(classOfT, idempotencyKey, urlMethod, requestType, requestData, null, null); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting single * <code>Dto</code> instances. In order to process collections of objects, * use <code>requestList</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param urlMethod Relevant method key. * @param requestType HTTP request term, one of the GET, PUT or POST. * @param requestData Collection of key-value pairs of request * parameters. * @param pagination Pagination object. * @return The Dto instance returned from API. * @throws Exception */ public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination) throws Exception { return request(classOfT, idempotencyKey, urlMethod, requestType, requestData, pagination, null); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting collections of * <code>Dto</code> instances. In order to process single objects, * use <code>request</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param classOfTItem The class of single item in array. * @param urlMethod Relevant method key. * @param requestType HTTP request term. For lists should be always GET. * @param requestData Collection of key-value pairs of request * parameters. * @param pagination Pagination object. * @param additionalUrlParams * @return The collection of Dto instances returned from API. * @throws Exception */ public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination, Map<String, String> additionalUrlParams) throws Exception { this.requestType = requestType; this.requestData = requestData; List<T> responseResult = this.doRequestList(classOfT, classOfTItem, urlMethod, pagination, additionalUrlParams); if (pagination != null) { pagination = this.pagination; } return responseResult; } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting collections of * <code>Dto</code> instances. In order to process single objects, * use <code>request</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param classOfTItem The class of single item in array. * @param urlMethod Relevant method key. * @param requestType HTTP request term. For lists should be always GET. * @return The collection of Dto instances returned from API. * @throws Exception */ public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType) throws Exception { return requestList(classOfT, classOfTItem, urlMethod, requestType, null, null, null); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting collections of * <code>Dto</code> instances. In order to process single objects, * use <code>request</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param classOfTItem The class of single item in array. * @param urlMethod Relevant method key. * @param requestType HTTP request term. For lists should be always GET. * @param requestData Collection of key-value pairs of request * parameters. * @return The collection of Dto instances returned from API. * @throws Exception */ public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType, Map<String, String> requestData) throws Exception { return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, null, null); } /** * Makes a call to the MangoPay API. * <p> * This generic method handles calls targeting collections of * <code>Dto</code> instances. In order to process single objects, * use <code>request</code> method instead. * * @param <T> Type on behalf of which the request is being called. * @param classOfT Type on behalf of which the request is being called. * @param classOfTItem The class of single item in array. * @param urlMethod Relevant method key. * @param requestType HTTP request term. For lists should be always GET. * @param requestData Collection of key-value pairs of request * parameters. * @param pagination Pagination object. * @return The collection of Dto instances returned from API. * @throws Exception */ public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination) throws Exception { return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, pagination, null); } private <T extends Dto> T doRequest(Class<T> classOfT, String idempotencyKey, String urlMethod, Pagination pagination, T entity) throws Exception { T response = null; try { UrlTool urlTool = new UrlTool(root); String restUrl = urlTool.getRestUrl(urlMethod, this.authRequired, pagination, null); URL url = new URL(urlTool.getFullUrl(restUrl)); if (this.debugMode) { logger.info("FullUrl: {}", urlTool.getFullUrl(restUrl)); } /* FOR WEB DEBUG PURPOSES SocketAddress addr = new InetSocketAddress("localhost", 8888); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); connection = (HttpURLConnection)url.openConnection(proxy); */ connection = (HttpURLConnection) url.openConnection(); // Get connection timeout from config connection.setConnectTimeout(this.root.getConfig().getConnectTimeout()); // Get read timeout from config connection.setReadTimeout(this.root.getConfig().getReadTimeout()); // set request method connection.setRequestMethod(this.requestType); // set headers Map<String, String> httpHeaders = this.getHttpHeaders(restUrl); for (Entry<String, String> entry : httpHeaders.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); if (this.debugMode) logger.info("HTTP Header: {}", entry.getKey() + ": " + entry.getValue()); } if (idempotencyKey != null && !idempotencyKey.trim().isEmpty()) { connection.addRequestProperty("Idempotency-Key", idempotencyKey); } // prepare to go connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (pagination != null) { this.pagination = pagination; } if (this.debugMode) logger.info("RequestType: {}", this.requestType); if (this.requestData != null || entity != null) { String requestBody = ""; if (entity != null) { HashMap<String, Object> requestData = buildRequestData(classOfT, entity); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); requestData = requestData.trim(); requestBody = gson.toJson(requestData); } if (this.requestData != null) { String params = ""; for (Entry<String, String> entry : this.requestData.entrySet()) { params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); } requestBody = params.replaceFirst("&", ""); } if (this.debugMode) { logger.info("RequestData: {}", this.requestData); logger.info("RequestBody: {}", requestBody); } try (OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) { osw.write(requestBody); osw.flush(); } } // get response this.responseCode = connection.getResponseCode(); InputStream is; if (this.responseCode != 200 && this.responseCode != 204) { is = connection.getErrorStream(); } else { is = connection.getInputStream(); } StringBuffer resp; try (BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { String line; resp = new StringBuffer(); while ((line = rd.readLine()) != null) { resp.append(line); } } String responseString = resp.toString(); if (this.debugMode) { if (this.responseCode == 200 || this.responseCode == 204) { logger.info("Response OK: {}", responseString); } else { logger.info("Response ERROR: {}", responseString); } } if (this.responseCode == 200) { this.readResponseHeaders(connection); response = castResponseToEntity(classOfT, new JsonParser().parse(responseString).getAsJsonObject()); if (this.debugMode) logger.info("Response object: {}", response.toString()); } this.checkResponseCode(responseString); } catch (Exception ex) { //ex.printStackTrace(); if (this.debugMode) logger.error("EXCEPTION: {}", Arrays.toString(ex.getStackTrace())); throw ex; } return response; } private void readResponseHeaders(HttpURLConnection conn) { List<RateLimit> updatedRateLimits = null; for (Map.Entry<String, List<String>> k : conn.getHeaderFields().entrySet()) { for (String v : k.getValue()) { if (this.debugMode) logger.info("Response header: {}", k.getKey() + ":" + v); if (k.getKey() == null) continue; if (k.getKey().equals("X-RateLimit-Remaining")) { if (updatedRateLimits == null) { updatedRateLimits = initRateLimits(); } List<String> callsRemaining = k.getValue(); updatedRateLimits.get(0).setCallsRemaining(Integer.valueOf(callsRemaining.get(3))); updatedRateLimits.get(1).setCallsRemaining(Integer.valueOf(callsRemaining.get(2))); updatedRateLimits.get(2).setCallsRemaining(Integer.valueOf(callsRemaining.get(1))); updatedRateLimits.get(3).setCallsRemaining(Integer.valueOf(callsRemaining.get(0))); } if (k.getKey().equals("X-RateLimit")) { if (updatedRateLimits == null) { updatedRateLimits = initRateLimits(); } List<String> callsMade = k.getValue(); updatedRateLimits.get(0).setCallsMade(Integer.valueOf(callsMade.get(3))); updatedRateLimits.get(1).setCallsMade(Integer.valueOf(callsMade.get(2))); updatedRateLimits.get(2).setCallsMade(Integer.valueOf(callsMade.get(1))); updatedRateLimits.get(3).setCallsMade(Integer.valueOf(callsMade.get(0))); } if (k.getKey().equals("X-RateLimit-Reset")) { if (updatedRateLimits == null) { updatedRateLimits = initRateLimits(); } List<String> resetTimes = k.getValue(); updatedRateLimits.get(0).setResetTimeMillis(Long.valueOf(resetTimes.get(3))); updatedRateLimits.get(1).setResetTimeMillis(Long.valueOf(resetTimes.get(2))); updatedRateLimits.get(2).setResetTimeMillis(Long.valueOf(resetTimes.get(1))); updatedRateLimits.get(3).setResetTimeMillis(Long.valueOf(resetTimes.get(0))); } if (k.getKey().equals("X-Number-Of-Pages")) { this.pagination.setTotalPages(Integer.parseInt(v)); } if (k.getKey().equals("X-Number-Of-Items")) { this.pagination.setTotalItems(Integer.parseInt(v)); } if (k.getKey().equals("Link")) { String linkValue = v; String[] links = linkValue.split(","); if (links != null && links.length > 0) { for (String link : links) { link = link.replaceAll(Matcher.quoteReplacement("<\""), ""); link = link.replaceAll(Matcher.quoteReplacement("\">"), ""); link = link.replaceAll(Matcher.quoteReplacement(" rel=\""), ""); link = link.replaceAll(Matcher.quoteReplacement("\""), ""); String[] oneLink = link.split(";"); if (oneLink != null && oneLink.length > 1) { if (oneLink[0] != null && oneLink[1] != null) { this.pagination.setLinks(oneLink); } } } } } } } if (updatedRateLimits != null) { root.setRateLimits(updatedRateLimits); } } private List<RateLimit> initRateLimits() { return Arrays.asList( new RateLimit(15), new RateLimit(30), new RateLimit(60), new RateLimit(24 * 60)); } private <T extends Dto> HashMap<String, Object> buildRequestData(Class<T> classOfT, T entity) { HashMap<String, Object> result = new HashMap<>(); ArrayList<String> readOnlyProperties = entity.getReadOnlyProperties(); List<Field> fields = getAllFields(entity.getClass()); String fieldName; for (Field f : fields) { f.setAccessible(true); boolean isList = false; for (Class<?> i : f.getType().getInterfaces()) { if (i.getName().equals("java.util.List")) { isList = true; break; } } fieldName = fromCamelCase(f.getName()); if(fieldName.equals("DeclaredUBOs") && classOfT.equals(UboDeclaration.class)) { try { List<DeclaredUbo> declaredUbos = (List<DeclaredUbo>) f.get(entity); List<String> declaredUboIds = new ArrayList<>(); for(DeclaredUbo ubo : declaredUbos) { declaredUboIds.add(ubo.getUserId()); } result.put(fieldName, declaredUboIds.toArray()); } catch (IllegalAccessException e) { if (debugMode) { logger.warn("Failed to build DeclaredUBOs request data", e); } } continue; } boolean isReadOnly = false; for (String s : readOnlyProperties) { if (s.equals(fieldName)) { isReadOnly = true; break; } } if (isReadOnly) continue; if (canReadSubRequestData(classOfT, fieldName)) { HashMap<String, Object> subRequestData = new HashMap<>(); try { Method m = RestTool.class.getDeclaredMethod("buildRequestData", Class.class, Dto.class); subRequestData = (HashMap<String, Object>) m.invoke(this, f.getType(), f.get(entity)); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { if (this.debugMode) logger.error("EXCEPTION: {}", Arrays.toString(ex.getStackTrace())); } for (Entry<String, Object> e : subRequestData.entrySet()) { result.put(e.getKey(), e.getValue()); } } else { try { if (!isList) { result.put(fieldName, f.get(entity)); } else { result.put(fieldName, ((List) f.get(entity)).toArray()); } } catch (IllegalArgumentException | IllegalAccessException ex) { continue; } } } return result; } private List<Field> getAllFields(Class<?> c) { List<Field> fields = new ArrayList<>(); fields.addAll(Arrays.asList(c.getDeclaredFields())); while (c.getSuperclass() != null) { fields.addAll(Arrays.asList(c.getSuperclass().getDeclaredFields())); c = c.getSuperclass(); } return fields; } private <T> Boolean canReadSubRequestData(Class<T> classOfT, String fieldName) { if (classOfT.getName().equals(PayIn.class.getName()) && (fieldName.equals("PaymentDetails") || fieldName.equals("ExecutionDetails"))) { return true; } if (classOfT.getName().equals(PayOut.class.getName()) && fieldName.equals("MeanOfPaymentDetails")) { return true; } if (classOfT.getName().equals(BankAccount.class.getName()) && fieldName.equals("Details")) { return true; } if (classOfT.getName().equals(BankingAlias.class.getName()) && fieldName.equals("Details")) { return true; } return false; } public <T> T castResponseToEntity(Class<T> classOfT, JsonObject response) throws Exception { return castResponseToEntity(classOfT, response, false); } private <T> T castResponseToEntity(Class<T> classOfT, JsonObject response, boolean asDependentObject) throws Exception { try { if (debugMode) { logger.info("Entity type: {}", classOfT.getName()); } if (classOfT.getName().equals(IdempotencyResponse.class.getName())) { // handle the special case here IdempotencyResponse resp = new IdempotencyResponse(); for (Entry<String, JsonElement> entry : response.entrySet()) { if (entry.getKey().equals("StatusCode")) { resp.setStatusCode(entry.getValue().getAsString()); } else if (entry.getKey().equals("ContentLength")) { resp.setContentLength(entry.getValue().getAsString()); } else if (entry.getKey().equals("ContentType")) { resp.setContentType(entry.getValue().getAsString()); } else if (entry.getKey().equals("Date")) { resp.setDate(entry.getValue().getAsString()); } else if (entry.getKey().equals("Resource")) { resp.setResource(entry.getValue().toString()); } else if (entry.getKey().equals("RequestURL")) { resp.setRequestUrl(entry.getValue().toString()); } } return (T) resp; } T result = null; if (classOfT.getName().equals(User.class.getName())) { for (Entry<String, JsonElement> entry : response.entrySet()) { if (entry.getKey().equals("PersonType")) { String userType = entry.getValue().getAsString(); if (userType.equals(PersonType.NATURAL.toString())) { result = (T) new UserNatural(); break; } else if (userType.equals(PersonType.LEGAL.toString())) { result = (T) new UserLegal(); break; } else { throw new Exception(String.format("Unknown type of user: %s", entry.getValue().getAsString())); } } } } else { result = classOfT.newInstance(); } Map<String, Type> subObjects = ((Dto) result).getSubObjects(); Map<String, Map<String, Map<String, Class<?>>>> dependentObjects = ((Dto) result).getDependentObjects(); List<Field> fields = getAllFields(result.getClass()); for (Field f : fields) { f.setAccessible(true); String name = fromCamelCase(f.getName()); boolean isList = false; for (Class<?> i : f.getType().getInterfaces()) { if (i.getName().equals("java.util.List")) { isList = true; break; } } // does this field have dependent objects? if (!asDependentObject && dependentObjects.containsKey(name)) { Map<String, Map<String, Class<?>>> allowedTypes = dependentObjects.get(name); for (Entry<String, JsonElement> entry : response.entrySet()) { if (entry.getKey().equals(name)) { String paymentTypeDef = entry.getValue().getAsString(); if (allowedTypes.containsKey(paymentTypeDef)) { Map<String, Class<?>> targetObjectsDef = allowedTypes.get(paymentTypeDef); for (Entry<String, Class<?>> e : targetObjectsDef.entrySet()) { Field targetField = classOfT.getDeclaredField(toCamelCase(e.getKey())); targetField.setAccessible(true); if (isList) { targetField.set(result, Arrays.asList(castResponseToEntity(e.getValue(), response, true))); } else { targetField.set(result, castResponseToEntity(e.getValue(), response, true)); } } } break; } } } for (Entry<String, JsonElement> entry : response.entrySet()) { if (entry.getKey().equals(name)) { // is sub object? if (subObjects.containsKey(name)) { if (entry.getValue() instanceof JsonNull) { f.set(result, null); } else { f.set(result, castResponseToEntity(f.getType(), entry.getValue().getAsJsonObject())); } break; } String fieldTypeName = f.getType().getName(); boolean fieldIsArray = false; for (Class<?> i : f.getType().getInterfaces()) { if (i.getName().equals("java.util.List")) { fieldIsArray = true; break; } } if (debugMode) { logger.info("Recognized field: {}", String.format("[%s] %s%s", name, fieldTypeName, fieldIsArray ? "[]" : "")); } if (fieldIsArray) { ParameterizedType genericType = (ParameterizedType) f.getGenericType(); Class<?> genericTypeClass = (Class<?>) genericType.getActualTypeArguments()[0]; if (entry.getValue().isJsonArray()) { JsonArray ja = entry.getValue().getAsJsonArray(); Iterator<JsonElement> i = ja.iterator(); Class<?> classOfList = Class.forName(fieldTypeName); Method addMethod = classOfList.getDeclaredMethod("add", Object.class); Object o = classOfList.newInstance(); while (i.hasNext()) { JsonElement e = i.next(); if (genericTypeClass.getName().equals(String.class.getName())) { addMethod.invoke(o, e.getAsJsonPrimitive().getAsString()); } else if (genericTypeClass.getName().equals(int.class.getName()) || genericTypeClass.getName().equals(Integer.class.getName())) { addMethod.invoke(o, e.getAsJsonPrimitive().getAsInt()); } else if (genericTypeClass.getName().equals(long.class.getName()) || genericTypeClass.getName().equals(Long.class.getName())) { addMethod.invoke(o, e.getAsJsonPrimitive().getAsLong()); } else if (genericTypeClass.getName().equals(double.class.getName()) || genericTypeClass.getName().equals(Double.class.getName())) { addMethod.invoke(o, e.getAsJsonPrimitive().getAsDouble()); } else if (genericTypeClass.isEnum()) {// Enumeration, try getting enum by name Class cls = genericTypeClass; Object val = Enum.valueOf(cls, e.getAsJsonPrimitive().getAsString()); addMethod.invoke(o, val); } else if (Dto.class.isAssignableFrom(genericTypeClass)){ addMethod.invoke(o, castResponseToEntity(genericTypeClass, e.getAsJsonObject())); } } f.set(result, o); } } else { if (!entry.getValue().isJsonNull()) { if (fieldTypeName.equals(int.class.getName())) { f.setInt(result, entry.getValue().getAsInt()); } else if (fieldTypeName.equals(Integer.class.getName())) { f.set(result, entry.getValue().getAsInt()); } else if (fieldTypeName.equals(long.class.getName())) { f.setLong(result, entry.getValue().getAsLong()); } else if (fieldTypeName.equals(Long.class.getName())) { f.set(result, entry.getValue().getAsLong()); } else if (fieldTypeName.equals(double.class.getName())) { f.setDouble(result, entry.getValue().getAsDouble()); } else if (fieldTypeName.equals(Double.class.getName())) { f.set(result, entry.getValue().getAsDouble()); } else if (fieldTypeName.equals(String.class.getName())) { f.set(result, entry.getValue().getAsString()); } else if (fieldTypeName.equals(boolean.class.getName())) { f.setBoolean(result, entry.getValue().getAsBoolean()); } else if (fieldTypeName.equals(Boolean.class.getName())) { f.set(result, entry.getValue().getAsBoolean()); } else if (f.getType().isEnum()) {// Enumeration, try getting enum by name Class cls = f.getType(); Object val = Enum.valueOf(cls, entry.getValue().getAsString()); f.set(result, val); } } break; } } } } if (classOfT.getName().equals(Address.class.getName())) { if (!((Address) result).isValid()) result = null; } return result; } catch (Exception e) { if (this.debugMode) logger.error("EXCEPTION: {}", Arrays.toString(e.getStackTrace())); throw e; } } private String toCamelCase(String fieldName) { if (fieldName.toUpperCase().equals(fieldName)) { return fieldName.toLowerCase(); } if (fieldName.equals("KYCLevel")) { return "kycLevel"; } if (fieldName.equals("DeclaredUBOs")) { return "declaredUbos"; } String camelCase = (fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1, fieldName.length())).replace("URL", "Url").replace("AVS", "Avs"); while (camelCase.contains("_")) { int index = camelCase.indexOf("_"); String letterAfter = ("" + camelCase.charAt(index + 1)).toUpperCase(); camelCase = camelCase.substring(0, index) + letterAfter + camelCase.substring(index + 2); } return camelCase; } private String fromCamelCase(String fieldName) { if (fieldName.equals("iban") || fieldName.equals("bic") || fieldName.equals("aba")) { return fieldName.toUpperCase(); } if (fieldName.equals("kycLevel")) { return "KYCLevel"; } if (fieldName.equals("accessToken")) { return "access_token"; } if (fieldName.equals("tokenType")) { return "token_type"; } if (fieldName.equals("expiresIn")) { return "expires_in"; } if (fieldName.equals("url")) { return "Url"; } if (fieldName.equals("declaredUbos")) { return "DeclaredUBOs"; } return (fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1)).replace("Url", "URL").replace("Avs", "AVS"); } private <T extends Dto> List<T> doRequestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, Pagination pagination) throws Exception { return doRequestList(classOfT, classOfTItem, urlMethod, pagination, null); } private <T extends Dto> List<T> doRequestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, Pagination pagination, Map<String, String> additionalUrlParams) throws Exception { List<T> response = new ArrayList<>(); try { UrlTool urlTool = new UrlTool(root); String restUrl = urlTool.getRestUrl(urlMethod, this.authRequired, pagination, additionalUrlParams); URL url = new URL(urlTool.getFullUrl(restUrl)); if (this.debugMode) logger.info("FullUrl: {}", urlTool.getFullUrl(restUrl)); connection = (HttpURLConnection) url.openConnection(); // set request method connection.setRequestMethod(this.requestType); // set headers Map<String, String> httpHeaders = this.getHttpHeaders(restUrl); for (Entry<String, String> entry : httpHeaders.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); if (this.debugMode) logger.info("HTTP Header: {}", entry.getKey() + ": " + entry.getValue()); } // prepare to go connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (pagination != null) { this.pagination = pagination; } if (this.debugMode) logger.info("RequestType: {}", this.requestType); if (this.requestData != null) { String requestBody; String params = ""; for (Entry<String, String> entry : this.requestData.entrySet()) { params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); } requestBody = params.replaceFirst("&", ""); writeRequestBody(connection, requestBody); if (this.debugMode) { logger.info("RequestData: {}", this.requestData); logger.info("RequestBody: {}", requestBody); } } else if (restUrl.contains("consult") && (restUrl.contains("KYC/documents") || restUrl.contains("dispute-documents"))) { writeRequestBody(connection, ""); } //Get Response this.responseCode = connection.getResponseCode(); InputStream is; if (this.responseCode != 200) { is = connection.getErrorStream(); } else { is = connection.getInputStream(); } StringBuffer resp; try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { String line; resp = new StringBuffer(); while ((line = rd.readLine()) != null) { resp.append(line); resp.append('\r'); } } String responseString = resp.toString(); if (this.debugMode) { if (this.responseCode == 200) { logger.info("Response OK: {}", responseString); } else { logger.info("Response ERROR: {}", responseString); } } if (this.responseCode == 200) { this.readResponseHeaders(connection); JsonArray ja = new JsonParser().parse(responseString).getAsJsonArray(); for (int x = 0; x < ja.size(); x++) { JsonObject jo = ja.get(x).getAsJsonObject(); T toAdd = castResponseToEntity(classOfTItem, jo); response.add(toAdd); } if (this.debugMode) { logger.info("Response object: {}", response.toString()); logger.info("Elements count: {}", response.size()); } } this.checkResponseCode(responseString); } catch (Exception ex) { if (this.debugMode) logger.error("EXCEPTION: {}", Arrays.toString(ex.getStackTrace())); throw ex; } return response; } private void writeRequestBody(HttpURLConnection connection, String body) throws IOException { try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.writeBytes(body); wr.flush(); } } /** * Gets HTTP header to use in request. * * @param restUrl The REST API URL. * @return Array containing HTTP headers. */ private Map<String, String> getHttpHeaders(String restUrl) throws Exception { // return if already created... if (this.requestHttpHeaders != null) return this.requestHttpHeaders; // ...or initialize with default headers Map<String, String> httpHeaders = new HashMap<>(); // content type httpHeaders.put("Content-Type", "application/json"); // AuthenticationHelper http header if (this.authRequired) { AuthenticationHelper authHlp = new AuthenticationHelper(root); httpHeaders.putAll(authHlp.getHttpHeaderKey()); } return httpHeaders; } /** * Checks the HTTP response code and if it's neither 200 nor 204 throws a ResponseException. * * @param message Text response. * @throws ResponseException If response code is other than 200 or 204. */ private void checkResponseCode(String message) throws ResponseException { if (this.responseCode != 200 && this.responseCode != 204) { HashMap<Integer, String> responseCodes = new HashMap<Integer, String>() {{ put(206, "PartialContent"); put(400, "Bad request"); put(401, "Unauthorized"); put(403, "Prohibition to use the method"); put(404, "Not found"); put(405, "Method not allowed"); put(413, "Request entity too large"); put(422, "Unprocessable entity"); put(500, "Internal server error"); put(501, "Not implemented"); }}; ResponseException responseException = new ResponseException(message); responseException.setResponseHttpCode(this.responseCode); if (responseCodes.containsKey(this.responseCode)) { responseException.setResponseHttpDescription(responseCodes.get(this.responseCode)); } else { responseException.setResponseHttpDescription("Unknown response error"); } if (message != null) { JsonObject error = new JsonParser().parse(message).getAsJsonObject(); for (Entry<String, JsonElement> entry : error.entrySet()) { switch (entry.getKey().toLowerCase()) { case "message": responseException.setApiMessage(entry.getValue().getAsString()); break; case "type": responseException.setType(entry.getValue().getAsString()); break; case "id": responseException.setId(entry.getValue().getAsString()); break; case "date": responseException.setDate((int) entry.getValue().getAsDouble()); break; case "errors": if (entry.getValue() == null) break; if (entry.getValue().isJsonNull()) break; for (Entry<String, JsonElement> errorEntry : entry.getValue().getAsJsonObject().entrySet()) { if (!responseException.getErrors().containsKey(errorEntry.getKey())) responseException.getErrors().put(errorEntry.getKey(), errorEntry.getValue().getAsString()); else { String description = responseException.getErrors().get(errorEntry.getKey()); description = " | " + errorEntry.getValue().getAsString(); responseException.getErrors().put(errorEntry.getKey(), description); } } break; } } } throw responseException; } } }
package com.percero.util; import java.sql.Timestamp; import java.util.Date; public class DateUtils { public static java.sql.Date utilDateToSqlDate(java.util.Date utilDate) { if (utilDate != null) { return new java.sql.Date(utilDate.getTime()); } else { return null; } } public static Date utilDateFromSqlTimestamp(Timestamp timestamp) { if (timestamp != null) { return new Date(timestamp.getTime()); } return null; } public static Timestamp sqlTimestampFromUtilDate(java.util.Date utilDate){ if(utilDate!=null){ return new Timestamp(utilDate.getTime()); } return null; } }
package com.stanfy.gsonxml; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import com.google.gson.internal.Primitives; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; import com.stanfy.gsonxml.XmlReader.Options; public class GsonXml { /** Core object. */ private final Gson core; /** XML parser creator. */ private final XmlParserCreator xmlParserCreator; /** Option. */ private final Options options; GsonXml(final Gson gson, final XmlParserCreator xmlParserCreator, final Options options) { if (xmlParserCreator == null) { throw new NullPointerException("XmlParserCreator is null"); } this.core = gson; this.xmlParserCreator = xmlParserCreator; this.options = options; } public Gson getGson() { return core; } public <T> T fromXml(final String json, final Class<T> classOfT) throws JsonSyntaxException { final Object object = fromXml(json, (Type) classOfT); return Primitives.wrap(classOfT).cast(object); } @SuppressWarnings("unchecked") public <T> T fromXml(final String json, final Type typeOfT) throws JsonSyntaxException { if (json == null) { return null; } final StringReader reader = new StringReader(json); final T target = (T) fromXml(reader, typeOfT); return target; } public <T> T fromXml(final Reader json, final Class<T> classOfT) throws JsonSyntaxException, JsonIOException { final XmlReader jsonReader = new XmlReader(json, xmlParserCreator, options); // change reader final Object object = fromXml(jsonReader, classOfT); assertFullConsumption(object, jsonReader); return Primitives.wrap(classOfT).cast(object); } @SuppressWarnings("unchecked") public <T> T fromXml(final Reader json, final Type typeOfT) throws JsonIOException, JsonSyntaxException { final XmlReader jsonReader = new XmlReader(json, xmlParserCreator, options); // change reader final T object = (T) fromXml(jsonReader, typeOfT); assertFullConsumption(object, jsonReader); return object; } private static void assertFullConsumption(final Object obj, final JsonReader reader) { try { if (obj != null && reader.peek() != JsonToken.END_DOCUMENT) { throw new JsonIOException("JSON document was not fully consumed."); } } catch (final MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (final IOException e) { throw new JsonIOException(e); } } /** * Reads the next JSON value from {@code reader} and convert it to an object * of type {@code typeOfT}. * Since Type is not parameterized by T, this method is type unsafe and should be used carefully * * @throws JsonIOException if there was a problem writing to the Reader * @throws JsonSyntaxException if json is not a valid representation for an object of type */ public <T> T fromXml(final XmlReader reader, final Type typeOfT) throws JsonIOException, JsonSyntaxException { return core.fromJson(reader, typeOfT); } @Override public String toString() { return core.toString(); } }
package com.stuonline.utils; public class Images { public static final String[] imageUrls=new String[]{ "http://p2.so.qhimg.com/t013bb71a2f30431c82.jpg", "http://p2.so.qhimg.com/t0128499e54414cd142.jpg", "http://p2.so.qhimg.com/t01ac1dc41960f791d7.jpg", "http://p0.so.qhimg.com/t01f7ba592e4c15632f.jpg", "http://p2.so.qhimg.com/t01100898142d4c38c7.jpg", "http://p3.so.qhimg.com/t018a0a63f9ad604083.jpg", "http://p2.so.qhimg.com/t01e85ecccf735a230c.jpg", "http://p1.so.qhimg.com/t01317abd787457c88b.jpg", "http://p3.so.qhimg.com/t01613f0d469bbe4c23.jpg", "http://p1.so.qhimg.com/t018c46a3c4be21c696.jpg", "http://p3.so.qhimg.com/t01ddfc5427975ee8d8.jpg", "http://p2.so.qhimg.com/t011537e9d141ba0322.jpg", "http://p0.so.qhimg.com/t01dcd6ef5d1568207f.jpg", "http://p3.so.qhimg.com/t010f767db65e212443.jpg", "http://p1.so.qhimg.com/t01f8a86362ec073d66.jpg", "http://p1.so.qhimg.com/t01a3f16c4c700cc4f1.jpg", "http://p2.so.qhimg.com/t01c040369a554580ac.jpg", "http://p1.so.qhimg.com/t011e107f5d4a699c41.jpg", "http://p3.so.qhimg.com/t015cfe501583ccdef8.jpg", "http://p1.so.qhimg.com/t017d58ea5a10984531.jpg", "http://p4.so.qhimg.com/t019f90fc1793a37964.jpg", "http://p2.so.qhimg.com/t0108171674d6629c5c.jpg", "http://p3.so.qhimg.com/t015e582a99e458834d.jpg", "http://p1.so.qhimg.com/t01f5e7ee80f0c3d481.jpg", "http://p0.so.qhimg.com/t01362a161523d0c385.jpg", "http://p3.so.qhimg.com/t01e664cb18e89204ed.jpg", "http://p3.so.qhimg.com/t01e2cf1aa2453b47b8.jpg", "http://p3.so.qhimg.com/t010ca6e35d940c7bb8.jpg", "http://p4.so.qhimg.com/t0128f3bf87aae0d199.jpg", "http://p0.so.qhimg.com/t01a8caf0911a4f485a.jpg", "http://p4.so.qhimg.com/t01e41c1d04327b9314.jpg", "http://p2.so.qhimg.com/t0149c7f8a88c679032.jpg", "http://p3.so.qhimg.com/t01901c451c3556a283.jpg", "http://p3.so.qhimg.com/t010fdce3595f0c72bd.jpg", "http://p1.so.qhimg.com/t0134fa4403144bbc8b.jpg", "http://p0.so.qhimg.com/t01af9cf943d225bc0f.jpg", "http://p1.so.qhimg.com/t0195bb470d93a2870b.jpg", "http://p1.so.qhimg.com/t015ea10d2324e69c1b.jpg", "http://p2.so.qhimg.com/t0108171674d6629c5c.jpg", "http://p2.so.qhimg.com/t010555de030e5a697c.jpg", "http://p0.so.qhimg.com/t0185f7b0e19056ae45.jpg", "http://p0.so.qhimg.com/t0114e4c892cd09053a.jpg", "http://p1.so.qhimg.com/t01980f97779b3261db.jpg", "http://p0.so.qhimg.com/t01af3a44abdeacda7f.jpg", "http://p0.so.qhimg.com/t01010fee16bcc2a75a.jpg", "http://p4.so.qhimg.com/t01bbf9a70218efc1ce.jpg", "http://p1.so.qhimg.com/t012041b4de40fa3d51.jpg", "http://p0.so.qhimg.com/t0152b700cd4dd80a6f.jpg", "http://p2.so.qhimg.com/t01c68e11466c9d4e2c.jpg", "http://p3.so.qhimg.com/t01ab7702915055b7f3.jpg", "http://p1.so.qhimg.com/t0107c6432486bdc7b1.jpg", "http://p3.so.qhimg.com/t01ab0954855296cd58.jpg", "http://p1.so.qhimg.com/t015b03aaf549b48b5b.jpg", "http://p0.so.qhimg.com/t012d4b7d3ffb1897ff.jpg", "http://p2.so.qhimg.com/t0142493cd54dad6677.jpg", "http://p2.so.qhimg.com/t01b2c879f6b27e5c02.jpg", "http://p4.so.qhimg.com/t01f4a39ce56961c049.jpg", "http://p2.so.qhimg.com/t01c040369a554580ac.jpg", "http://p1.so.qhimg.com/t011e107f5d4a699c41.jpg", "http://p3.so.qhimg.com/t015cfe501583ccdef8.jpg", "http://p1.so.qhimg.com/t017d58ea5a10984531.jpg", "http://p4.so.qhimg.com/t019f90fc1793a37964.jpg", "http://p2.so.qhimg.com/t0108171674d6629c5c.jpg", "http://p3.so.qhimg.com/t015e582a99e458834d.jpg", "http://p1.so.qhimg.com/t01f5e7ee80f0c3d481.jpg", "http://p0.so.qhimg.com/t01362a161523d0c385.jpg", "http://p3.so.qhimg.com/t01e664cb18e89204ed.jpg", "http://p3.so.qhimg.com/t01e2cf1aa2453b47b8.jpg", "http://p3.so.qhimg.com/t010ca6e35d940c7bb8.jpg", "http://p4.so.qhimg.com/t0128f3bf87aae0d199.jpg", "http://p0.so.qhimg.com/t01a8caf0911a4f485a.jpg", "http://p4.so.qhimg.com/t01e41c1d04327b9314.jpg", "http://p2.so.qhimg.com/t0149c7f8a88c679032.jpg", "http://p3.so.qhimg.com/t01901c451c3556a283.jpg", "http://p3.so.qhimg.com/t010fdce3595f0c72bd.jpg", "http://p1.so.qhimg.com/t0134fa4403144bbc8b.jpg", "http://p0.so.qhimg.com/t01af9cf943d225bc0f.jpg", "http://p1.so.qhimg.com/t0195bb470d93a2870b.jpg", "http://p1.so.qhimg.com/t015ea10d2324e69c1b.jpg", "http://p2.so.qhimg.com/t0108171674d6629c5c.jpg", "http://p2.so.qhimg.com/t010555de030e5a697c.jpg", "http://p0.so.qhimg.com/t0185f7b0e19056ae45.jpg", "http://p0.so.qhimg.com/t0114e4c892cd09053a.jpg", "http://p1.so.qhimg.com/t01980f97779b3261db.jpg", "http://p0.so.qhimg.com/t01af3a44abdeacda7f.jpg", "http://p0.so.qhimg.com/t01010fee16bcc2a75a.jpg", "http://p4.so.qhimg.com/t01bbf9a70218efc1ce.jpg", "http://p1.so.qhimg.com/t012041b4de40fa3d51.jpg", "http://p0.so.qhimg.com/t0152b700cd4dd80a6f.jpg", "http://p2.so.qhimg.com/t01c68e11466c9d4e2c.jpg", "http://p3.so.qhimg.com/t01ab7702915055b7f3.jpg", "http://p1.so.qhimg.com/t0107c6432486bdc7b1.jpg", "http://p3.so.qhimg.com/t01ab0954855296cd58.jpg", "http://p1.so.qhimg.com/t015b03aaf549b48b5b.jpg", "http://p0.so.qhimg.com/t012d4b7d3ffb1897ff.jpg", "http://p2.so.qhimg.com/t0142493cd54dad6677.jpg", "http://p2.so.qhimg.com/t01b2c879f6b27e5c02.jpg", "http://p4.so.qhimg.com/t01f4a39ce56961c049.jpg", "http://p2.so.qhimg.com/t01c040369a554580ac.jpg", "http://p1.so.qhimg.com/t011e107f5d4a699c41.jpg", "http://p3.so.qhimg.com/t015cfe501583ccdef8.jpg", "http://p1.so.qhimg.com/t017d58ea5a10984531.jpg", "http://p4.so.qhimg.com/t019f90fc1793a37964.jpg", "http://p2.so.qhimg.com/t0108171674d6629c5c.jpg", "http://p3.so.qhimg.com/t015e582a99e458834d.jpg", "http://p1.so.qhimg.com/t01f5e7ee80f0c3d481.jpg", "http://p0.so.qhimg.com/t01362a161523d0c385.jpg", "http://p3.so.qhimg.com/t01e664cb18e89204ed.jpg", "http://p3.so.qhimg.com/t01e2cf1aa2453b47b8.jpg", "http://p3.so.qhimg.com/t010ca6e35d940c7bb8.jpg", "http://p4.so.qhimg.com/t0128f3bf87aae0d199.jpg", "http://p0.so.qhimg.com/t01a8caf0911a4f485a.jpg", "http://p4.so.qhimg.com/t01e41c1d04327b9314.jpg", "http://p2.so.qhimg.com/t0149c7f8a88c679032.jpg", "http://p3.so.qhimg.com/t01901c451c3556a283.jpg", "http://p3.so.qhimg.com/t010fdce3595f0c72bd.jpg", "http://p1.so.qhimg.com/t0134fa4403144bbc8b.jpg", "http://p0.so.qhimg.com/t01af9cf943d225bc0f.jpg", "http://p1.so.qhimg.com/t0195bb470d93a2870b.jpg", "http://p1.so.qhimg.com/t015ea10d2324e69c1b.jpg", "http://p2.so.qhimg.com/t0108171674d6629c5c.jpg", "http://p2.so.qhimg.com/t010555de030e5a697c.jpg", "http://p0.so.qhimg.com/t0185f7b0e19056ae45.jpg" }; }
package com.tacs.deathlist; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.core.Response; @Path("/{username}") public class Usuario { @PathParam("username") private String username; public Usuario() { } @GET @Produces("text/plain") public String getUsername() { System.out.format("Entró a getUsername en Usuario con: %s%n",username); return username; } @GET @Path("/list/{listName}") @Produces("text/plain") public Response getList(@PathParam("listName") String listName) { System.out.format("Entró a getList en Usuario con: %s%n",listName); return Response.status(Response.Status.OK).build(); } @POST @Path("/list/{listName}") @Consumes("text/plain") public void createList(@PathParam("listName") String listName) { System.out.format("Entró a createList en Usuario con: %s%n",listName); } }
package dk.itu.kelvin.layout; // General utilities import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; // JavaFX scene utilities import javafx.scene.Group; import javafx.scene.Scene; // JavaFX shape utilities import javafx.scene.control.Label; import javafx.scene.shape.Rectangle; // JavaFX geometry utilities import javafx.geometry.Bounds; import javafx.geometry.Point2D; // Fast utils import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; // Math import dk.itu.kelvin.math.Haversine; import dk.itu.kelvin.math.Mercator; import dk.itu.kelvin.math.Projection; // Controllers import dk.itu.kelvin.controller.ChartController; // Models import dk.itu.kelvin.model.Address; import dk.itu.kelvin.model.BoundingBox; import dk.itu.kelvin.model.Element; import dk.itu.kelvin.model.Node; // Stores import dk.itu.kelvin.store.ElementStore; /** * Chart class for handling which elements to display and where. * * <p> * This class functions as the canvas for all map specific elements, while the * extension to {@link Group} allows for addition and removal of elements. * * <p> * Aside from being able to add regular {@code JavaFX} elements, additional * methods have been added to allow for adding our own data model. * * {@link Chart} constructor takes no parameters, adding initial layers elements * to the chart. */ public final class Chart extends Group { /** * Maximum zoom factor. */ private static final double MAX_ZOOM_FACTOR = 4; /** * Minimum zoom factor. */ private static final double MIN_ZOOM_FACTOR = 0.5; /** * The size of each tile in the chart. */ private static int tileSize = 256; /** * Stores all elements. */ private ElementStore elementStore; /** * Keep track of the tiles currently showing. */ private Map<Anchor, Group> showing = new Object2ObjectOpenHashMap<>(); /** * Keep track of the tiles of POI currently showing. */ private Map<Anchor, Group> showingPOI = new Object2ObjectOpenHashMap<>(); /** * HashSet representing the POI tags currently being shown on the map. */ private Set<String> activeTags = new ObjectOpenHashSet<>(); /** * HashSet representing the POI tags that is selected by the user. */ private Set<String> currentTags = new ObjectOpenHashSet<>(); /** * Current smallest x-coordinate of the chart viewport. */ private int minX; /** * Current smallest y-coordinate of the chart viewport. */ private int minY; /** * Current largest x-coordinate of the chart viewport. */ private int maxX; /** * Current largest y-coordinate of the chart viewport. */ private int maxY; /** * Layer of land elements. */ private Group landLayer = new Group(); /** * Layer of meta elements. */ private Group metaLayer = new Group(); /** * The width of the map. */ private double mapWidth; /** * The height of the map. */ private double mapHeight; /** * A unit for how many pixel it takes to stretch 1 meter. */ private double unitPrM; /** * The bounds of the chart. */ private BoundingBox bounds; /** * Initialize the chart. */ public Chart() { this.getChildren().addAll(this.landLayer, this.metaLayer); } /** * Setter for the element store field. * @param elementStore the element store object. */ public void elementStore(final ElementStore elementStore) { this.elementStore = elementStore; } /** * Add bounds to the chart. * * @param bounds The bounds to add to the chart. */ public void bounds(final BoundingBox bounds) { if (bounds == null) { return; } this.bounds = bounds; this.mapWidth = Math.abs(bounds.maxX() - bounds.minX()); this.mapHeight = Math.abs(bounds.maxY() - bounds.minY()); double centerX = bounds.minX() + (this.mapWidth / 2); double centerY = bounds.minY() + (this.mapHeight / 2); Node centerNode = new Node(centerX, centerY); // The 10.000 is default padding to ensure it still works for really small // maps with coastlines. double paddingX = 10000 + this.mapWidth; double paddingY = 10000 + this.mapHeight; Rectangle wrapper = new Rectangle( bounds.minX() - paddingX, bounds.minY() - paddingY, this.mapWidth + paddingX * 2, this.mapHeight + paddingY * 2 ); wrapper.getStyleClass().add("wrapper"); if (this.getChildren().contains(wrapper)) { this.getChildren().remove(wrapper); } this.getChildren().add(wrapper); this.landLayer.setClip(bounds.render()); Projection mp = new Mercator(); double mapLength = Haversine.distance( mp.yToLat(bounds.minY()), mp.xToLon(bounds.minX()), mp.yToLat(bounds.minY()), mp.xToLon(bounds.maxX()) ) * 1000; double unitPrPx = mapLength / (this.mapWidth / 100); this.unitPrM = 100 / unitPrPx; this.center(centerNode, this.getMapScale()); } /** * Calculates the appropriate scale for the map and window size, with the * intent see the whole map. * @return the scale needed to see the whole map. */ private double getMapScale() { double scaleX = this.mapWidth / this.getScene().getWidth(); double scaleY = this.mapHeight / this.getScene().getHeight(); double scaleMax = Math.max(scaleX, scaleY); return 1 / scaleMax; } /** * Gets the elementStore of all elements. * @return the elementStore. */ public ElementStore getElementStore() { return this.elementStore; } /** * Gets the bounds BoundingBox of the map. * @return the bounds. */ public BoundingBox getBounds() { return this.bounds; } /** * Pan the chart. * * @param x The amount to pan on the x-axis. * @param y The amount to pan on the y-axis. */ public void pan(final double x, final double y) { this.setTranslateX(this.getTranslateX() + x); this.setTranslateY(this.getTranslateY() + y); this.layoutTiles(); } /** * Center the chart on the specified scene coordinate. * * @param x The x-coordinate to center on. * @param y The y-coordinate to center on. */ public void center(final double x, final double y) { this.pan( -(x - this.getScene().getWidth() / 2), -(y - this.getScene().getHeight() / 2) ); } /** * Center the chart on the specified scene coordinate. * * @param x The x-coordinate to center on. * @param y The y-coordinate to center on. * @param scale The scale to set after centering. */ public void center(final double x, final double y, final double scale) { this.setScale(scale); this.center(x, y); } /** * Center the chart on the specified node. * * @param node The node to center on. */ public void center(final Node node) { this.center( this.localToScene(node.x(), node.y()).getX(), this.localToScene(node.x(), node.y()).getY() ); } /** * Center the chart on the specified node. * * @param node The node to center on. * @param scale The scale to set after centering. */ public void center(final Node node, final double scale) { this.setScale(scale); this.center(node); } /** * Center the chart on the specified address. * * @param address The address to center on. */ public void center(final Address address) { this.center( this.localToScene(address.x(), address.y()).getX(), this.localToScene(address.x(), address.y()).getY() ); } /** * Center the chart on the specified address. * * @param address The address to center on. * @param scale The scale to set after centering. */ public void center(final Address address, final double scale) { this.setScale(scale); this.center(address); } /** * Centering chart on two addresses and adjust the scale. * @param addr1 the from address. * @param addr2 the destination address. */ public void center(final Address addr1, final Address addr2) { double deltaX = addr2.x() - addr1.x(); double deltaY = addr2.y() - addr1.y(); Node center = new Node(addr1.x() + (deltaX / 2), addr1.y() + (deltaY / 2)); double paddingX = 50; double paddingY = 200; double xDist = paddingX + Math.abs(addr1.x() - addr2.x()); double yDist = paddingY + Math.abs(addr1.y() - addr2.y()); double scaleX = xDist / this.getScene().getWidth(); double scaleY = yDist / this.getScene().getHeight(); double scaleMax = Math.max(scaleX, scaleY); if (1 / scaleMax < MIN_ZOOM_FACTOR) { this.center(addr1, MIN_ZOOM_FACTOR); } else { this.center(center, 1 / scaleMax); } } /** * Zoom the chart. * * @param factor The factor with which to zoom. * @param x The x-coordinate of the pivot point. * @param y The y-coordinate of the pivot point. */ public void zoom(final double factor, final double x, final double y) { double oldScale = this.getScaleX(); double newScale = oldScale * factor; if (factor > 1 && newScale >= MAX_ZOOM_FACTOR) { return; } if (factor < 1 && newScale < MIN_ZOOM_FACTOR) { return; } this.setScale(newScale); // Calculate the difference between the new and the old scale. double f = (newScale / oldScale) - 1; // Get the layout bounds of the chart in local coordinates. Bounds bounds = this.localToScene(this.getLayoutBounds()); double dx = x - (bounds.getMinX() + bounds.getWidth() / 2); double dy = y - (bounds.getMinY() + bounds.getHeight() / 2); this.setTranslateX(this.getTranslateX() - f * dx); this.setTranslateY(this.getTranslateY() - f * dy); this.layoutTiles(); } /** * Zoom the chart, using the center of the scene as the pivot point. * * @param factor The factor with which to zoom. */ public void zoom(final double factor) { this.zoom( factor, this.getScene().getWidth() / 2, this.getScene().getHeight() / 2 ); } /** * Sets a specific scale on both x and y. * @param scale the scale to set. */ private void setScale(final double scale) { if (scale <= MIN_ZOOM_FACTOR) { this.setScaleX(MIN_ZOOM_FACTOR); this.setScaleY(MIN_ZOOM_FACTOR); } else if (scale >= MAX_ZOOM_FACTOR) { this.setScaleX(MAX_ZOOM_FACTOR); this.setScaleY(MAX_ZOOM_FACTOR); } else { this.setScaleX(scale); this.setScaleY(scale); } ChartController.setScaleLength(this.unitPrM * this.getScaleX()); } /** * Layout the tiles of the chart. */ private void layoutTiles() { Scene scene = this.getScene(); if (scene == null) { return; } Point2D min = this.sceneToLocal(0, 0); Point2D max = this.sceneToLocal(scene.getWidth(), scene.getHeight()); int minX = (int) (this.tileSize * Math.floor(min.getX() / this.tileSize)); int minY = (int) (this.tileSize * Math.floor(min.getY() / this.tileSize)); int maxX = (int) (this.tileSize * Math.floor(max.getX() / this.tileSize)); int maxY = (int) (this.tileSize * Math.floor(max.getY() / this.tileSize)); this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; Set<Anchor> anchors = new ObjectOpenHashSet<>(); for (int x = minX; x <= maxX; x += this.tileSize) { for (int y = minY; y <= maxY; y += this.tileSize) { anchors.add(new Anchor(x, y)); } } Iterator<Anchor> it = this.showing.keySet().iterator(); while (it.hasNext()) { Anchor anchor = it.next(); if (anchors.contains(anchor)) { continue; } this.hide(anchor); it.remove(); } for (Anchor anchor: anchors) { if (this.showing.containsKey(anchor)) { continue; } this.show(anchor); } it = this.showingPOI.keySet().iterator(); while (it.hasNext()) { Anchor anchor = it.next(); if (anchors.contains(anchor)) { if ( this.activeTags.containsAll(this.currentTags) && this.activeTags.size() == this.currentTags.size() ) { continue; } } this.hidePOI(anchor); it.remove(); } for (Anchor anchor: anchors) { if (this.showingPOI.containsKey(anchor)) { if ( this.activeTags.containsAll(this.currentTags) && this.activeTags.size() == this.currentTags.size() ) { continue; } } this.showPOI(anchor); } } /** * Sets visibility for labels attached to a unique type of POI. * * @param tag unique type of POI. */ public void showSelectedPoi(final String tag) { this.currentTags.add(tag); this.layoutTiles(); } /** * Remove visibility for labels attached to a unique type of POI. * * @param tag unique key in POI. */ public void hidePointsOfInterests(final String tag) { this.currentTags.remove(tag); this.layoutTiles(); } /** * Shows all current POI on a specific anchor. * @param anchor the anchor to show. */ private void showPOI(final Anchor anchor) { if (anchor == null) { return; } int x = anchor.x; int y = anchor.y; Group group = new Group(); for (String tag: this.currentTags) { List<Element> elements = this.elementStore.find() .types("poi") .tag(tag) .bounds(this.minX, this.minY, this.maxX + this.tileSize, this.maxY + this.tileSize) .get(); for (Element element: elements) { Node node = (Node) element; Label label = node.render(); group.getChildren().add(label); } } group.setClip(new Rectangle(x, y, this.tileSize, this.tileSize)); group.setCache(true); this.metaLayer.getChildren().add(group); this.activeTags = new ObjectOpenHashSet<>(this.currentTags); this.showingPOI.put(anchor, group); } /** * Hides a specific anchor of POI. * @param anchor The anchor to hide. */ private void hidePOI(final Anchor anchor) { if (anchor == null) { return; } Group group = this.showingPOI.get(anchor); this.metaLayer.getChildren().remove(group); } /** * Show the specified anchor. * * @param anchor The anchor to show. */ private void show(final Anchor anchor) { if (anchor == null) { return; } int x = anchor.x; int y = anchor.y; List<Element> elements = this.elementStore.find() .types("land", "way", "relation", "transportWay") .bounds(x, y, x + this.tileSize, y + this.tileSize) .get(); if (elements.isEmpty()) { return; } Collections.sort(elements, Element.COMPARATOR); Group group = new Group(); group.setClip(new Rectangle(x, y, this.tileSize, this.tileSize)); group.setCache(true); for (Element element: elements) { group.getChildren().add(element.render()); } this.landLayer.getChildren().add(group); this.showing.put(anchor, group); } /** * Hide the specified anchor. * * @param anchor The anchor to hide. */ private void hide(final Anchor anchor) { if (anchor == null) { return; } Group group = this.showing.get(anchor); this.landLayer.getChildren().remove(group); } /** * Removes children from layers and sets collections to null. */ public void clear() { this.landLayer.getChildren().clear(); this.metaLayer.getChildren().clear(); this.showing.clear(); this.showingPOI.clear(); this.elementStore = new ElementStore(); this.currentTags.clear(); } /** * The {@link Anchor} class describes an anchor point for a group of elements * within the chart. */ private static class Anchor { /** * The x-coordinate of the anchor. */ private int x; /** * The y-coordinate of the anchor. */ private int y; /** * Initialize a new anchor. * * @param x The x-coordinate of the anchor. * @param y The y-coordinate of the anchor. */ public Anchor(final int x, final int y) { this.x = x; this.y = y; } /** * Check if the anchor equals the specified object. * * @param object The object to compare the anchor to. * @return A boolean indicating whether or not the anchor is equal to * The specified object. */ public boolean equals(final Object object) { if (object == null || !(object instanceof Anchor)) { return false; } if (object == this) { return true; } Anchor anchor = (Anchor) object; return anchor.x == this.x && anchor.y == this.y; } /** * Compute the hash code of the anchor. * * @return The hash code of the anchor. */ public int hashCode() { long bits = 7L; bits = 31L * bits + this.x; bits = 31L * bits + this.y; return (int) (bits ^ (bits >> 32)); } } }
package fr.jrds.snmpcodec; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.snmp4j.smi.OID; import org.snmp4j.smi.Variable; import fr.jrds.snmpcodec.smi.Index; import fr.jrds.snmpcodec.smi.ObjectType; import fr.jrds.snmpcodec.smi.Syntax; import fr.jrds.snmpcodec.smi.Trap; public abstract class MibStore { public final OidTreeNode top; public final Map<String, List<OidTreeNode>> names; public final Map<String, Syntax> syntaxes; public final Map<OidTreeNode, ObjectType> objects ; public final Map<OidTreeNode, Map<Integer, Trap>> resolvedTraps; public final Set<String> modules; protected MibStore(OidTreeNode top, Set<String> modules, Map<String, List<OidTreeNode>> names, Map<String, Syntax> syntaxes, Map<OidTreeNode, ObjectType> objects, Map<OidTreeNode, Map<Integer, Trap>> _resolvedTraps) { this.syntaxes = Collections.unmodifiableMap(syntaxes); this.objects = Collections.unmodifiableMap(objects); this.resolvedTraps = Collections.unmodifiableMap(_resolvedTraps); this.modules = Collections.unmodifiableSet(modules); this.names = Collections.unmodifiableMap(names); this.top = top; } /** * Try to resolve the OID as a map. * <p>If the OID is a table entry, the map is {@link java.util.LinkedHashMap LinkedHashMap}. The keys are * the table name, followed by column name. The values are the current column name followed by the index * values.</p> * If the OID is a single value, both the map's key and value contains the name of the OID. * @param oid * @return */ public Map<String, Object> parseIndexOID(int[] oid) { OidTreeNode found = top.search(oid); if(found == null) { return Collections.emptyMap(); } Map<String, Object> parts; int[] foundOID = found.getElements(); if(foundOID.length < oid.length ) { //The full path was not found, try to resolve the suffix as a value // It's not a table, MIB module missing, abort // Table check is needed, some broken implementations starts tables at index 0 (not allowed in RFC) if (found.getTableEntry() == null) { if (foundOID.length == oid.length - 1 && oid[oid.length - 1] == 0) { // Hey of course it was not a table, it was a oid value return Collections.singletonMap(found.getSymbol(), found.getSymbol()); } else { return Collections.singletonMap(found.getSymbol(), Arrays.copyOfRange(oid, foundOID.length, oid.length)); } } parts = new LinkedHashMap<>(); parts.put(found.getTableEntry().getSymbol(), found.getSymbol()); OidTreeNode parent = top.find(Arrays.copyOf(foundOID, foundOID.length -1 )); if (parent != null) { ObjectType parentCodec = objects.get(parent); if(parentCodec.isIndexed()) { Index idx = parentCodec.getIndex(); int[] index = Arrays.copyOfRange(oid, foundOID.length, oid.length); idx.resolve(index, this).forEach((i,j) -> parts.put(i, j)); } } } else { parts = Collections.singletonMap(found.getSymbol(), found.getSymbol()); } return parts; } public boolean containsKey(String text) { return names.containsKey(text); } public int[] getFromName(String text) { if (names.containsKey(text)) { for(OidTreeNode s: names.get(text)) { return s.getElements(); } } return null; } public String format(OID instanceOID, Variable variable) { OidTreeNode s = top.find(instanceOID.getValue()); if (s == null) { return null; } else if (resolvedTraps.containsKey(s)) { Trap trap = resolvedTraps.get(s).get(variable.toInt()); if (trap == null) { return null; } else { return trap.name; } } else if (objects.containsKey(s)) { ObjectType ot = objects.get(s); return ot.format(variable); } return null; } public Variable parse(OID instanceOID, String text) { OidTreeNode node = top.search(instanceOID.getValue()); if (node == null) { return null; } else if (syntaxes.containsKey(node.getSymbol())) { return syntaxes.get(node.getSymbol()).parse(text); } return null; } }
package com.axiastudio.zoefx.core.db; import com.axiastudio.zoefx.core.Utilities; import com.axiastudio.zoefx.core.view.Model; import javafx.beans.property.Property; import java.util.HashMap; import java.util.List; import java.util.Map; public class DataSet<E> { private List<E> store; private Integer currentIndex; private Model<E> currentModel=null; private Map<Property, Object> changes = new HashMap(); private Boolean dirty=Boolean.FALSE; public DataSet(List<E> store) { this.store = store; goFirst(); } public void setStore(List<E> store) { this.store = store; goFirst(); changes.clear(); dirty = Boolean.FALSE; } public Integer getCurrentIndex() { return currentIndex; } public Model<E> newModel() { E entity = store.get(currentIndex); currentModel = new Model(entity); return currentModel; } public Model<E> getCurrentModel() { return currentModel; } public void goFirst() { currentIndex = 0; } public void goLast() { currentIndex = store.size()-1; } public void goNext() { if( currentIndex < store.size()-1 ){ currentIndex++; } } public void goPrevious() { if( currentIndex>0 ){ currentIndex } } public Integer size() { return store.size(); } public Boolean isDirty() { return dirty; } public void getDirty() { dirty = Boolean.TRUE; } public void addChange(Property property, Object oldValue, Object newValue){ if( !changes.keySet().contains(property) ){ changes.put(property, oldValue); getDirty(); } } public void revert() { for( Property property: changes.keySet() ){ property.setValue(changes.get(property)); } changes.clear(); dirty = Boolean.FALSE; } public void commit() { Database db = Utilities.queryUtility(Database.class); if( db != null ) { Manager<E> manager = db.createManager(getEntityClass()); E entity = store.get(currentIndex); manager.commit(entity); } changes.clear(); dirty = Boolean.FALSE; } private Class<E> getEntityClass() { return (Class<E>) store.get(0).getClass(); } public void create() { Database db = Utilities.queryUtility(Database.class); if( db != null ) { Manager<E> manager = db.createManager(getEntityClass()); E entity = manager.create(); store.add(entity); } else { try { E entity = getEntityClass().newInstance(); store.add(entity); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } goLast(); } public void delete() { } }